diff --git a/.gitignore b/.gitignore index c027f5873c8..db8e29d903a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,5 @@ node_modules/ built/* -tests/cases/*.js -tests/cases/*/*.js -tests/cases/*/*/*.js -tests/cases/*/*/*/*.js -tests/cases/*/*/*/*/*.js -tests/cases/*.js.map -tests/cases/*/*.js.map -tests/cases/*/*/*.js.map -tests/cases/*/*/*/*.js.map -tests/cases/*/*/*/*/*.js.map tests/cases/rwc/* tests/cases/test262/* tests/cases/perf/* @@ -38,9 +28,9 @@ build.json *.actual tests/webhost/*.d.ts tests/webhost/webtsc.js -tests/*.js -tests/*.js.map -tests/*.d.ts +tests/cases/**/*.js +tests/cases/**/*.js.map +tests/cases/**/*.d.ts *.config scripts/debug.bat scripts/run.bat diff --git a/.travis.yml b/.travis.yml index 03e319f6b16..b31d1f10da0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,7 @@ language: node_js node_js: + - 'stable' - '4' - '0.10' diff --git a/AUTHORS.md b/AUTHORS.md index 0ade4c31221..0501514d758 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -2,69 +2,104 @@ TypeScript is authored by: * Adam Freidin * Ahmad Farid +* Akshar Patel * Anders Hejlsberg * Arnav Singh * Arthur Ozga +* Asad Saeeduddin * Basarat Ali Syed * Ben Duffield * Bill Ticehurst +* Brett Mayen * Bryan Forbes * Caitlin Potter * Chris Bubernak * Colby Russell * Colin Snover * Cyrus Najmabadi +* Dan Corder * Dan Quirk * Daniel Rosenwasser +* @dashaus * David Li -* Dick van den Brink -* Dirk Bäumer +* Denis Nedelyaev +* Dick van den Brink +* Dirk Bäumer +* Dirk Holtwick +* Eyas Sharaiha +* @falsandtru * Frank Wallis * Gabriel Isenberg * Gilad Peleg +* Graeme Wicksted * Guillaume Salles +* Guy Bedford * Harald Niesche +* Iain Monro * Ingvar Stepanyan * Ivo Gabe de Wolff * James Whitney * Jason Freeman +* Jason Killian * Jason Ramsay * Jed Mao +* Jeffrey Morlan * Johannes Rieken +* John Vilk * Jonathan Bond-Caron * Jonathan Park * Jonathan Turner +* Jonathon Smith * Josh Kalderimis +* Julian Williams * Kagami Sascha Rosylight * Keith Mashinter +* Ken Howard * Kenji Imamula * Lorant Pinter +* Lucien Greathouse +* Martin VšetiÄŤka * Masahiro Wakame +* Mattias Buelens * Max Deepfield * Micah Zoltu * Mohamed Hegazy +* Nathan Shively-Sanders +* Nathan Yee * Oleg Mihailik * Oleksandr Chekhovskyi * Paul van Brenk +* @pcbro * Pedro Maltez * Philip Bulley * piloopin +* @progre +* Punya Biswal +* Richard Sentino * Ron Buckton +* Rowan Wyborn * Ryan Cavanaugh +* Ryohei Ikegami +* SĂ©bastien Arod * Sheetal Nandi * Shengping Zhong * Shyyko Serhiy -* Simon Hürlimann +* Simon HĂĽrlimann * Solal Pirelli * Stan Thomas * Steve Lucco +* Thomas Loubiou * Tien Hoanhtien +* Tim Perry * Tingan Ho * togru * Tomas Grubliauskas * TruongSinh Tran-Nguyen +* Viliv Vane * Vladimir Matveev * Wesley Wigham +* York Yao * Yui Tanglertsampan +* Yuichi Nukiyama * Zev Spitz -* Zhengbo Li \ No newline at end of file +* Zhengbo Li diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 68d88854849..7a99bf318d2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,45 @@ +# Instructions for Logging Issues + +## 1. Read the FAQ + +Please [read the FAQ](https://github.com/Microsoft/TypeScript/wiki/FAQ) before logging new issues, even if you think you have found a bug. + +Issues that ask questions answered in the FAQ will be closed without elaboration. + +## 2. Search for Duplicates + +[Search the existing issues](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue) before logging a new one. + +## 3. Do you have a question? + +The issue tracker is for **issues**, in other words, bugs and suggestions. +If you have a *question*, please use [Stack Overflow](http://stackoverflow.com/questions/tagged/typescript), [Gitter](https://gitter.im/Microsoft/TypeScript), your favorite search engine, or other resources. +Due to increased traffic, we can no longer answer questions in the issue tracker. + +## 4. Did you find a bug? + +When logging a bug, please be sure to include the following: + * What version of TypeScript you're using (run `tsc --v`) + * If at all possible, an *isolated* way to reproduce the behavior + * The behavior you expect to see, and the actual behavior + +You can try out the nightly build of TypeScript (`npm install typescript@next`) to see if the bug has already been fixed. + +## 5. Do you have a suggestion? + +We also accept suggestions in the issue tracker. +Be sure to [check the FAQ](https://github.com/Microsoft/TypeScript/wiki/FAQ) and [search](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue) first. + +In general, things we find useful when reviewing suggestions are: +* A description of the problem you're trying to solve +* An overview of the suggested solution +* Examples of how the suggestion would work in various places + * Code examples showing e.g. "this would be an error, this wouldn't" + * Code examples showing the generated JavaScript (if applicable) +* If relevant, precedent in other languages can be useful for establishing context and expected behavior + +# Instructions for Contributing Code + ## Contributing bug fixes TypeScript is currently accepting contributions in the form of bug fixes. A bug must have an issue tracking it in the issue tracker that has been approved ("Milestone == Community") by the TypeScript team. Your pull request should include a link to the bug that you are fixing. If you've submitted a PR for a bug, please post a comment in the bug to avoid duplication of effort. @@ -29,18 +71,20 @@ Your pull request should: * Tests should include reasonable permutations of the target fix/change * Include baseline changes with your change * All changed code must have 100% code coverage -* Follow the code conventions descriped in [Coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines) +* Follow the code conventions described in [Coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines) * To avoid line ending issues, set `autocrlf = input` and `whitespace = cr-at-eol` in your git configuration ## Contributing `lib.d.ts` fixes The library sources are in: [src/lib](https://github.com/Microsoft/TypeScript/tree/master/src/lib) -To build the library files, run +Library files in `built/local/` are updated by running ```Shell -jake lib +jake ``` +The files in `lib/` are used to bootstrap compilation and usually do not need to be updated. + #### `src/lib/dom.generated.d.ts` and `src/lib/webworker.generated.d.ts` These two files represent the DOM typings and are auto-generated. To make any modifications to them, please submit a PR to https://github.com/Microsoft/TSJS-lib-generator diff --git a/Jakefile.js b/Jakefile.js index 14bf047cf21..a6570c3c710 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -40,6 +40,7 @@ var compilerSources = [ "utilities.ts", "binder.ts", "checker.ts", + "sourcemap.ts", "declarationEmitter.ts", "emitter.ts", "program.ts", @@ -59,6 +60,7 @@ var servicesSources = [ "utilities.ts", "binder.ts", "checker.ts", + "sourcemap.ts", "declarationEmitter.ts", "emitter.ts", "program.ts", @@ -148,7 +150,10 @@ var harnessSources = harnessCoreSources.concat([ "reuseProgramStructure.ts", "cachingInServerLSHost.ts", "moduleResolution.ts", - "tsconfigParsing.ts" + "tsconfigParsing.ts", + "commandLineParsing.ts", + "convertCompilerOptionsFromJson.ts", + "convertTypingOptionsFromJson.ts" ].map(function (f) { return path.join(unittestsDirectory, f); })).concat([ @@ -161,13 +166,15 @@ var harnessSources = harnessCoreSources.concat([ })); var librarySourceMap = [ - { target: "lib.core.d.ts", sources: ["core.d.ts"] }, + { target: "lib.core.d.ts", sources: ["header.d.ts", "core.d.ts"] }, { target: "lib.dom.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "dom.generated.d.ts"], }, { target: "lib.webworker.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "webworker.generated.d.ts"], }, { target: "lib.scriptHost.d.ts", sources: ["importcore.d.ts", "scriptHost.d.ts"], }, - { target: "lib.d.ts", sources: ["core.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: ["es6.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] } + { target: "lib.d.ts", sources: ["header.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"], }, + { target: "lib.core.es6.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts"]}, + { target: "lib.es6.d.ts", sources: ["header.d.ts", "es6.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] }, + { target: "lib.core.es7.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts", "es7.d.ts"]}, + { target: "lib.es7.d.ts", sources: ["header.d.ts", "es6.d.ts", "es7.d.ts", "core.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) { @@ -219,48 +226,59 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename); * @param prereqs: prerequisite tasks to compiling the file * @param prefixes: a list of files to prepend to the target file * @param useBuiltCompiler: true to use the built compiler, false to use the LKG - * @param noOutFile: true to compile without using --out - * @param generateDeclarations: true to compile using --declaration - * @param outDir: true to compile using --outDir - * @param keepComments: false to compile using --removeComments + * @parap {Object} opts - property bag containing auxiliary options + * @param {boolean} opts.noOutFile: true to compile without using --out + * @param {boolean} opts.generateDeclarations: true to compile using --declaration + * @param {string} opts.outDir: value for '--outDir' command line option + * @param {boolean} opts.keepComments: false to compile using --removeComments + * @param {boolean} opts.preserveConstEnums: true if compiler should keep const enums in code + * @param {boolean} opts.noResolve: true if compiler should not include non-rooted files in compilation + * @param {boolean} opts.stripInternal: true if compiler should remove declarations marked as @internal + * @param {boolean} opts.noMapRoot: true if compiler omit mapRoot option * @param callback: a function to execute after the compilation process ends */ -function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, preserveConstEnums, keepComments, noResolve, stripInternal, callback) { +function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) { file(outFile, prereqs, function() { var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler; - var options = "--module commonjs --noImplicitAny --noEmitOnError --pretty"; - + var options = "--noImplicitAny --noEmitOnError --pretty"; + opts = opts || {}; // Keep comments when specifically requested // or when in debug mode. - if (!(keepComments || useDebugMode)) { + if (!(opts.keepComments || useDebugMode)) { options += " --removeComments"; } - if (generateDeclarations) { + if (opts.generateDeclarations) { options += " --declaration"; } - if (preserveConstEnums || useDebugMode) { + if (opts.preserveConstEnums || useDebugMode) { options += " --preserveConstEnums"; } - if (outDir) { - options += " --outDir " + outDir; + if (opts.outDir) { + options += " --outDir " + opts.outDir; } - if (!noOutFile) { + if (!opts.noOutFile) { options += " --out " + outFile; } + else { + options += " --module commonjs" + } - if(noResolve) { + if(opts.noResolve) { options += " --noResolve"; } if (useDebugMode) { - options += " -sourcemap -mapRoot file:///" + path.resolve(path.dirname(outFile)); + options += " -sourcemap"; + if (!opts.noMapRoot) { + options += " -mapRoot file:///" + path.resolve(path.dirname(outFile)); + } } - if (stripInternal) { + if (opts.stripInternal) { options += " --stripInternal" } @@ -362,7 +380,6 @@ file(builtGeneratedDiagnosticMessagesJSON,[generatedDiagnosticMessagesJSON], fun desc("Generates a diagnostic file in TypeScript based on an input JSON file"); task("generate-diagnostics", [diagnosticInfoMapTs]); - // Publish nightly var configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js"); var configureNightlyTs = path.join(scriptsDirectory, "configureNightly.ts"); @@ -376,13 +393,7 @@ compileFile(/*outfile*/configureNightlyJs, /*prereqs*/ [configureNightlyTs], /*prefixes*/ [], /*useBuiltCompiler*/ false, - /*noOutFile*/ false, - /*generateDeclarations*/ false, - /*outDir*/ undefined, - /*preserveConstEnums*/ undefined, - /*keepComments*/ false, - /*noResolve*/ false, - /*stripInternal*/ false); + { noOutFile: false, generateDeclarations: false, keepComments: false, noResolve: false, stripInternal: false }); task("setDebugMode", function() { useDebugMode = true; @@ -432,6 +443,7 @@ var tscFile = path.join(builtLocalDirectory, compilerFilename); compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false); var servicesFile = path.join(builtLocalDirectory, "typescriptServices.js"); +var servicesFileInBrowserTest = path.join(builtLocalDirectory, "typescriptServicesInBrowserTest.js"); var standaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices.d.ts"); var nodePackageFile = path.join(builtLocalDirectory, "typescript.js"); var nodeDefinitionsFile = path.join(builtLocalDirectory, "typescript.d.ts"); @@ -440,13 +452,7 @@ var nodeStandaloneDefinitionsFile = path.join(builtLocalDirectory, "typescript_s compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, - /*noOutFile*/ false, - /*generateDeclarations*/ true, - /*outDir*/ undefined, - /*preserveConstEnums*/ true, - /*keepComments*/ true, - /*noResolve*/ false, - /*stripInternal*/ true, + { noOutFile: false, generateDeclarations: true, preserveConstEnums: true, keepComments: true, noResolve: false, stripInternal: true }, /*callback*/ function () { jake.cpR(servicesFile, nodePackageFile, {silent: true}); @@ -463,12 +469,22 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca var nodeDefinitionsFileContents = definitionFileContents + "\r\nexport = ts;"; fs.writeFileSync(nodeDefinitionsFile, nodeDefinitionsFileContents); - // Node package definition file to be distributed without the package. Created by replacing + // Node package definition file to be distributed without the package. Created by replacing // 'ts' namespace with '"typescript"' as a module. var nodeStandaloneDefinitionsFileContents = definitionFileContents.replace(/declare (namespace|module) ts/g, 'declare module "typescript"'); fs.writeFileSync(nodeStandaloneDefinitionsFile, nodeStandaloneDefinitionsFileContents); }); +compileFile(servicesFileInBrowserTest, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources), + /*prefixes*/ [copyright], + /*useBuiltCompiler*/ true, + { noOutFile: false, generateDeclarations: true, preserveConstEnums: true, keepComments: true, noResolve: false, stripInternal: true, noMapRoot: true }, + /*callback*/ function () { + var content = fs.readFileSync(servicesFileInBrowserTest).toString(); + var i = content.lastIndexOf("\n"); + fs.writeFileSync(servicesFileInBrowserTest, content.substring(0, i) + "\r\n//# sourceURL=../built/local/typeScriptServices.js" + content.substring(i)); + }); + var serverFile = path.join(builtLocalDirectory, "tsserver.js"); compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true); @@ -480,8 +496,7 @@ compileFile( [builtLocalDirectory, copyright].concat(languageServiceLibrarySources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, - /*noOutFile*/ false, - /*generateDeclarations*/ true); + { noOutFile: false, generateDeclarations: true }); // Local target to build the language service server library desc("Builds language service server library"); @@ -529,7 +544,8 @@ compileFile(word2mdJs, // The generated spec.md; built for the 'generate-spec' task file(specMd, [word2mdJs, specWord], function () { var specWordFullPath = path.resolve(specWord); - var cmd = "cscript //nologo " + word2mdJs + ' "' + specWordFullPath + '" ' + specMd; + var specMDFullPath = path.resolve(specMd); + var cmd = "cscript //nologo " + word2mdJs + ' "' + specWordFullPath + '" ' + '"' + specMDFullPath + '"'; console.log(cmd); child_process.exec(cmd, function () { complete(); @@ -639,7 +655,7 @@ function deleteTemporaryProjectOutput() { } } -function runConsoleTests(defaultReporter, defaultSubsets, postLint) { +function runConsoleTests(defaultReporter, defaultSubsets) { cleanTestDirs(); var debug = process.env.debug || process.env.d; tests = process.env.test || process.env.tests || process.env.t; @@ -672,13 +688,13 @@ function runConsoleTests(defaultReporter, defaultSubsets, postLint) { subsetRegexes = subsets.map(function (sub) { return "^" + sub + ".*$"; }); subsetRegexes.push("^(?!" + subsets.join("|") + ").*$"); } - subsetRegexes.forEach(function (subsetRegex) { + subsetRegexes.forEach(function (subsetRegex, i) { tests = subsetRegex ? ' -g "' + subsetRegex + '"' : ''; var cmd = "mocha" + (debug ? " --debug-brk" : "") + " -R " + reporter + tests + colors + ' -t ' + testTimeout + ' ' + run; console.log(cmd); exec(cmd, function () { deleteTemporaryProjectOutput(); - if (postLint) { + if (i === 0) { var lint = jake.Task['lint']; lint.addListener('complete', function () { complete(); @@ -700,7 +716,7 @@ task("runtests-parallel", ["build-rules", "tests", builtLocalDirectory], functio desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|] d[ebug]=true color[s]=false."); task("runtests", ["build-rules", "tests", builtLocalDirectory], function() { - runConsoleTests('mocha-fivemat-progress-reporter', [], /*postLint*/ true); + runConsoleTests('mocha-fivemat-progress-reporter', []); }, {async: true}); desc("Generates code coverage data via instanbul"); @@ -713,7 +729,7 @@ task("generate-code-coverage", ["tests", builtLocalDirectory], function () { // Browser tests var nodeServerOutFile = 'tests/webTestServer.js' var nodeServerInFile = 'tests/webTestServer.ts' -compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, /*noOutFile*/ true); +compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, { noOutFile: true }); desc("Runs browserify on run.js to produce a file suitable for running tests in the browser"); task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function() { @@ -722,7 +738,7 @@ task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function() }, {async: true}); desc("Runs the tests using the built run.js file like 'jake runtests'. Syntax is jake runtests-browser. Additional optional parameters tests=[regex], port=, browser=[chrome|IE]"); -task("runtests-browser", ["tests", "browserify", builtLocalDirectory], function() { +task("runtests-browser", ["tests", "browserify", builtLocalDirectory, servicesFileInBrowserTest], function() { cleanTestDirs(); host = "node" port = process.env.port || process.env.p || '8888'; @@ -861,7 +877,9 @@ var tslintRules = ([ "noNullRule", "preferConstRule", "booleanTriviaRule", - "typeOperatorSpacingRule" + "typeOperatorSpacingRule", + "noInOperatorRule", + "noIncrementDecrementRule" ]); var tslintRulesFiles = tslintRules.map(function(p) { return path.join(tslintRuleDir, p + ".ts"); @@ -872,7 +890,8 @@ var tslintRulesOutFiles = tslintRules.map(function(p) { desc("Compiles tslint rules to js"); task("build-rules", tslintRulesOutFiles); tslintRulesFiles.forEach(function(ruleFile, i) { - compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false, /*noOutFile*/ true, /*generateDeclarations*/ false, path.join(builtLocalDirectory, "tslint")); + compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false, + { noOutFile: true, generateDeclarations: false, outDir: path.join(builtLocalDirectory, "tslint")}); }); function getLinterOptions() { @@ -886,6 +905,7 @@ function getLinterOptions() { function lintFileContents(options, path, contents) { var ll = new Linter(path, contents, options); + console.log("Linting '" + path + "'.") return ll.lint(); } @@ -904,20 +924,36 @@ function lintFileAsync(options, path, cb) { }); } +var servicesLintTargets = [ + "navigateTo.ts", + "outliningElementsCollector.ts", + "patternMatcher.ts", + "services.ts", + "shims.ts", + "jsTyping.ts" +].map(function (s) { + return path.join(servicesDirectory, s); +}); var lintTargets = compilerSources .concat(harnessCoreSources) - .concat(serverCoreSources); + .concat(serverCoreSources) + .concat(tslintRulesFiles) + .concat(servicesLintTargets); desc("Runs tslint on the compiler sources"); task("lint", ["build-rules"], function() { var lintOptions = getLinterOptions(); + var failed = 0; for (var i in lintTargets) { var result = lintFile(lintOptions, lintTargets[i]); if (result.failureCount > 0) { console.log(result.output); - fail('Linter errors.', result.failureCount); + failed += result.failureCount; } } + if (failed > 0) { + fail('Linter errors.', failed); + } }); /** @@ -934,7 +970,7 @@ function lintWatchFile(filename) { if (event !== "change") { return; } - + if (!lintSemaphores[filename]) { lintSemaphores[filename] = true; lintFileAsync(getLinterOptions(), filename, function(err, result) { diff --git a/README.md b/README.md index e27e7a99fa7..13e1f3e4786 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ [![Build Status](https://travis-ci.org/Microsoft/TypeScript.svg?branch=master)](https://travis-ci.org/Microsoft/TypeScript) -[![npm version](https://badge.fury.io/js/typescript.svg)](http://badge.fury.io/js/typescript) -[![Downloads](http://img.shields.io/npm/dm/TypeScript.svg)](https://npmjs.org/package/typescript) +[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript) +[![Downloads](https://img.shields.io/npm/dm/TypeScript.svg)](https://www.npmjs.com/package/typescript) # TypeScript diff --git a/doc/README.md b/doc/README.md new file mode 100644 index 00000000000..cfc97fedbe9 --- /dev/null +++ b/doc/README.md @@ -0,0 +1,9 @@ +# Read This! + +This directory contains miscellaneous documentation such as the TypeScript language specification and logo. +If you are looking for more introductory material, you might want to take a look at the [TypeScript Handbook](https://github.com/Microsoft/TypeScript-Handbook). + +# Spec Contributions + +The specification is first authored as a Microsoft Word (docx) file and then generated into Markdown and PDF formats. +Due to the binary format of docx files, and the merging difficulties that may come with it, it is preferred that **any suggestions or problems found in the spec should be [filed as issues](https://github.com/Microsoft/TypeScript/issues/new)** rather than sent as pull requests. diff --git a/doc/TypeScript Language Specification (Change Markup).docx b/doc/TypeScript Language Specification (Change Markup).docx index 893f2e7ed22..1db9f4e5908 100644 Binary files a/doc/TypeScript Language Specification (Change Markup).docx and b/doc/TypeScript Language Specification (Change Markup).docx differ diff --git a/doc/TypeScript Language Specification (Change Markup).pdf b/doc/TypeScript Language Specification (Change Markup).pdf index 1b4faab62e1..3403ba90217 100644 Binary files a/doc/TypeScript Language Specification (Change Markup).pdf and b/doc/TypeScript Language Specification (Change Markup).pdf differ diff --git a/doc/TypeScript Language Specification.docx b/doc/TypeScript Language Specification.docx index 4aaa3bf92fe..4b8d3998f90 100644 Binary files a/doc/TypeScript Language Specification.docx and b/doc/TypeScript Language Specification.docx differ diff --git a/doc/TypeScript Language Specification.pdf b/doc/TypeScript Language Specification.pdf index 277fcecf2de..07069f6d3a0 100644 Binary files a/doc/TypeScript Language Specification.pdf and b/doc/TypeScript Language Specification.pdf differ diff --git a/doc/handbook/README.md b/doc/handbook/README.md new file mode 100644 index 00000000000..2d2e0e83a46 --- /dev/null +++ b/doc/handbook/README.md @@ -0,0 +1,4 @@ +# The TypeScript Handbook + +The contents of the TypeScript Handbook can be read from [its GitHub repository](https://github.com/Microsoft/TypeScript-Handbook). +Issues and pull requests should be directed there. \ No newline at end of file diff --git a/doc/images/image1.png b/doc/images/image1.png new file mode 100644 index 00000000000..e1db88fa4f8 Binary files /dev/null and b/doc/images/image1.png differ diff --git a/doc/images/image2.png b/doc/images/image2.png new file mode 100644 index 00000000000..c0321038057 Binary files /dev/null and b/doc/images/image2.png differ diff --git a/doc/images/image3.png b/doc/images/image3.png new file mode 100644 index 00000000000..5fe2ecb8f3e Binary files /dev/null and b/doc/images/image3.png differ diff --git a/doc/images/image4.png b/doc/images/image4.png new file mode 100644 index 00000000000..13a6d8fcfb6 Binary files /dev/null and b/doc/images/image4.png differ diff --git a/doc/spec.md b/doc/spec.md index fe2147be477..fa69d321056 100644 --- a/doc/spec.md +++ b/doc/spec.md @@ -1,8 +1,8 @@ # TypeScript Language Specification -Version 1.6 +Version 1.8 -August, 2015 +January, 2016
@@ -58,8 +58,8 @@ TypeScript is a trademark of Microsoft Corporation. * [3.6 Type Parameters](#3.6) * [3.6.1 Type Parameter Lists](#3.6.1) * [3.6.2 Type Argument Lists](#3.6.2) + * [3.6.3 This-types](#3.6.3) * [3.7 Named Types](#3.7) - * [3.7.1 Instance Types](#3.7.1) * [3.8 Specifying Types](#3.8) * [3.8.1 Predefined Types](#3.8.1) * [3.8.2 Type References](#3.8.2) @@ -71,6 +71,7 @@ TypeScript is a trademark of Microsoft Corporation. * [3.8.8 Function Type Literals](#3.8.8) * [3.8.9 Constructor Type Literals](#3.8.9) * [3.8.10 Type Queries](#3.8.10) + * [3.8.11 This-Type References](#3.8.11) * [3.9 Specifying Members](#3.9) * [3.9.1 Property Signatures](#3.9.1) * [3.9.2 Call Signatures](#3.9.2) @@ -158,7 +159,8 @@ TypeScript is a trademark of Microsoft Corporation. * [6.5 Generic Functions](#6.5) * [6.6 Code Generation](#6.6) * [6.7 Generator Functions](#6.7) - * [6.8 Type Guard Functions](#6.8) + * [6.8 Asynchronous Functions](#6.8) + * [6.9 Type Guard Functions](#6.9) * [7 Interfaces](#7) * [7.1 Interface Declarations](#7.1) * [7.2 Declaration Merging](#7.2) @@ -184,9 +186,10 @@ TypeScript is a trademark of Microsoft Corporation. * [8.4.3 Member Accessor Declarations](#8.4.3) * [8.4.4 Dynamic Property Declarations](#8.4.4) * [8.5 Index Member Declarations](#8.5) - * [8.6 Code Generation](#8.6) - * [8.6.1 Classes Without Extends Clauses](#8.6.1) - * [8.6.2 Classes With Extends Clauses](#8.6.2) + * [8.6 Decorators](#8.6) + * [8.7 Code Generation](#8.7) + * [8.7.1 Classes Without Extends Clauses](#8.7.1) + * [8.7.2 Classes With Extends Clauses](#8.7.2) * [9 Enums](#9) * [9.1 Enum Declarations](#9.1) * [9.2 Enum Members](#9.2) @@ -238,9 +241,9 @@ TypeScript is a trademark of Microsoft Corporation. JavaScript applications such as web e-mail, maps, document editing, and collaboration tools are becoming an increasingly important part of the everyday computing. We designed TypeScript to meet the needs of the JavaScript programming teams that build and maintain large JavaScript programs. TypeScript helps programming teams to define interfaces between software components and to gain insight into the behavior of existing JavaScript libraries. TypeScript also enables teams to reduce naming conflicts by organizing their code into dynamically-loadable modules. TypeScript's optional type system enables JavaScript programmers to use highly-productive development tools and practices: static checking, symbol-based navigation, statement completion, and code re-factoring. -TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 6 (ES6) syntax. Every JavaScript program is also a TypeScript program. The TypeScript compiler performs only file-local transformations on TypeScript programs and does not re-order variables declared in TypeScript. This leads to JavaScript output that closely matches the TypeScript input. TypeScript does not transform variable names, making tractable the direct debugging of emitted JavaScript. TypeScript optionally provides source maps, enabling source-level debugging. TypeScript tools typically emit JavaScript upon file save, preserving the test, edit, refresh cycle commonly used in JavaScript development. +TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax. Every JavaScript program is also a TypeScript program. The TypeScript compiler performs only file-local transformations on TypeScript programs and does not re-order variables declared in TypeScript. This leads to JavaScript output that closely matches the TypeScript input. TypeScript does not transform variable names, making tractable the direct debugging of emitted JavaScript. TypeScript optionally provides source maps, enabling source-level debugging. TypeScript tools typically emit JavaScript upon file save, preserving the test, edit, refresh cycle commonly used in JavaScript development. -TypeScript syntax includes all features of ECMAScript 6 (ES6), including classes and modules, and provides the ability to translate these features into ECMAScript 3 or 5 compliant code. +TypeScript syntax includes all features of ECMAScript 2015, including classes and modules, and provides the ability to translate these features into ECMAScript 3 or 5 compliant code. Classes enable programmers to express common object-oriented patterns in a standard way, making features like inheritance more readable and interoperable. Modules enable programmers to organize their code into components while avoiding naming conflicts. The TypeScript compiler provides module code generation options that support either static or dynamic loading of module contents. @@ -262,7 +265,7 @@ function f() { To benefit from this inference, a programmer can use the TypeScript language service. For example, a code editor can incorporate the TypeScript language service and use the service to find the members of a string object as in the following screen shot. -/ +  ![](images/image1.png) In this example, the programmer benefits from type inference without providing type annotations. Some beneficial tools, however, do require the programmer to provide type annotations. In TypeScript, we can express a parameter requirement as in the following code fragment. @@ -410,7 +413,7 @@ This signature denotes that a function may be passed as the parameter of the '$' A typical client would not need to add any additional typing but could just use a community-supplied typing to discover (through statement completion with documentation tips) and verify (through static checking) correct use of the library, as in the following screen shot. -/ +  ![](images/image2.png) Section [3.3](#3.3) provides additional information about object types. @@ -474,7 +477,7 @@ Section [4.23](#4.23) provides additional information about contextually typed e ## 1.6 Classes -JavaScript practice has two very common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms. Libraries such as 'prototype.js' are typical of this practice. TypeScript's namespaces are a formalization of the module pattern. (The term "module pattern" is somewhat unfortunate now that ECMAScript 6 formally supports modules in a manner different from what the module pattern prescribes. For this reason, TypeScript uses the term "namespace" for its formalization of the module pattern.) +JavaScript practice has two very common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms. Libraries such as 'prototype.js' are typical of this practice. TypeScript's namespaces are a formalization of the module pattern. (The term "module pattern" is somewhat unfortunate now that ECMAScript 2015 formally supports modules in a manner different from what the module pattern prescribes. For this reason, TypeScript uses the term "namespace" for its formalization of the module pattern.) This section and the namespace section below will show how TypeScript emits consistent, idiomatic JavaScript when emitting ECMAScript 3 or 5 compliant code for classes and namespaces. The goal of TypeScript's translation is to emit exactly what a programmer would type when implementing a class or namespace unaided by a tool. This section will also describe how TypeScript infers a type for each class declaration. We'll start with a simple BankAccount class. @@ -627,7 +630,7 @@ An important goal of TypeScript is to provide accurate and straightforward types JavaScript programming interfaces often include functions whose behavior is discriminated by a string constant passed to the function. The Document Object Model makes heavy use of this pattern. For example, the following screen shot shows that the 'createElement' method of the 'document' object has multiple signatures, some of which identify the types returned when specific strings are passed into the method. -/ +  ![](images/image3.png) The following code fragment uses this feature. Because the 'span' variable is inferred to have the type 'HTMLSpanElement', the code can reference without static error the 'isMultiline' property of 'span'. @@ -638,7 +641,7 @@ span.isMultiLine = false; // OK: HTMLSpanElement has isMultiline property In the following screen shot, a programming tool combines information from overloading on string parameters with contextual typing to infer that the type of the variable 'e' is 'MouseEvent' and that therefore 'e' has a 'clientX' property. -/ +  ![](images/image4.png) Section [3.9.2.4](#3.9.2.4) provides details on how to use string literals in function signatures. @@ -773,13 +776,13 @@ In this case, the compiler assumes that the namespace object resides in global v ## 1.11 Modules -TypeScript also supports ECMAScript 6 modules, which are files that contain top-level *export* and *import* directives. For this type of module the TypeScript compiler can emit both ECMAScript 6 compliant code and down-level ECMAScript 3 or 5 compliant code for a variety of module loading systems, including CommonJS, Asynchronous Module Definition (AMD), and Universal Module Definition (UMD). +TypeScript also supports ECMAScript 2015 modules, which are files that contain top-level *export* and *import* directives. For this type of module the TypeScript compiler can emit both ECMAScript 2015 compliant code and down-level ECMAScript 3 or 5 compliant code for a variety of module loading systems, including CommonJS, Asynchronous Module Definition (AMD), and Universal Module Definition (UMD).
#
2 Basic Concepts -The remainder of this document is the formal specification of the TypeScript programming language and is intended to be read as an adjunct to the [ECMAScript Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) (specifically, the ECMA-262 Standard, 6th Edition). This document describes the syntactic grammar added by TypeScript along with the compile-time processing and type checking performed by the TypeScript compiler, but it only minimally discusses the run-time behavior of programs since that is covered by the ECMAScript specification. +The remainder of this document is the formal specification of the TypeScript programming language and is intended to be read as an adjunct to the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition). This document describes the syntactic grammar added by TypeScript along with the compile-time processing and type checking performed by the TypeScript compiler, but it only minimally discusses the run-time behavior of programs since that is covered by the ECMAScript specification. ## 2.1 Grammar Conventions @@ -866,7 +869,7 @@ A property name can be any identifier (including a reserved word), a string lite ### 2.2.3 Computed Property Names -ECMAScript 6 permits object literals and classes to declare members with computed property names. A computed property name specifies an expression that computes the actual property name at run-time. Because the final property name isn't known at compile-time, TypeScript can only perform limited checks for entities declared with computed property names. However, a subset of computed property names known as ***well-known symbols*** can be used anywhere a *PropertyName* is expected, including property names within types. A computed property name is a well-known symbol if it is of the form +ECMAScript 2015 permits object literals and classes to declare members with computed property names. A computed property name specifies an expression that computes the actual property name at run-time. Because the final property name isn't known at compile-time, TypeScript can only perform limited checks for entities declared with computed property names. However, a subset of computed property names known as ***well-known symbols*** can be used anywhere a *PropertyName* is expected, including property names within types. A computed property name is a well-known symbol if it is of the form ```TypeScript [ Symbol . xxx ] @@ -884,6 +887,8 @@ interface Iterable { } ``` +*TODO: Update to reflect treatment of [computed property names with literal expressions](https://github.com/Microsoft/TypeScript/pull/5535)*. + ## 2.3 Declarations Declarations introduce names in their associated ***declaration spaces***. A name must be unique in its declaration space and can denote a ***value***, a ***type***, or a ***namespace***, or some combination thereof. Effectively, a single name can have as many as three distinct meanings. For example: @@ -913,7 +918,7 @@ Declarations introduce the following meanings for the name they declare: * A variable, parameter, function, generator, member variable, member function, member accessor, or enum member declaration introduces a value meaning. * An interface, type alias, or type parameter declaration introduces a type meaning. -* A class declaration introduces a value meaning (the constructor function) and a type meaning (the class instance type). +* A class declaration introduces a value meaning (the constructor function) and a type meaning (the class type). * An enum declaration introduces a value meaning (the enum instance) and a type meaning (the enum type). * A namespace declaration introduces a namespace meaning (the type and namespace container) and, if the namespace is instantiated (section [10.1](#10.1)), a value meaning (the namespace instance). * An import or export declaration introduces the meaning(s) of the imported or exported entity. @@ -996,7 +1001,9 @@ When an identifier is resolved as a *TypeName* (section [3.8.2](#3.8.2)), only n When an identifier is resolved as a *NamespaceName* (section [3.8.2](#3.8.2)), only names in scope with a namespace meaning are considered and other names are ignored. -Note that class members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class instance. This even includes members of the current instance in a constructor or member function, which are accessed by applying the dot operator to `this`. +*TODO: [Include specific rules for alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*. + +Note that class and interface members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class or interface instance. This even includes members of the current instance in a constructor or member function, which are accessed by applying the dot operator to `this`. As the rules above imply, locally declared entities in a namespace are closer in scope than exported entities declared in other namespace declarations for the same namespace. For example: @@ -1121,7 +1128,7 @@ var c = abc.charAt(2); // Property of String interface The Symbol primitive type corresponds to the similarly named JavaScript primitive type and represents unique tokens that may be used as keys for object properties. -The `symbol` keyword references the Symbol primitive type. Symbol values are obtained using the global object 'Symbol' which has a number of methods and properties and can be invoked as a function. In particular, the global object 'Symbol' defines a number of well-known symbols ([2.2.3](#2.2.3)) that can be used in a manner similar to identifiers. Note that the 'Symbol' object is available only in ECMAScript 6 environments. +The `symbol` keyword references the Symbol primitive type. Symbol values are obtained using the global object 'Symbol' which has a number of methods and properties and can be invoked as a function. In particular, the global object 'Symbol' defines a number of well-known symbols ([2.2.3](#2.2.3)) that can be used in a manner similar to identifiers. Note that the 'Symbol' object is available only in ECMAScript 2015 environments. For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Symbol primitive type behaves as an object type with the same properties as the global interface type 'Symbol'. @@ -1186,6 +1193,8 @@ Specialized signatures (section [3.9.2.4](#3.9.2.4)) permit string literals to b All string literal types are subtypes of the String primitive type. +*TODO: Update to reflect [expanded support for string literal types](https://github.com/Microsoft/TypeScript/pull/5185)*. + ## 3.3 Object Types Object types are composed from properties, call signatures, construct signatures, and index signatures, collectively called members. @@ -1323,7 +1332,7 @@ x = "hello"; // Ok x = 42; // Ok x = test; // Error, boolean not assignable x = test ? 5 : "five"; // Ok -x = test ? 0 : false; // Error, number | boolean not asssignable +x = test ? 0 : false; // Error, number | boolean not assignable ``` it is possible to assign 'x' a value of type `string`, `number`, or the union type `string | number`, but not any other type. To access a value in 'x', a type guard can be used to first narrow the type of 'x' to either `string` or `number`: @@ -1352,7 +1361,7 @@ var b = x.b; // b has type number var c = x.c; // Error, no property c in union type ``` -Note that 'x.a' has a union type because the type of 'a' is different in 'A' and 'B', whereas 'x.b' simply has type number because that is the type of 'b' in both 'A' and 'B'. Also note that there is no property 'x.c' because only 'A' has a property 'c'. +Note that 'x.a' has a union type because the type of 'a' is different in 'A' and 'B', whereas 'x.b' simply has type number because that is the type of 'b' in both 'A' and 'B'. Also note that there is no property 'x.c' because only 'B' has a property 'c'. When used as a contextual type (section [4.23](#4.23)), a union type has those members that are present in any of its constituent types, with types that are unions of the respective members in the constituent types. Specifically, a union type used as a contextual type has the apparent members defined in section [3.11.1](#3.11.1), except that a particular member need only be present in one or more constituent types instead of all constituent types. @@ -1437,7 +1446,7 @@ Type parameter names must be unique. A compile-time error occurs if two or more The scope of a type parameter extends over the entire declaration with which the type parameter list is associated, with the exception of static member declarations in classes. -Each type parameter has an associated type parameter ***constraint*** that establishes an upper bound for type arguments. Omitting a constraint or specifying type `any` as the constraint corresponds to specifying the empty object type `{}`. Type parameters declared in a particular type parameter list may not be referenced in constraints in that type parameter list. +A type parameter may have an associated type parameter ***constraint*** that establishes an upper bound for type arguments. Type parameters may be referenced in type parameter constraints within the same type parameter list, including even constraint declarations that occur to the left of the type parameter. The ***base constraint*** of a type parameter *T* is defined as follows: @@ -1448,15 +1457,21 @@ The ***base constraint*** of a type parameter *T* is defined as follows: In the example ```TypeScript -interface G { - f(x: V): V; -} +interface G { } ``` -the base constraint of 'T' is the empty object type, and the base constraint of 'U' and 'V' is 'Function'. +the base constraint of 'T' is the empty object type and the base constraint of 'U' and 'V' is 'Function'. For purposes of determining type relationships (section [3.11](#3.11)), type parameters appear to be subtypes of their base constraint. Likewise, in property accesses (section [4.13](#4.13)), `new` operations (section [4.14](#4.14)), and function calls (section [4.15](#4.15)), type parameters appear to have the members of their base constraint, but no other members. +It is an error for a type parameter to directly or indirectly be a constraint for itself. For example, both of the following declarations are invalid: + +```TypeScript +interface A { } + +interface B { } +``` + ### 3.6.2 Type Argument Lists A type reference (section [3.8.2](#3.8.2)) to a generic type must include a list of type arguments enclosed in angle brackets and separated by commas. Similarly, a call (section [4.15](#4.15)) to a generic function may explicitly include a type argument list instead of relying on type inference. @@ -1471,7 +1486,7 @@ A type reference (section [3.8.2](#3.8.2)) to a generic type must include a list   *TypeArgument:*    *Type* -Type arguments correspond one-to-one with type parameters of the generic type or function being referenced. A type argument list is required to specify exactly one type argument for each corresponding type parameter, and each type argument is required to ***satisfy*** the constraint of its corresponding type parameter. A type argument satisfies a type parameter constraint if the type argument is assignable to (section [3.11.4](#3.11.4)) the constraint type once type arguments are substituted for type parameters. +Type arguments correspond one-to-one with type parameters of the generic type or function being referenced. A type argument list is required to specify exactly one type argument for each corresponding type parameter, and each type argument for a constrained type parameter is required to ***satisfy*** the constraint of that type parameter. A type argument satisfies a type parameter constraint if the type argument is assignable to (section [3.11.4](#3.11.4)) the constraint type once type arguments are substituted for type parameters. Given the declaration @@ -1483,6 +1498,33 @@ a type reference of the form 'G<A, B>' places no requirements on 'A' but requ The process of substituting type arguments for type parameters in a generic type or generic signature is known as ***instantiating*** the generic type or signature. Instantiation of a generic type or signature can fail if the supplied type arguments do not satisfy the constraints of their corresponding type parameters. +### 3.6.3 This-types + +Every class and interface has a ***this-type*** that represents the actual type of instances of the class or interface within the declaration of the class or interface. The this-type is referenced using the keyword `this` in a type position. Within instance methods and constructors of a class, the type of the expression `this` (section [4.2](#4.2)) is the this-type of the class. + +Classes and interfaces support inheritance and therefore the instance represented by `this` in a method isn't necessarily an instance of the containing class—it may in fact be an instance of a derived class or interface. To model this relationship, the this-type of a class or interface is classified as a type parameter. Unlike other type parameters, it is not possible to explicitly pass a type argument for a this-type. Instead, in a type reference to a class or interface type, the type reference *itself* is implicitly passed as a type argument for the this-type. For example: + +```TypeScript +class A { + foo() { + return this; + } +} + +class B extends A { + bar() { + return this; + } +} + +let b: B; +let x = b.foo().bar(); // Fluent pattern works, type of x is B +``` + +In the declaration of `b` above, the type reference `B` is itself passed as a type argument for B's this-type. Thus, the referenced type is an instantiation of class `B` where all occurrences of the type `this` are replaced with `B`, and for that reason the `foo` method of `B` actually returns `B` (as opposed to `A`). + +The this-type of a given class or interface type *C* implicitly has a constraint consisting of a type reference to *C* with *C*'s own type parameters passed as type arguments and with that type reference passed as the type argument for the this-type. + ## 3.7 Named Types Classes, interfaces, enums, and type aliases are ***named types*** that are introduced through class declarations (section [8.1](#8.1)), interface declarations (section [7.1](#7.1)), enum declarations ([9.1](#9.1)), and type alias declarations (section [3.10](#3.10)). Classes, interfaces, and type aliases may have type parameters and are then called ***generic types***. Conversely, named types without type parameters are called ***non-generic types***. @@ -1511,21 +1553,6 @@ is indistinguishable from the type { first: string; second: Entity; } ``` -### 3.7.1 Instance Types - -Each class and interface has an associated actual type known as the ***instance type***. For a non-generic class or interface, the instance type is simply a type reference to the class or interface. For a generic class or interface, the instance type is an instantiation of the generic type where each of the type arguments is the corresponding type parameter. Since the instance type uses the type parameters it can be used only where the type parameters are in scope—that is, inside the declaration of the class or interface. Within the constructor and instance member functions of a class, the type of `this` is the instance type of the class. - -The following example illustrates the concept of an instance type: - -```TypeScript -class G { // Introduce type parameter T - self: G; // Use T as type argument to form instance type - f() { - this.self = this; // self and this are both of type G - } -} -``` - ## 3.8 Specifying Types Types are specified either by referencing their keyword or name, or by writing object type literals, array type literals, tuple type literals, function type literals, constructor type literals, or type queries. @@ -1550,7 +1577,8 @@ Types are specified either by referencing their keyword or name, or by writing o    *ObjectType*    *ArrayType*    *TupleType* -   *TypeQuery* +   *TypeQuery* +   *ThisType*   *ParenthesizedType:*    `(` *Type* `)` @@ -1711,7 +1739,7 @@ A union type literal is written as a sequence of types separated by vertical bar   *UnionType:*    *UnionOrIntersectionOrPrimaryType* `|` *IntersectionOrPrimaryType* -A union typle literal references a union type (section [3.4](#3.4)). +A union type literal references a union type (section [3.4](#3.4)). ### 3.8.7 Intersection Type Literals @@ -1720,7 +1748,7 @@ An intersection type literal is written as a sequence of types separated by ampe   *IntersectionType:*    *IntersectionOrPrimaryType* `&` *PrimaryType* -An intersection typle literal references an intersection type (section [3.5](#3.5)). +An intersection type literal references an intersection type (section [3.5](#3.5)). ### 3.8.8 Function Type Literals @@ -1804,6 +1832,41 @@ var h: () => typeof h; Here, 'g' and 'g.x' have the same recursive type, and likewise 'h' and 'h()' have the same recursive type. +### 3.8.11 This-Type References + +The `this` keyword is used to reference the this-type (section [3.6.3](#3.6.3)) of a class or interface. + +  *ThisType:* +   `this` + +The meaning of a *ThisType* depends on the closest enclosing *FunctionDeclaration*, *FunctionExpression*, *PropertyDefinition*, *ClassElement*, or *TypeMember*, known as the root declaration of the *ThisType*, as follows: + +* When the root declaration is an instance member or constructor of a class, the *ThisType* references the this-type of that class. +* When the root declaration is a member of an interface type, the *ThisType* references the this-type of that interface. +* Otherwise, the *ThisType* is an error. + +Note that in order to avoid ambiguities it is not possible to reference the this-type of a class or interface in a nested object type literal. In the example + +```TypeScript +interface ListItem { + getHead(): this; + getTail(): this; + getHeadAndTail(): { head: this, tail: this }; // Error +} +``` + +the `this` references on the last line are in error because their root declarations are not members of a class or interface. The recommended way to reference the this-type of an outer class or interface in an object type literal is to declare an intermediate generic type and pass `this` as a type argument. For example: + +```TypeScript +type HeadAndTail = { head: T, tail: T }; + +interface ListItem { + getHead(): this; + getTail(): this; + getHeadAndTail(): HeadAndTail; +} +``` + ## 3.9 Specifying Members The members of an object type literal (section [3.8.3](#3.8.3)) are specified as a combination of property, call, construct, index, and method signatures. @@ -1931,6 +1994,8 @@ A parameter can be marked optional by following its name or binding pattern with *TODO: Update to reflect [binding parameter cannot be optional in implementation signature](https://github.com/Microsoft/TypeScript/issues/2797)*. +*TODO: Update to reflect [required parameters support initializers](https://github.com/Microsoft/TypeScript/pull/4022)*. + #### 3.9.2.3 Return Type If present, a call signature's return type annotation specifies the type of the value computed and returned by a call operation. A `void` return type annotation is used to indicate that a function has no return value. @@ -2122,8 +2187,9 @@ Types in TypeScript have identity, subtype, supertype, and assignment compatibil The ***apparent members*** of a type are the members observed in subtype, supertype, and assignment compatibility relationships, as well as in the type checking of property accesses (section [4.13](#4.13)), `new` operations (section [4.14](#4.14)), and function calls (section [4.15](#4.15)). The apparent members of a type are determined as follows: -* The apparent members of the primitive types Number, Boolean, and String are the apparent members of the global interface types 'Number', 'Boolean', and 'String' respectively. -* The apparent members of an enum type are the apparent members of the global interface type 'Number'. +* The apparent members of the primitive type Number and all enum types are the apparent members of the global interface type 'Number'. +* The apparent members of the primitive type Boolean are the apparent members of the global interface type 'Boolean'. +* The apparent members of the primitive type String and all string literal types are the apparent members of the global interface type 'String'. * The apparent members of a type parameter are the apparent members of the constraint (section [3.6.1](#3.6.1)) of that type parameter. * The apparent members of an object type *T* are the combination of the following: * The declared and/or inherited members of *T*. @@ -2239,7 +2305,7 @@ Types are required to be assignment compatible in certain circumstances, such as * *S* or *T* is the Any type. * *S* is the Undefined type. * *S* is the Null type and *T* is not the Undefined type. -* *S* or *T* is an enum type and* *the other is the primitive type Number. +* *S* or *T* is an enum type and the other is the primitive type Number. * *S* is a string literal type and *T* is the primitive type String. * *S* is a union type and each constituent type of *S* is assignable to *T*. * *S* is an intersection type and at least one constituent type of *S* is assignable to *T*. @@ -2258,8 +2324,8 @@ Types are required to be assignment compatible in certain circumstances, such as * *M* has a rest parameter or the number of non-optional parameters in *N* is less than or equal to the total number of parameters in *M*, * for parameter positions that are present in both signatures, each parameter type in *N* is assignable to or from the corresponding parameter type in *M*, and * the result type of *M* is Void, or the result type of *N* is assignable to that of *M*. - * *M* is a string index signature of type *U* and *S* has an apparent string index signature of a type that is assignable to *U*. - * *M* is a numeric index signature of type *U* and *S* has an apparent string or numeric index signature of a type that is assignable to *U*. + * *M* is a string index signature of type *U*, and *U* is the Any type or *S* has an apparent string index signature of a type that is assignable to *U*. + * *M* is a numeric index signature of type *U*, and *U* is the Any type or *S* has an apparent string or numeric index signature of a type that is assignable to *U*. When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type. @@ -2366,6 +2432,8 @@ In certain contexts, inferences for a given set of type parameters are made *fro When comparing call or construct signatures, signatures in *S* correspond to signatures of the same kind in *T* pairwise in declaration order. If *S* and *T* have different numbers of a given kind of signature, the excess *first* signatures in declaration order of the longer list are ignored. +*TODO: Update to reflect [improved union and intersection type inference](https://github.com/Microsoft/TypeScript/pull/5738)*. + ### 3.11.8 Recursive Types Classes and interfaces can reference themselves in their internal structure, in effect creating recursive types with infinite nesting. For example, the type @@ -2443,7 +2511,7 @@ Expressions are classified as ***values*** or ***references***. References are t The type of `this` in an expression depends on the location in which the reference takes place: -* In a constructor, instance member function, instance member accessor, or instance member variable initializer, `this` is of the class instance type of the containing class. +* In a constructor, instance member function, instance member accessor, or instance member variable initializer, `this` is of the this-type (section [3.6.3](#3.6.3)) of the containing class. * In a static member function or static member accessor, the type of `this` is the constructor function type of the containing class. * In a function declaration or a function expression, `this` is of type Any. * In the global namespace, `this` is of type Any. @@ -2569,6 +2637,8 @@ The resulting type an array literal expression is determined as follows: A spread element must specify an expression of an array-like type (section [3.3.2](#3.3.2)), or otherwise an error occurs. +*TODO: The compiler currently doesn't support applying the spread operator to a string (to spread the individual characters of a string into a string array). This will eventually be allowed, but only when the code generation target is ECMAScript 2015 or later*. + *TODO: Document spreading an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array literal*. The rules above mean that an array literal is always of an array type, unless it is contextually typed by a tuple-like type. For example @@ -2619,7 +2689,7 @@ A super call invokes the constructor of the base class on the instance reference The type of a super call expression is Void. -The JavaScript code generated for a super call is specified in section [8.6.2](#8.6.2). +The JavaScript code generated for a super call is specified in section [8.7.2](#8.7.2). ### 4.9.2 Super Property Access @@ -2632,7 +2702,7 @@ Super property accesses are not permitted in other contexts, and it is not possi Super property accesses are typically used to access overridden base class member functions from derived class member functions. For an example of this, see section [8.4.2](#8.4.2). -The JavaScript code generated for a super property access is specified in section [8.6.2](#8.6.2). +The JavaScript code generated for a super property access is specified in section [8.7.2](#8.7.2). *TODO: Update section to include [bracket notation in super property access](https://github.com/Microsoft/TypeScript/issues/3970)*. @@ -2777,7 +2847,7 @@ object . name where *object* is an expression and *name* is an identifier (including, possibly, a reserved word), is used to access the property with the given name on the given object. A dot notation property access is processed as follows at compile-time: * If *object* is of type Any, any *name* is permitted and the property access is of type Any. -* Otherwise, if *name* denotes an accessible apparent property (section [3.11.1](#3.11.1)) in the type of *object*, the property access is of the type of that property. Public members are always accessible, but private and protected members of a class have restricted accessibility, as described in [8.2.2](#8.2.2). +* Otherwise, if *name* denotes an accessible apparent property (section [3.11.1](#3.11.1)) in the widened type (section [3.12](#3.12)) of *object*, the property access is of the type of that property. Public members are always accessible, but private and protected members of a class have restricted accessibility, as described in [8.2.2](#8.2.2). * Otherwise, the property access is invalid and a compile-time error occurs. A bracket notation property access of the form @@ -2892,7 +2962,7 @@ Given a signature < *T1* , *T2* , … , *Tn* Type argument inference produces a set of candidate types for each type parameter. Given a type parameter *T* and set of candidate types, the actual inferred type argument is determined as follows: * If the set of candidate argument types is empty, the inferred type argument for *T* is *T*'s constraint. -* Otherwise, if at least one of the candidate types is a supertype of all of the other candidate types, let *C* denote the first such candidate type. If *C* satisfies *T*'s constraint, the inferred type argument for *T* is *C*. Otherwise, the inferred type argument for *T* is *T*'s constraint. +* Otherwise, if at least one of the candidate types is a supertype of all of the other candidate types, let *C* denote the widened form (section [3.12](#3.12)) of the first such candidate type. If *C* satisfies *T*'s constraint, the inferred type argument for *T* is *C*. Otherwise, the inferred type argument for *T* is *T*'s constraint. * Otherwise, if no candidate type is a supertype of all of the other candidate types, type inference has fails and no type argument is inferred for *T*. In order to compute candidate types, the argument list is processed as follows: @@ -3030,6 +3100,8 @@ if (shape instanceof Circle) { } ``` +*TODO: Document [as operator](https://github.com/Microsoft/TypeScript/pull/3564)*. + ## 4.17 JSX Expressions *TODO: Document [JSX expressions](https://github.com/Microsoft/TypeScript/issues/3203)*. @@ -3106,6 +3178,8 @@ These operators require their operands to be of type Any, the Number primitive t |String|||||| |Other|||||| +*TODO: Document the [exponentation operator](https://github.com/Microsoft/TypeScript/issues/4812)*. + ### 4.19.2 The + operator The binary + operator requires both operands to be of the Number primitive type or an enum type, or at least one of the operands to be of type Any or the String primitive type. Operands of an enum type are treated as having the primitive type Number. If one operand is the `null` or `undefined` value, it is treated as having the type of the other operand. If both operands are of the Number primitive type, the result is of the Number primitive type. If one or both operands are of the String primitive type, the result is of the String primitive type. Otherwise, the result is of type Any. @@ -3218,7 +3292,7 @@ is subject to the same requirements, and produces a value of the same type, as t ### 4.21.1 Destructuring Assignment -A ***destructuring assignment*** is an assignment operation in which the left hand operand is a destructuring assignment pattern as defined by the *AssignmentPattern* production in the ECMAScript 6 specification. +A ***destructuring assignment*** is an assignment operation in which the left hand operand is a destructuring assignment pattern as defined by the *AssignmentPattern* production in the ECMAScript 2015 specification. In a destructuring assignment expression, the type of the expression on the right must be assignable to the assignment target on the left. An expression of type *S* is considered assignable to an assignment target *V* if one of the following is true: @@ -3233,9 +3307,11 @@ In a destructuring assignment expression, the type of the expression on the righ * *S* is a tuple-like type (section [3.3.3](#3.3.3)) with a property named *N* of a type that is assignable to the target given in *E*, where *N* is the numeric index of *E* in the array assignment pattern, or * *S* is not a tuple-like type and the numeric index signature type of *S* is assignable to the target given in *E*. +*TODO: [Update to specify behavior when assignment element E is a rest element](https://github.com/Microsoft/TypeScript/issues/2713)*. + In an assignment property or element that includes a default value, the type of the default value must be assignable to the target given in the assignment property or element. -When the output target is ECMAScript 6 or higher, destructuring variable assignments remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring variable assignments are rewritten to series of simple assignments. For example, the destructuring assignment +When the output target is ECMAScript 2015 or higher, destructuring variable assignments remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring variable assignments are rewritten to series of simple assignments. For example, the destructuring assignment ```TypeScript var x = 1; @@ -3360,6 +3436,8 @@ In the rules above, when a narrowing operation would remove all constituent type Note that type guards affect types of variables and parameters only and have no effect on members of objects such as properties. Also note that it is possible to defeat a type guard by calling a function that changes the type of the guarded variable. +*TODO: Document [user defined type guard functions](https://github.com/Microsoft/TypeScript/issues/1007)*. + In the example ```TypeScript @@ -3432,7 +3510,7 @@ This chapter describes the static type checking TypeScript provides for JavaScri ## 5.1 Blocks -Blocks are extended to include local interface, type alias, and enum declarations (classes are already included by the ECMAScript 6 grammar). +Blocks are extended to include local interface, type alias, and enum declarations (classes are already included by the ECMAScript 2015 grammar).   *Declaration:* *( Modified )*    … @@ -3549,7 +3627,9 @@ The type *T* associated with a binding element is determined as follows: When a destructuring variable declaration, binding property, or binding element specifies an initializer expression, the type of the initializer expression is required to be assignable to the widened form of the type associated with the destructuring variable declaration, binding property, or binding element. -When the output target is ECMAScript 6 or higher, except for removing the optional type annotation, destructuring variable declarations remain unchanged in the emitted JavaScript code. +*TODO: Update rules to reflect [improved checking of destructuring with literal initializers](https://github.com/Microsoft/TypeScript/pull/4598)*. + +When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring variable declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring variable declarations are rewritten to simple variable declarations. For example, an object destructuring declaration of the form @@ -3805,7 +3885,7 @@ function g(x: number) { the inferred return type for 'f' and 'g' is Any because the functions reference themselves through a cycle with no return type annotations. Adding an explicit return type 'number' to either breaks the cycle and causes the return type 'number' to be inferred for the other. -An explicitly typed function whose return type isn't the Void or the Any type must have at least one return statement somewhere in its body. An exception to this rule is if the function implementation consists of a single 'throw' statement. +An explicitly typed function whose return type isn't the Void type, the Any type, or a union type containing the Void or Any type as a constituent must have at least one return statement somewhere in its body. An exception to this rule is if the function implementation consists of a single 'throw' statement. The type of 'this' in a function implementation is the Any type. @@ -3855,7 +3935,7 @@ The type of local introduced in a destructuring parameter declaration is determi * Otherwise, if the parameter is a rest parameter, *T* is `any[]`. * Otherwise, *T* is `any`. -When the output target is ECMAScript 6 or higher, except for removing the optional type annotation, destructuring parameter declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring parameter declarations are rewritten to local variable declarations. +When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring parameter declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring parameter declarations are rewritten to local variable declarations. The example @@ -3965,9 +4045,13 @@ where *Parameter* is the parameter name and *Default* is the default value expre *TODO: Document [generator functions](https://github.com/Microsoft/TypeScript/issues/2873)*. -## 6.8 Type Guard Functions +## 6.8 Asynchronous Functions -*TODO: Document [type guard functions](https://github.com/Microsoft/TypeScript/issues/1007)*. +*TODO: Document [asynchronous functions](https://github.com/Microsoft/TypeScript/issues/1664)*. + +## 6.9 Type Guard Functions + +*TODO: Document [type guard functions](https://github.com/Microsoft/TypeScript/issues/1007), including [this type predicates](https://github.com/Microsoft/TypeScript/pull/5906)*.
@@ -4016,7 +4100,7 @@ The following constraints must be satisfied by an interface declaration or other * An interface cannot declare a property with the same name as an inherited private or protected property. * Inherited properties with the same name must be identical (section [3.11.2](#3.11.2)). * All properties of the interface must satisfy the constraints implied by the index signatures of the interface as specified in section [3.9.4](#3.9.4). -* The instance type (section [3.7.1](#3.7.1)) of the declared interface must be assignable (section [3.11.4](#3.11.4)) to each of the base type references. +* The this-type (section [3.6.3](#3.6.3)) of the declared interface must be assignable (section [3.11.4](#3.11.4)) to each of the base type references. An interface is permitted to inherit identical members from multiple base types and will in that case only contain one occurrence of each particular member. @@ -4090,6 +4174,8 @@ interface Document { Note that the members of the last interface declaration appear first in the merged declaration. Also note that the relative order of members declared in the same interface body is preserved. +*TODO: Document [class and interface declaration merging](https://github.com/Microsoft/TypeScript/pull/3333)*. + ##
7.3 Interfaces Extending Classes When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. When a class containing private or protected members is the base type of an interface type, that interface type can only be implemented by that class or a descendant class. For example: @@ -4193,13 +4279,13 @@ var Point: { }; ``` -The context in which a class is referenced distinguishes between the class instance type and the constructor function. For example, in the assignment statement +The context in which a class is referenced distinguishes between the class type and the constructor function. For example, in the assignment statement ```TypeScript var p: Point = new Point(10, 20); ``` -the identifier 'Point' in the type annotation refers to the class instance type, whereas the identifier 'Point' in the `new` expression refers to the constructor function object. +the identifier 'Point' in the type annotation refers to the class type, whereas the identifier 'Point' in the `new` expression refers to the constructor function object. ### 8.1.1 Class Heritage Specification @@ -4225,7 +4311,7 @@ The following constraints must be satisfied by the class heritage specification * If present, the type reference specified in the `extends` clause must denote a class type. Furthermore, the *TypeName* part of the type reference is required to be a reference to the class constructor function when evaluated as an expression. * A class declaration may not, directly or indirectly, specify a base class that originates in the same declaration. In other words a class cannot, directly or indirectly, be a base class of itself, regardless of type arguments. -* The instance type (section [3.7.1](#3.7.1)) of the declared class must be assignable (section [3.11.4](#3.11.4)) to the base type reference and each of the type references listed in the `implements` clause. +* The this-type (section [3.6.3](#3.6.3)) of the declared class must be assignable (section [3.11.4](#3.11.4)) to the base type reference and each of the type references listed in the `implements` clause. * The constructor function type created by the class declaration must be assignable to the base class constructor function type, ignoring construct signatures. The following example illustrates a situation in which the first rule above would be violated: @@ -4266,7 +4352,7 @@ The members of a class consist of the members introduced through member declarat Members are either ***instance members*** or ***static members***. -Instance members are members of the class type (section [8.2.4](#8.2.4)) and its associated instance type. Within constructors, instance member functions, and instance member accessors, the type of `this` is the instance type (section [3.7.1](#3.7.1)) of the class. +Instance members are members of the class type (section [8.2.4](#8.2.4)) and its associated this-type. Within constructors, instance member functions, and instance member accessors, the type of `this` is the this-type (section [3.6.3](#3.6.3)) of the class. Static members are declared using the `static` modifier and are members of the constructor function type (section [8.2.5](#8.2.5)). Within static member functions and static member accessors, the type of `this` is the constructor function type. @@ -4280,7 +4366,7 @@ Public property members can be accessed everywhere without restrictions. Private property members can be accessed only within their declaring class. Specifically, a private member *M* declared in a class *C* can be accessed only within the class body of *C*. -Protected property members can be accessed only within their declaring class and classes derived from their declaring class, and a protected instance property member must be accessed *through* an instance of the enclosing class. Specifically, a protected member *M* declared in a class *C* can be accessed only within the class body of *C* or the class body of a class derived from *C*. Furthermore, when a protected instance member *M* is accessed in a property access *E*`.`*M* within the body of a class *D*, the type of *E* is required to be *D* or a type that directly or indirectly has *D* as a base type, regardless of type arguments. +Protected property members can be accessed only within their declaring class and classes derived from their declaring class, and a protected instance property member must be accessed *through* an instance of the enclosing class or a subclass thereof. Specifically, a protected member *M* declared in a class *C* can be accessed only within the class body of *C* or the class body of a class derived from *C*. Furthermore, when a protected instance member *M* is accessed in a property access *E*`.`*M* within the body of a class *D*, the type of *E* is required to be *D* or a type that directly or indirectly has *D* as a base type, regardless of type arguments. Private and protected accessibility is enforced only at compile-time and serves as no more than an *indication of intent*. Since JavaScript provides no mechanism to create private and protected properties on an object, it is not possible to enforce the private and protected modifiers in dynamic code at run-time. For example, private and protected accessibility can be defeated by changing an object's static type to Any and accessing the member dynamically. @@ -4326,14 +4412,14 @@ An index member in a derived class is said to override an index member in a base ### 8.2.4 Class Types -A class declaration declares a new named type (section [3.7](#3.7)) called a class type. Within the constructor and member functions of a class, the type of `this` is the instance type (section [3.7.1](#3.7.1)) of this class type. The class type has the following members: +A class declaration declares a new named type (section [3.7](#3.7)) called a class type. Within the constructor and instance member functions of a class, the type of `this` is the this-type (section [3.6.3](#3.6.3)) of that class type. The class type has the following members: * A property for each instance member variable declaration in the class body. * A property of a function type for each instance member function declaration in the class body. * A property for each uniquely named instance member accessor declaration in the class body. * A property for each constructor parameter declared with a `public`, `private`, or `protected` modifier. * An index signature for each instance index member declaration in the class body. -* All base class instance type property or index members that are not overridden in the class. +* All base class instance property or index members that are not overridden in the class. All instance property members (including those that are private or protected) of a class must satisfy the constraints implied by the index members of the class as specified in section [3.9.4](#3.9.4). @@ -4353,7 +4439,7 @@ class B extends A { } ``` -the instance type of 'A' is +the class type of 'A' is equivalent to ```TypeScript interface A { @@ -4363,7 +4449,7 @@ interface A { } ``` -and the instance type of 'B' is +and the class type of 'B' is equivalent to ```TypeScript interface B { @@ -4374,16 +4460,16 @@ interface B { } ``` -Note that static declarations in a class do not contribute to the class type and its instance type—rather, static declarations introduce properties on the constructor function object. Also note that the declaration of 'g' in 'B' overrides the member inherited from 'A'. +Note that static declarations in a class do not contribute to the class type—rather, static declarations introduce properties on the constructor function object. Also note that the declaration of 'g' in 'B' overrides the member inherited from 'A'. ### 8.2.5 Constructor Function Types The type of the constructor function introduced by a class declaration is called the constructor function type. The constructor function type has the following members: -* If the class contains no constructor declaration and has no base class, a single construct signature with no parameters, having the same type parameters as the class and returning the instance type of the class. -* If the class contains no constructor declaration and has a base class, a set of construct signatures with the same parameters as those of the base class constructor function type following substitution of type parameters with the type arguments specified in the base class type reference, all having the same type parameters as the class and returning the instance type of the class. -* If the class contains a constructor declaration with no overloads, a construct signature with the parameter list of the constructor implementation, having the same type parameters as the class and returning the instance type of the class. -* If the class contains a constructor declaration with overloads, a set of construct signatures with the parameter lists of the overloads, all having the same type parameters as the class and returning the instance type of the class. +* If the class contains no constructor declaration and has no base class, a single construct signature with no parameters, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. +* If the class contains no constructor declaration and has a base class, a set of construct signatures with the same parameters as those of the base class constructor function type following substitution of type parameters with the type arguments specified in the base class type reference, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. +* If the class contains a constructor declaration with no overloads, a construct signature with the parameter list of the constructor implementation, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. +* If the class contains a constructor declaration with overloads, a set of construct signatures with the parameter lists of the overloads, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments. * A property for each static member variable declaration in the class body. * A property of a function type for each static member function declaration in the class body. * A property for each uniquely named static member accessor declaration in the class body. @@ -4428,7 +4514,7 @@ var TwoArrays: { } ``` -Note that the construct signatures in the constructor function types have the same type parameters as their class and return the instance type of their class. Also note that when a derived class doesn't declare a constructor, type arguments from the base class reference are substituted before construct signatures are propagated from the base constructor function type to the derived constructor function type. +Note that each construct signature in the constructor function types has the same type parameters as its class and returns an instantiation of its class with those type parameters passed as type arguments. Also note that when a derived class doesn't declare a constructor, type arguments from the base class reference are substituted before construct signatures are propagated from the base constructor function type to the derived constructor function type. ## 8.3 Constructor Declarations @@ -4446,7 +4532,7 @@ When a class has constructor overloads, the overloads determine the construct si When a class has both constructor overloads and a constructor implementation, the overloads must precede the implementation and all of the declarations must be consecutive with no intervening grammatical elements. -The function body of a constructor is permitted to contain return statements. If return statements specify expressions, those expressions must be of types that are assignable to the instance type of the class. +The function body of a constructor is permitted to contain return statements. If return statements specify expressions, those expressions must be of types that are assignable to the this-type (section [3.6.3](#3.6.3)) of the class. The type parameters of a generic class are in scope and accessible in a constructor declaration. @@ -4478,6 +4564,8 @@ class Point { } ``` +A parameter property declaration may declare an optional parameter (by including a question mark or a default value), but the property introduced by such a declaration is always considered a required property (section [3.3.6](#3.3.6)). + ### 8.3.2 Super Calls Super calls (section [4.9.1](#4.9.1)) are used to call the constructor of the base class. A super call consists of the keyword `super` followed by an argument list enclosed in parentheses. For example: @@ -4524,7 +4612,7 @@ Property member declarations can be member variable declarations, member functio    *MemberFunctionDeclaration*    *MemberAccessorDeclaration* -Member declarations without a `static` modifier are called instance member declarations. Instance property member declarations declare properties in the class instance type (section [8.2.4](#8.2.4)), and must specify names that are unique among all instance property member and parameter property declarations in the containing class, with the exception that instance get and set accessor declarations may pairwise specify the same name. +Member declarations without a `static` modifier are called instance member declarations. Instance property member declarations declare properties in the class type (section [8.2.4](#8.2.4)), and must specify names that are unique among all instance property member and parameter property declarations in the containing class, with the exception that instance get and set accessor declarations may pairwise specify the same name. Member declarations with a `static` modifier are called static member declarations. Static property member declarations declare properties in the constructor function type (section [8.2.5](#8.2.5)), and must specify names that are unique among all static property member declarations in the containing class, with the exception that static get and set accessor declarations may pairwise specify the same name. @@ -4549,7 +4637,7 @@ class Point { } ``` -The class instance type 'Point' has the members: +The class type 'Point' has the members: ```TypeScript interface Point { @@ -4578,7 +4666,7 @@ A member variable declaration declares an instance member variable or a static m The type associated with a member variable declaration is determined in the same manner as an ordinary variable declaration (see section [5.2](#5.2)). -An instance member variable declaration introduces a member in the class instance type and optionally initializes a property on instances of the class. Initializers in instance member variable declarations are executed once for every new instance of the class and are equivalent to assignments to properties of `this` in the constructor. In an initializer expression for an instance member variable, `this` is of the class instance type. +An instance member variable declaration introduces a member in the class type and optionally initializes a property on instances of the class. Initializers in instance member variable declarations are executed once for every new instance of the class and are equivalent to assignments to properties of `this` in the constructor. In an initializer expression for an instance member variable, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. A static member variable declaration introduces a property in the constructor function type and optionally initializes a property on the constructor function object. Initializers in static member variable declarations are executed once when the containing script or module is loaded. @@ -4625,7 +4713,7 @@ A member function declaration is processed in the same manner as an ordinary fun All declarations for the same member function must specify the same accessibility (public, private, or protected) and kind (instance or static). -An instance member function declaration declares a property in the class instance type and assigns a function object to a property on the prototype object of the class. In the body of an instance member function declaration, `this` is of the class instance type. +An instance member function declaration declares a property in the class type and assigns a function object to a property on the prototype object of the class. In the body of an instance member function declaration, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. A static member function declaration declares a property in the constructor function type and assigns a function object to a property on the constructor function object. In the body of a static member function declaration, the type of `this` is the constructor function type. @@ -4691,23 +4779,23 @@ Get and set accessors are processed in the same manner as in an object literal ( Accessors for the same member name must specify the same accessibility. -An instance member accessor declaration declares a property in the class instance type and defines a property on the prototype object of the class with a get or set accessor. In the body of an instance member accessor declaration, `this` is of the class instance type. +An instance member accessor declaration declares a property in the class type and defines a property on the prototype object of the class with a get or set accessor. In the body of an instance member accessor declaration, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class. A static member accessor declaration declares a property in the constructor function type and defines a property on the constructor function object of the class with a get or set accessor. In the body of a static member accessor declaration, the type of `this` is the constructor function type. -Get and set accessors are emitted as calls to 'Object.defineProperty' in the generated JavaScript, as described in section [8.6.1](#8.6.1). +Get and set accessors are emitted as calls to 'Object.defineProperty' in the generated JavaScript, as described in section [8.7.1](#8.7.1). ### 8.4.4 Dynamic Property Declarations If the *PropertyName* of a property member declaration is a computed property name that doesn't denote a well-known symbol ([2.2.3](#2.2.3)), the construct is considered a ***dynamic property declaration***. The following rules apply to dynamic property declarations: -* A dynamic property declaration does not introduce a property in the class instance type or constructor function type. +* A dynamic property declaration does not introduce a property in the class type or constructor function type. * The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type. * The name associated with a dynamic property declarations is considered to be a numeric property name if the property name expression is of type Any or the Number primitive type. ## 8.5 Index Member Declarations -An index member declaration introduces an index signature (section [3.9.4](#3.9.4)) in the class instance type. +An index member declaration introduces an index signature (section [3.9.4](#3.9.4)) in the class type.   *IndexMemberDeclaration:*    *IndexSignature* `;` @@ -4720,11 +4808,15 @@ It is not possible to declare index members for the static side of a class. Note that it is seldom meaningful to include a string index signature in a class because it constrains all instance properties of the class. However, numeric index signatures can be useful to control the element type when a class is used in an array-like manner. -## 8.6 Code Generation +## 8.6 Decorators -When the output target is ECMAScript 6 or higher, type parameters, implements clauses, accessibility modifiers, and member variable declarations are removed in the emitted code, but otherwise class declarations are emitted as written. When the output target is ECMAScript 3 or 5, more comprehensive rewrites are performed, as described in this section. +*TODO: Document [decorators](https://github.com/Microsoft/TypeScript/issues/2249)*. -### 8.6.1 Classes Without Extends Clauses +## 8.7 Code Generation + +When the output target is ECMAScript 2015 or higher, type parameters, implements clauses, accessibility modifiers, and member variable declarations are removed in the emitted code, but otherwise class declarations are emitted as written. When the output target is ECMAScript 3 or 5, more comprehensive rewrites are performed, as described in this section. + +### 8.7.1 Classes Without Extends Clauses A class with no `extends` clause generates JavaScript equivalent to the following: @@ -4828,7 +4920,7 @@ where *MemberName* is the name of the member accessor, *GetAccessorStatements* i where *MemberName* is the name of the static variable, and *InitializerExpression* is the code generated for the initializer expression. -### 8.6.2 Classes With Extends Clauses +### 8.7.2 Classes With Extends Clauses A class with an `extends` clause generates JavaScript equivalent to the following: @@ -5396,7 +5488,7 @@ This copies a reference to the entity into a property on the namespace instance. # 11 Scripts and Modules -TypeScript implements support for ECMAScript 6 modules and supports down-level code generation targeting CommonJS, AMD, and other module systems. +TypeScript implements support for ECMAScript 2015 modules and supports down-level code generation targeting CommonJS, AMD, and other module systems. ## 11.1 Programs and Source Files @@ -5424,7 +5516,7 @@ When a TypeScript program is compiled, all of the program's source files are pro The TypeScript compiler automatically determines a source file's dependencies and includes those dependencies in the program being compiled. The determination is made from "reference comments" and module import declarations as follows: -* A comment of the form /// <reference path="…"/> adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file. +* A comment of the form /// <reference path="…"/> that occurs before the first token in a source file adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file. * A module import declaration that specifies a relative module name (section [11.3.1](#11.3.1)) resolves the name relative to the directory of the containing source file. If a source file with the resulting path and file extension '.ts' exists, that file is added as a dependency. Otherwise, if a source file with the resulting path and file extension '.d.ts' exists, that file is added as a dependency. * A module import declaration that specifies a top-level module name (section [11.3.1](#11.3.1)) resolves the name in a host dependent manner (typically by resolving the name relative to a module name space root or searching for the name in a series of directories). If a source file with extension '.ts' or '.d.ts' corresponding to the reference is located, that file is added as a dependency. @@ -5539,7 +5631,7 @@ TypeScript supports multiple patterns of JavaScript code generation for modules: * CommonJS. This format is used by server frameworks such as node.js. * AMD (Asynchronous Module Definition). This format is used by asynchronous module loaders such as RequireJS. * UMD (Universal Module Definition). A variation of the AMD format that allows modules to also be loaded by CommonJS loaders. -* System. This format is used to represent ECMAScript 6 semantics with high fidelity in down-level environments. +* System. This format is used to represent ECMAScript 2015 semantics with high fidelity in down-level environments. The desired module code generation pattern is selected through a compiler option and does not affect the TypeScript source code. Indeed, it is possible to author modules that can be compiled for use both on the server side (e.g. using node.js) and on the client side (using an AMD compliant loader) with no changes to the TypeScript source code. @@ -5620,7 +5712,7 @@ An import require declaration of the form import m = require("mod"); ``` -is equivalent to the ECMAScript 6 import declaration +is equivalent to the ECMAScript 2015 import declaration ```TypeScript import * as m from "mod"; @@ -5828,16 +5920,17 @@ The 'main' and 'log' example from section [11.3](#11.3) above generates the foll File main.js: ```TypeScript -var log = require("./log"); -log.message("hello"); +var log_1 = require("./log"); +log_1.message("hello"); ``` File log.js: ```TypeScript -exports.message = function(s) { +function message(s) { console.log(s); -} +} +exports.message = message; ``` A module import declaration is represented in the generated JavaScript as a variable initialized by a call to the 'require' function provided by the module system host. A variable declaration and 'require' call is emitted for a particular imported module only if the imported module, or a local alias (section [10.3](#10.3)) that references the imported module, is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *NamespaceName* or *TypeQueryExpression*, nothing is emitted. @@ -5850,15 +5943,15 @@ File geometry.ts: export interface Point { x: number; y: number }; export function point(x: number, y: number): Point { - return { x: x, y: y }; + return { x, y }; } ``` File game.ts: ```TypeScript -import g = require("./geometry"); -var p = g.point(10, 20); +import * as g from "./geometry"; +let p = g.point(10, 20); ``` The 'game' module references the imported 'geometry' module in an expression (through its alias 'g') and a 'require' call is therefore included in the emitted JavaScript: @@ -5871,8 +5964,8 @@ var p = g.point(10, 20); Had the 'game' module instead been written to only reference 'geometry' in a type position ```TypeScript -import g = require("./geometry"); -var p: g.Point = { x: 10, y: 20 }; +import * as g from "./geometry"; +let p: g.Point = { x: 10, y: 20 }; ``` the emitted JavaScript would have no dependency on the 'geometry' module and would simply be @@ -5890,8 +5983,8 @@ The "main" and "log" example from above generates the following JavaScript code File main.js: ```TypeScript -define(["require", "exports", "./log"], function(require, exports, log) { - log.message("hello"); +define(["require", "exports", "./log"], function(require, exports, log_1) { + log_1.message("hello"); } ``` @@ -5899,9 +5992,10 @@ File log.js: ```TypeScript define(["require", "exports"], function(require, exports) { - exports.message = function(s) { + function message(s) { console.log(s); } + exports.message = message; } ``` @@ -5957,7 +6051,7 @@ Ambient function declarations cannot specify a function bodies and do not permit ### 12.1.3 Ambient Class Declarations -An ambient class declaration declares a class instance type and a constructor function in the containing declaration space. +An ambient class declaration declares a class type and a constructor function in the containing declaration space.   *AmbientClassDeclaration:*    `class` *BindingIdentifier* *TypeParametersopt* *ClassHeritage* `{` *AmbientClassBody* `}` @@ -6057,7 +6151,7 @@ declare module "io" { # A Grammar -This appendix contains a summary of the grammar found in the main document. As described in section [2.1](#2.1), the TypeScript grammar is a superset of the grammar defined in the [ECMAScript Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) (specifically, the ECMA-262 Standard, 6th Edition) and this appendix lists only productions that are new or modified from the ECMAScript grammar. +This appendix contains a summary of the grammar found in the main document. As described in section [2.1](#2.1), the TypeScript grammar is a superset of the grammar defined in the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition) and this appendix lists only productions that are new or modified from the ECMAScript grammar. ## A.1 Types @@ -6104,7 +6198,8 @@ This appendix contains a summary of the grammar found in the main document. As d    *ObjectType*    *ArrayType*    *TupleType* -   *TypeQuery* +   *TypeQuery* +   *ThisType*   *ParenthesizedType:*    `(` *Type* `)` @@ -6179,6 +6274,9 @@ This appendix contains a summary of the grammar found in the main document. As d    *IdentifierReference*    *TypeQueryExpression* `.` *IdentifierName* +  *ThisType:* +   `this` +   *PropertySignature:*    *PropertyName* `?`*opt* *TypeAnnotationopt* diff --git a/doc/wiki/README.md b/doc/wiki/README.md new file mode 100644 index 00000000000..19961197840 --- /dev/null +++ b/doc/wiki/README.md @@ -0,0 +1,6 @@ +# The TypeScript Wiki + +To read the wiki, [visit the wiki on GitHub](https://github.com/Microsoft/TypeScript/wiki). + +To contribute by filing an issue or sending a pull request, [visit the wiki repository](https://github.com/Microsoft/TypeScript-wiki). + diff --git a/issue_template.md b/issue_template.md new file mode 100644 index 00000000000..dcd2280570c --- /dev/null +++ b/issue_template.md @@ -0,0 +1,27 @@ + + +**TypeScript Version:** + +1.7.5 / 1.8.0-beta / nightly (1.9.0-dev.20160217) + +**Code** + +```ts +// A self-contained demonstration of the problem follows... + +``` + +**Expected behavior:** + +**Actual behavior:** diff --git a/lib/README.md b/lib/README.md index b2837989505..852d449f1e5 100644 --- a/lib/README.md +++ b/lib/README.md @@ -1,4 +1,5 @@ -# Read this! +# Read This! -These files are not meant to be edited by hand. -If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. \ No newline at end of file +**These files are not meant to be edited by hand.** +If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. +Running `jake LKG` will then appropriately update the files in this directory. diff --git a/lib/lib.core.d.ts b/lib/lib.core.d.ts index 50fd8a8e495..c1843f5207e 100644 --- a/lib/lib.core.d.ts +++ b/lib/lib.core.d.ts @@ -14,13 +14,12 @@ and limitations under the License. ***************************************************************************** */ /// - ///////////////////////////// /// ECMAScript APIs ///////////////////////////// -declare var NaN: number; -declare var Infinity: number; +declare const NaN: number; +declare const Infinity: number; /** * Evaluates JavaScript code and executes it. @@ -130,7 +129,7 @@ interface ObjectConstructor { (value: any): any; /** A reference to the prototype for a class of objects. */ - prototype: Object; + readonly prototype: Object; /** * Returns the prototype of an object. @@ -221,7 +220,7 @@ interface ObjectConstructor { /** * Provides functionality common to all JavaScript objects. */ -declare var Object: ObjectConstructor; +declare const Object: ObjectConstructor; /** * Creates a new function. @@ -250,7 +249,7 @@ interface Function { bind(thisArg: any, ...argArray: any[]): any; prototype: any; - length: number; + readonly length: number; // Non-standard extensions arguments: any; @@ -264,10 +263,10 @@ interface FunctionConstructor { */ new (...args: string[]): Function; (...args: string[]): Function; - prototype: Function; + readonly prototype: Function; } -declare var Function: FunctionConstructor; +declare const Function: FunctionConstructor; interface IArguments { [index: number]: any; @@ -415,7 +414,7 @@ interface String { trim(): string; /** Returns the length of a String object. */ - length: number; + readonly length: number; // IE extensions /** @@ -428,20 +427,20 @@ interface String { /** Returns the primitive value of the specified object. */ valueOf(): string; - [index: number]: string; + readonly [index: number]: string; } interface StringConstructor { new (value?: any): String; (value?: any): string; - prototype: String; + readonly prototype: String; fromCharCode(...codes: number[]): string; } /** * Allows manipulation and formatting of text strings and determination and location of substrings within strings. */ -declare var String: StringConstructor; +declare const String: StringConstructor; interface Boolean { /** Returns the primitive value of the specified object. */ @@ -451,10 +450,10 @@ interface Boolean { interface BooleanConstructor { new (value?: any): Boolean; (value?: any): boolean; - prototype: Boolean; + readonly prototype: Boolean; } -declare var Boolean: BooleanConstructor; +declare const Boolean: BooleanConstructor; interface Number { /** @@ -488,57 +487,57 @@ interface Number { interface NumberConstructor { new (value?: any): Number; (value?: any): number; - prototype: Number; + readonly prototype: Number; /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ - MAX_VALUE: number; + readonly MAX_VALUE: number; /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ - MIN_VALUE: number; + readonly MIN_VALUE: number; /** * A value that is not a number. * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. */ - NaN: number; + readonly NaN: number; /** * A value that is less than the largest negative number that can be represented in JavaScript. * JavaScript displays NEGATIVE_INFINITY values as -infinity. */ - NEGATIVE_INFINITY: number; + readonly NEGATIVE_INFINITY: number; /** * A value greater than the largest number that can be represented in JavaScript. * JavaScript displays POSITIVE_INFINITY values as infinity. */ - POSITIVE_INFINITY: number; + readonly POSITIVE_INFINITY: number; } /** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ -declare var Number: NumberConstructor; +declare const Number: NumberConstructor; interface TemplateStringsArray extends Array { - raw: string[]; + readonly raw: string[]; } interface Math { /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ - E: number; + readonly E: number; /** The natural logarithm of 10. */ - LN10: number; + readonly LN10: number; /** The natural logarithm of 2. */ - LN2: number; + readonly LN2: number; /** The base-2 logarithm of e. */ - LOG2E: number; + readonly LOG2E: number; /** The base-10 logarithm of e. */ - LOG10E: number; + readonly LOG10E: number; /** Pi. This is the ratio of the circumference of a circle to its diameter. */ - PI: number; + readonly PI: number; /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ - SQRT1_2: number; + readonly SQRT1_2: number; /** The square root of 2. */ - SQRT2: number; + readonly SQRT2: number; /** * Returns the absolute value of a number (the value without regard to whether it is positive or negative). * For example, the absolute value of -5 is the same as the absolute value of 5. @@ -631,7 +630,7 @@ interface Math { tan(x: number): number; } /** An intrinsic object that provides basic mathematics functionality and constants. */ -declare var Math: Math; +declare const Math: Math; /** Enables basic storage and retrieval of dates and times. */ interface Date { @@ -793,7 +792,7 @@ interface DateConstructor { new (value: string): Date; new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; - prototype: Date; + readonly prototype: Date; /** * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. * @param s A date string @@ -813,7 +812,7 @@ interface DateConstructor { now(): number; } -declare var Date: DateConstructor; +declare const Date: DateConstructor; interface RegExpMatchArray extends Array { index?: number; @@ -839,16 +838,16 @@ interface RegExp { test(string: string): boolean; /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ - source: string; + readonly source: string; /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ - global: boolean; + readonly global: boolean; /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ - ignoreCase: boolean; + readonly ignoreCase: boolean; /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ - multiline: boolean; + readonly multiline: boolean; lastIndex: number; @@ -859,7 +858,7 @@ interface RegExp { interface RegExpConstructor { new (pattern: string, flags?: string): RegExp; (pattern: string, flags?: string): RegExp; - prototype: RegExp; + readonly prototype: RegExp; // Non-standard extensions $1: string; @@ -874,7 +873,7 @@ interface RegExpConstructor { lastMatch: string; } -declare var RegExp: RegExpConstructor; +declare const RegExp: RegExpConstructor; interface Error { name: string; @@ -884,10 +883,10 @@ interface Error { interface ErrorConstructor { new (message?: string): Error; (message?: string): Error; - prototype: Error; + readonly prototype: Error; } -declare var Error: ErrorConstructor; +declare const Error: ErrorConstructor; interface EvalError extends Error { } @@ -895,10 +894,10 @@ interface EvalError extends Error { interface EvalErrorConstructor { new (message?: string): EvalError; (message?: string): EvalError; - prototype: EvalError; + readonly prototype: EvalError; } -declare var EvalError: EvalErrorConstructor; +declare const EvalError: EvalErrorConstructor; interface RangeError extends Error { } @@ -906,10 +905,10 @@ interface RangeError extends Error { interface RangeErrorConstructor { new (message?: string): RangeError; (message?: string): RangeError; - prototype: RangeError; + readonly prototype: RangeError; } -declare var RangeError: RangeErrorConstructor; +declare const RangeError: RangeErrorConstructor; interface ReferenceError extends Error { } @@ -917,10 +916,10 @@ interface ReferenceError extends Error { interface ReferenceErrorConstructor { new (message?: string): ReferenceError; (message?: string): ReferenceError; - prototype: ReferenceError; + readonly prototype: ReferenceError; } -declare var ReferenceError: ReferenceErrorConstructor; +declare const ReferenceError: ReferenceErrorConstructor; interface SyntaxError extends Error { } @@ -928,10 +927,10 @@ interface SyntaxError extends Error { interface SyntaxErrorConstructor { new (message?: string): SyntaxError; (message?: string): SyntaxError; - prototype: SyntaxError; + readonly prototype: SyntaxError; } -declare var SyntaxError: SyntaxErrorConstructor; +declare const SyntaxError: SyntaxErrorConstructor; interface TypeError extends Error { } @@ -939,10 +938,10 @@ interface TypeError extends Error { interface TypeErrorConstructor { new (message?: string): TypeError; (message?: string): TypeError; - prototype: TypeError; + readonly prototype: TypeError; } -declare var TypeError: TypeErrorConstructor; +declare const TypeError: TypeErrorConstructor; interface URIError extends Error { } @@ -950,10 +949,10 @@ interface URIError extends Error { interface URIErrorConstructor { new (message?: string): URIError; (message?: string): URIError; - prototype: URIError; + readonly prototype: URIError; } -declare var URIError: URIErrorConstructor; +declare const URIError: URIErrorConstructor; interface JSON { /** @@ -998,13 +997,115 @@ interface JSON { /** * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. */ -declare var JSON: JSON; +declare const JSON: JSON; ///////////////////////////// /// ECMAScript Array API (specially handled by compiler) ///////////////////////////// +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat>(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + + readonly [n: number]: T; +} + interface Array { /** * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. @@ -1028,12 +1129,7 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: U[]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: T[]): T[]; + concat(...items: (T | T[])[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1053,19 +1149,16 @@ interface Array { * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): T[]; - /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: T, b: T) => number): T[]; - /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. */ splice(start: number): T[]; - /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. @@ -1073,62 +1166,53 @@ interface Array { * @param items Elements to insert into the array in place of the deleted elements. */ splice(start: number, deleteCount: number, ...items: T[]): T[]; - /** * Inserts new elements at the start of an array. * @param items Elements to insert at the start of the Array. */ unshift(...items: T[]): number; - /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; - /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. */ lastIndexOf(searchElement: T, fromIndex?: number): number; - /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; - /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; - /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1141,7 +1225,6 @@ interface Array { * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. @@ -1166,10 +1249,10 @@ interface ArrayConstructor { (arrayLength: number): T[]; (...items: T[]): T[]; isArray(arg: any): arg is Array; - prototype: Array; + readonly prototype: Array; } -declare var Array: ArrayConstructor; +declare const Array: ArrayConstructor; interface TypedPropertyDescriptor { enumerable?: boolean; @@ -1199,11 +1282,10 @@ interface PromiseLike { } interface ArrayLike { - length: number; - [n: number]: T; + readonly length: number; + readonly [n: number]: T; } - /** * Represents a raw buffer of binary data, which is used to store data for the * different typed arrays. ArrayBuffers cannot be read from or written to directly, @@ -1214,7 +1296,7 @@ interface ArrayBuffer { /** * Read-only. The length of the ArrayBuffer (in bytes). */ - byteLength: number; + readonly byteLength: number; /** * Returns a section of an ArrayBuffer. @@ -1223,11 +1305,11 @@ interface ArrayBuffer { } interface ArrayBufferConstructor { - prototype: ArrayBuffer; + readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } -declare var ArrayBuffer: ArrayBufferConstructor; +declare const ArrayBuffer: ArrayBufferConstructor; interface ArrayBufferView { /** @@ -1247,9 +1329,9 @@ interface ArrayBufferView { } interface DataView { - buffer: ArrayBuffer; - byteLength: number; - byteOffset: number; + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; /** * Gets the Float32 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. @@ -1377,7 +1459,7 @@ interface DataView { interface DataViewConstructor { new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; } -declare var DataView: DataViewConstructor; +declare const DataView: DataViewConstructor; /** * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested @@ -1387,22 +1469,22 @@ interface Int8Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -1501,7 +1583,7 @@ interface Int8Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -1625,7 +1707,7 @@ interface Int8Array { [index: number]: number; } interface Int8ArrayConstructor { - prototype: Int8Array; + readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; @@ -1633,7 +1715,7 @@ interface Int8ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -1650,7 +1732,7 @@ interface Int8ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } -declare var Int8Array: Int8ArrayConstructor; +declare const Int8Array: Int8ArrayConstructor; /** * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the @@ -1660,22 +1742,22 @@ interface Uint8Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -1774,7 +1856,7 @@ interface Uint8Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -1899,7 +1981,7 @@ interface Uint8Array { } interface Uint8ArrayConstructor { - prototype: Uint8Array; + readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; @@ -1907,7 +1989,7 @@ interface Uint8ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -1924,7 +2006,7 @@ interface Uint8ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } -declare var Uint8Array: Uint8ArrayConstructor; +declare const Uint8Array: Uint8ArrayConstructor; /** * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. @@ -1934,22 +2016,22 @@ interface Uint8ClampedArray { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2048,7 +2130,7 @@ interface Uint8ClampedArray { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2173,7 +2255,7 @@ interface Uint8ClampedArray { } interface Uint8ClampedArrayConstructor { - prototype: Uint8ClampedArray; + readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; @@ -2181,7 +2263,7 @@ interface Uint8ClampedArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -2197,7 +2279,7 @@ interface Uint8ClampedArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } -declare var Uint8ClampedArray: Uint8ClampedArrayConstructor; +declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; /** * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the @@ -2207,22 +2289,22 @@ interface Int16Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2321,7 +2403,7 @@ interface Int16Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2446,7 +2528,7 @@ interface Int16Array { } interface Int16ArrayConstructor { - prototype: Int16Array; + readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; @@ -2454,7 +2536,7 @@ interface Int16ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -2471,7 +2553,7 @@ interface Int16ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } -declare var Int16Array: Int16ArrayConstructor; +declare const Int16Array: Int16ArrayConstructor; /** * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the @@ -2481,22 +2563,22 @@ interface Uint16Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2595,7 +2677,7 @@ interface Uint16Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2720,7 +2802,7 @@ interface Uint16Array { } interface Uint16ArrayConstructor { - prototype: Uint16Array; + readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; @@ -2728,7 +2810,7 @@ interface Uint16ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -2745,7 +2827,7 @@ interface Uint16ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } -declare var Uint16Array: Uint16ArrayConstructor; +declare const Uint16Array: Uint16ArrayConstructor; /** * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. @@ -2754,22 +2836,22 @@ interface Int32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2868,7 +2950,7 @@ interface Int32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2993,7 +3075,7 @@ interface Int32Array { } interface Int32ArrayConstructor { - prototype: Int32Array; + readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; @@ -3001,7 +3083,7 @@ interface Int32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3017,7 +3099,7 @@ interface Int32ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } -declare var Int32Array: Int32ArrayConstructor; +declare const Int32Array: Int32ArrayConstructor; /** * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the @@ -3027,22 +3109,22 @@ interface Uint32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3141,7 +3223,7 @@ interface Uint32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3266,7 +3348,7 @@ interface Uint32Array { } interface Uint32ArrayConstructor { - prototype: Uint32Array; + readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; @@ -3274,7 +3356,7 @@ interface Uint32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3290,7 +3372,7 @@ interface Uint32ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } -declare var Uint32Array: Uint32ArrayConstructor; +declare const Uint32Array: Uint32ArrayConstructor; /** * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number @@ -3300,22 +3382,22 @@ interface Float32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3414,7 +3496,7 @@ interface Float32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3539,7 +3621,7 @@ interface Float32Array { } interface Float32ArrayConstructor { - prototype: Float32Array; + readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; @@ -3547,7 +3629,7 @@ interface Float32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3564,7 +3646,7 @@ interface Float32ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } -declare var Float32Array: Float32ArrayConstructor; +declare const Float32Array: Float32ArrayConstructor; /** * A typed array of 64-bit float values. The contents are initialized to 0. If the requested @@ -3574,22 +3656,22 @@ interface Float64Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3688,7 +3770,7 @@ interface Float64Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3813,7 +3895,7 @@ interface Float64Array { } interface Float64ArrayConstructor { - prototype: Float64Array; + readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; @@ -3821,7 +3903,7 @@ interface Float64ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3837,4 +3919,4 @@ interface Float64ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } -declare var Float64Array: Float64ArrayConstructor; +declare const Float64Array: Float64ArrayConstructor; diff --git a/lib/lib.core.es6.d.ts b/lib/lib.core.es6.d.ts index 857f5957a45..4ccdd73c614 100644 --- a/lib/lib.core.es6.d.ts +++ b/lib/lib.core.es6.d.ts @@ -14,13 +14,12 @@ and limitations under the License. ***************************************************************************** */ /// - ///////////////////////////// /// ECMAScript APIs ///////////////////////////// -declare var NaN: number; -declare var Infinity: number; +declare const NaN: number; +declare const Infinity: number; /** * Evaluates JavaScript code and executes it. @@ -130,7 +129,7 @@ interface ObjectConstructor { (value: any): any; /** A reference to the prototype for a class of objects. */ - prototype: Object; + readonly prototype: Object; /** * Returns the prototype of an object. @@ -221,7 +220,7 @@ interface ObjectConstructor { /** * Provides functionality common to all JavaScript objects. */ -declare var Object: ObjectConstructor; +declare const Object: ObjectConstructor; /** * Creates a new function. @@ -250,7 +249,7 @@ interface Function { bind(thisArg: any, ...argArray: any[]): any; prototype: any; - length: number; + readonly length: number; // Non-standard extensions arguments: any; @@ -264,10 +263,10 @@ interface FunctionConstructor { */ new (...args: string[]): Function; (...args: string[]): Function; - prototype: Function; + readonly prototype: Function; } -declare var Function: FunctionConstructor; +declare const Function: FunctionConstructor; interface IArguments { [index: number]: any; @@ -415,7 +414,7 @@ interface String { trim(): string; /** Returns the length of a String object. */ - length: number; + readonly length: number; // IE extensions /** @@ -428,20 +427,20 @@ interface String { /** Returns the primitive value of the specified object. */ valueOf(): string; - [index: number]: string; + readonly [index: number]: string; } interface StringConstructor { new (value?: any): String; (value?: any): string; - prototype: String; + readonly prototype: String; fromCharCode(...codes: number[]): string; } /** * Allows manipulation and formatting of text strings and determination and location of substrings within strings. */ -declare var String: StringConstructor; +declare const String: StringConstructor; interface Boolean { /** Returns the primitive value of the specified object. */ @@ -451,10 +450,10 @@ interface Boolean { interface BooleanConstructor { new (value?: any): Boolean; (value?: any): boolean; - prototype: Boolean; + readonly prototype: Boolean; } -declare var Boolean: BooleanConstructor; +declare const Boolean: BooleanConstructor; interface Number { /** @@ -488,57 +487,57 @@ interface Number { interface NumberConstructor { new (value?: any): Number; (value?: any): number; - prototype: Number; + readonly prototype: Number; /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ - MAX_VALUE: number; + readonly MAX_VALUE: number; /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ - MIN_VALUE: number; + readonly MIN_VALUE: number; /** * A value that is not a number. * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. */ - NaN: number; + readonly NaN: number; /** * A value that is less than the largest negative number that can be represented in JavaScript. * JavaScript displays NEGATIVE_INFINITY values as -infinity. */ - NEGATIVE_INFINITY: number; + readonly NEGATIVE_INFINITY: number; /** * A value greater than the largest number that can be represented in JavaScript. * JavaScript displays POSITIVE_INFINITY values as infinity. */ - POSITIVE_INFINITY: number; + readonly POSITIVE_INFINITY: number; } /** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ -declare var Number: NumberConstructor; +declare const Number: NumberConstructor; interface TemplateStringsArray extends Array { - raw: string[]; + readonly raw: string[]; } interface Math { /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ - E: number; + readonly E: number; /** The natural logarithm of 10. */ - LN10: number; + readonly LN10: number; /** The natural logarithm of 2. */ - LN2: number; + readonly LN2: number; /** The base-2 logarithm of e. */ - LOG2E: number; + readonly LOG2E: number; /** The base-10 logarithm of e. */ - LOG10E: number; + readonly LOG10E: number; /** Pi. This is the ratio of the circumference of a circle to its diameter. */ - PI: number; + readonly PI: number; /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ - SQRT1_2: number; + readonly SQRT1_2: number; /** The square root of 2. */ - SQRT2: number; + readonly SQRT2: number; /** * Returns the absolute value of a number (the value without regard to whether it is positive or negative). * For example, the absolute value of -5 is the same as the absolute value of 5. @@ -631,7 +630,7 @@ interface Math { tan(x: number): number; } /** An intrinsic object that provides basic mathematics functionality and constants. */ -declare var Math: Math; +declare const Math: Math; /** Enables basic storage and retrieval of dates and times. */ interface Date { @@ -793,7 +792,7 @@ interface DateConstructor { new (value: string): Date; new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; - prototype: Date; + readonly prototype: Date; /** * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. * @param s A date string @@ -813,7 +812,7 @@ interface DateConstructor { now(): number; } -declare var Date: DateConstructor; +declare const Date: DateConstructor; interface RegExpMatchArray extends Array { index?: number; @@ -839,16 +838,16 @@ interface RegExp { test(string: string): boolean; /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ - source: string; + readonly source: string; /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ - global: boolean; + readonly global: boolean; /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ - ignoreCase: boolean; + readonly ignoreCase: boolean; /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ - multiline: boolean; + readonly multiline: boolean; lastIndex: number; @@ -859,7 +858,7 @@ interface RegExp { interface RegExpConstructor { new (pattern: string, flags?: string): RegExp; (pattern: string, flags?: string): RegExp; - prototype: RegExp; + readonly prototype: RegExp; // Non-standard extensions $1: string; @@ -874,7 +873,7 @@ interface RegExpConstructor { lastMatch: string; } -declare var RegExp: RegExpConstructor; +declare const RegExp: RegExpConstructor; interface Error { name: string; @@ -884,10 +883,10 @@ interface Error { interface ErrorConstructor { new (message?: string): Error; (message?: string): Error; - prototype: Error; + readonly prototype: Error; } -declare var Error: ErrorConstructor; +declare const Error: ErrorConstructor; interface EvalError extends Error { } @@ -895,10 +894,10 @@ interface EvalError extends Error { interface EvalErrorConstructor { new (message?: string): EvalError; (message?: string): EvalError; - prototype: EvalError; + readonly prototype: EvalError; } -declare var EvalError: EvalErrorConstructor; +declare const EvalError: EvalErrorConstructor; interface RangeError extends Error { } @@ -906,10 +905,10 @@ interface RangeError extends Error { interface RangeErrorConstructor { new (message?: string): RangeError; (message?: string): RangeError; - prototype: RangeError; + readonly prototype: RangeError; } -declare var RangeError: RangeErrorConstructor; +declare const RangeError: RangeErrorConstructor; interface ReferenceError extends Error { } @@ -917,10 +916,10 @@ interface ReferenceError extends Error { interface ReferenceErrorConstructor { new (message?: string): ReferenceError; (message?: string): ReferenceError; - prototype: ReferenceError; + readonly prototype: ReferenceError; } -declare var ReferenceError: ReferenceErrorConstructor; +declare const ReferenceError: ReferenceErrorConstructor; interface SyntaxError extends Error { } @@ -928,10 +927,10 @@ interface SyntaxError extends Error { interface SyntaxErrorConstructor { new (message?: string): SyntaxError; (message?: string): SyntaxError; - prototype: SyntaxError; + readonly prototype: SyntaxError; } -declare var SyntaxError: SyntaxErrorConstructor; +declare const SyntaxError: SyntaxErrorConstructor; interface TypeError extends Error { } @@ -939,10 +938,10 @@ interface TypeError extends Error { interface TypeErrorConstructor { new (message?: string): TypeError; (message?: string): TypeError; - prototype: TypeError; + readonly prototype: TypeError; } -declare var TypeError: TypeErrorConstructor; +declare const TypeError: TypeErrorConstructor; interface URIError extends Error { } @@ -950,10 +949,10 @@ interface URIError extends Error { interface URIErrorConstructor { new (message?: string): URIError; (message?: string): URIError; - prototype: URIError; + readonly prototype: URIError; } -declare var URIError: URIErrorConstructor; +declare const URIError: URIErrorConstructor; interface JSON { /** @@ -998,13 +997,115 @@ interface JSON { /** * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. */ -declare var JSON: JSON; +declare const JSON: JSON; ///////////////////////////// /// ECMAScript Array API (specially handled by compiler) ///////////////////////////// +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat>(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + + readonly [n: number]: T; +} + interface Array { /** * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. @@ -1028,12 +1129,7 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: U[]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: T[]): T[]; + concat(...items: (T | T[])[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1053,19 +1149,16 @@ interface Array { * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): T[]; - /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: T, b: T) => number): T[]; - /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. */ splice(start: number): T[]; - /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. @@ -1073,62 +1166,53 @@ interface Array { * @param items Elements to insert into the array in place of the deleted elements. */ splice(start: number, deleteCount: number, ...items: T[]): T[]; - /** * Inserts new elements at the start of an array. * @param items Elements to insert at the start of the Array. */ unshift(...items: T[]): number; - /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; - /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. */ lastIndexOf(searchElement: T, fromIndex?: number): number; - /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; - /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; - /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1141,7 +1225,6 @@ interface Array { * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. @@ -1166,10 +1249,10 @@ interface ArrayConstructor { (arrayLength: number): T[]; (...items: T[]): T[]; isArray(arg: any): arg is Array; - prototype: Array; + readonly prototype: Array; } -declare var Array: ArrayConstructor; +declare const Array: ArrayConstructor; interface TypedPropertyDescriptor { enumerable?: boolean; @@ -1199,11 +1282,10 @@ interface PromiseLike { } interface ArrayLike { - length: number; - [n: number]: T; + readonly length: number; + readonly [n: number]: T; } - /** * Represents a raw buffer of binary data, which is used to store data for the * different typed arrays. ArrayBuffers cannot be read from or written to directly, @@ -1214,7 +1296,7 @@ interface ArrayBuffer { /** * Read-only. The length of the ArrayBuffer (in bytes). */ - byteLength: number; + readonly byteLength: number; /** * Returns a section of an ArrayBuffer. @@ -1223,11 +1305,11 @@ interface ArrayBuffer { } interface ArrayBufferConstructor { - prototype: ArrayBuffer; + readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } -declare var ArrayBuffer: ArrayBufferConstructor; +declare const ArrayBuffer: ArrayBufferConstructor; interface ArrayBufferView { /** @@ -1247,9 +1329,9 @@ interface ArrayBufferView { } interface DataView { - buffer: ArrayBuffer; - byteLength: number; - byteOffset: number; + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; /** * Gets the Float32 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. @@ -1377,7 +1459,7 @@ interface DataView { interface DataViewConstructor { new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; } -declare var DataView: DataViewConstructor; +declare const DataView: DataViewConstructor; /** * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested @@ -1387,22 +1469,22 @@ interface Int8Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -1501,7 +1583,7 @@ interface Int8Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -1625,7 +1707,7 @@ interface Int8Array { [index: number]: number; } interface Int8ArrayConstructor { - prototype: Int8Array; + readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; @@ -1633,7 +1715,7 @@ interface Int8ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -1650,7 +1732,7 @@ interface Int8ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } -declare var Int8Array: Int8ArrayConstructor; +declare const Int8Array: Int8ArrayConstructor; /** * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the @@ -1660,22 +1742,22 @@ interface Uint8Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -1774,7 +1856,7 @@ interface Uint8Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -1899,7 +1981,7 @@ interface Uint8Array { } interface Uint8ArrayConstructor { - prototype: Uint8Array; + readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; @@ -1907,7 +1989,7 @@ interface Uint8ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -1924,7 +2006,7 @@ interface Uint8ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } -declare var Uint8Array: Uint8ArrayConstructor; +declare const Uint8Array: Uint8ArrayConstructor; /** * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. @@ -1934,22 +2016,22 @@ interface Uint8ClampedArray { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2048,7 +2130,7 @@ interface Uint8ClampedArray { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2173,7 +2255,7 @@ interface Uint8ClampedArray { } interface Uint8ClampedArrayConstructor { - prototype: Uint8ClampedArray; + readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; @@ -2181,7 +2263,7 @@ interface Uint8ClampedArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -2197,7 +2279,7 @@ interface Uint8ClampedArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } -declare var Uint8ClampedArray: Uint8ClampedArrayConstructor; +declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; /** * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the @@ -2207,22 +2289,22 @@ interface Int16Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2321,7 +2403,7 @@ interface Int16Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2446,7 +2528,7 @@ interface Int16Array { } interface Int16ArrayConstructor { - prototype: Int16Array; + readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; @@ -2454,7 +2536,7 @@ interface Int16ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -2471,7 +2553,7 @@ interface Int16ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } -declare var Int16Array: Int16ArrayConstructor; +declare const Int16Array: Int16ArrayConstructor; /** * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the @@ -2481,22 +2563,22 @@ interface Uint16Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2595,7 +2677,7 @@ interface Uint16Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2720,7 +2802,7 @@ interface Uint16Array { } interface Uint16ArrayConstructor { - prototype: Uint16Array; + readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; @@ -2728,7 +2810,7 @@ interface Uint16ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -2745,7 +2827,7 @@ interface Uint16ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } -declare var Uint16Array: Uint16ArrayConstructor; +declare const Uint16Array: Uint16ArrayConstructor; /** * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. @@ -2754,22 +2836,22 @@ interface Int32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2868,7 +2950,7 @@ interface Int32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2993,7 +3075,7 @@ interface Int32Array { } interface Int32ArrayConstructor { - prototype: Int32Array; + readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; @@ -3001,7 +3083,7 @@ interface Int32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3017,7 +3099,7 @@ interface Int32ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } -declare var Int32Array: Int32ArrayConstructor; +declare const Int32Array: Int32ArrayConstructor; /** * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the @@ -3027,22 +3109,22 @@ interface Uint32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3141,7 +3223,7 @@ interface Uint32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3266,7 +3348,7 @@ interface Uint32Array { } interface Uint32ArrayConstructor { - prototype: Uint32Array; + readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; @@ -3274,7 +3356,7 @@ interface Uint32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3290,7 +3372,7 @@ interface Uint32ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } -declare var Uint32Array: Uint32ArrayConstructor; +declare const Uint32Array: Uint32ArrayConstructor; /** * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number @@ -3300,22 +3382,22 @@ interface Float32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3414,7 +3496,7 @@ interface Float32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3539,7 +3621,7 @@ interface Float32Array { } interface Float32ArrayConstructor { - prototype: Float32Array; + readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; @@ -3547,7 +3629,7 @@ interface Float32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3564,7 +3646,7 @@ interface Float32ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } -declare var Float32Array: Float32ArrayConstructor; +declare const Float32Array: Float32ArrayConstructor; /** * A typed array of 64-bit float values. The contents are initialized to 0. If the requested @@ -3574,22 +3656,22 @@ interface Float64Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3688,7 +3770,7 @@ interface Float64Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3813,7 +3895,7 @@ interface Float64Array { } interface Float64ArrayConstructor { - prototype: Float64Array; + readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; @@ -3821,7 +3903,7 @@ interface Float64ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3837,7 +3919,7 @@ interface Float64ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } -declare var Float64Array: Float64ArrayConstructor; +declare const Float64Array: Float64ArrayConstructor; declare type PropertyKey = string | number | symbol; interface Symbol { @@ -3847,14 +3929,14 @@ interface Symbol { /** Returns the primitive value of the specified object. */ valueOf(): Object; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "Symbol"; } interface SymbolConstructor { /** * A reference to the prototype. */ - prototype: Symbol; + readonly prototype: Symbol; /** * Returns a new unique Symbol value. @@ -3882,67 +3964,67 @@ interface SymbolConstructor { * A method that determines if a constructor object recognizes an object as one of the * constructor’s instances. Called by the semantics of the instanceof operator. */ - hasInstance: symbol; + readonly hasInstance: symbol; /** * A Boolean value that if true indicates that an object should flatten to its array elements * by Array.prototype.concat. */ - isConcatSpreadable: symbol; + readonly isConcatSpreadable: symbol; /** * A method that returns the default iterator for an object. Called by the semantics of the * for-of statement. */ - iterator: symbol; + readonly iterator: symbol; /** * A regular expression method that matches the regular expression against a string. Called * by the String.prototype.match method. */ - match: symbol; + readonly match: symbol; /** * A regular expression method that replaces matched substrings of a string. Called by the * String.prototype.replace method. */ - replace: symbol; + readonly replace: symbol; /** * A regular expression method that returns the index within a string that matches the * regular expression. Called by the String.prototype.search method. */ - search: symbol; + readonly search: symbol; /** * A function valued property that is the constructor function that is used to create * derived objects. */ - species: symbol; + readonly species: symbol; /** * A regular expression method that splits a string at the indices that match the regular * expression. Called by the String.prototype.split method. */ - split: symbol; + readonly split: symbol; /** * A method that converts an object to a corresponding primitive value. * Called by the ToPrimitive abstract operation. */ - toPrimitive: symbol; + readonly toPrimitive: symbol; /** * A String value that is used in the creation of the default string description of an object. * Called by the built-in method Object.prototype.toString. */ - toStringTag: symbol; + readonly toStringTag: symbol; /** * An Object whose own property names are property names that are excluded from the 'with' * environment bindings of the associated objects. */ - unscopables: symbol; + readonly unscopables: symbol; } declare var Symbol: SymbolConstructor; @@ -4040,7 +4122,7 @@ interface Function { /** * Returns the name of the function. Function names are read-only and can not be changed. */ - name: string; + readonly name: string; /** * Determines whether the given value inherits from this function if this function was used @@ -4058,7 +4140,7 @@ interface NumberConstructor { * that is representable as a Number value, which is approximately: * 2.2204460492503130808472633361816 x 10‍â’‍16. */ - EPSILON: number; + readonly EPSILON: number; /** * Returns true if passed value is finite. @@ -4093,14 +4175,14 @@ interface NumberConstructor { * a Number value. * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 â’ 1. */ - MAX_SAFE_INTEGER: number; + readonly MAX_SAFE_INTEGER: number; /** * The value of the smallest integer n such that n and n â’ 1 are both exactly representable as * a Number value. * The value of Number.MIN_SAFE_INTEGER is â’9007199254740991 (â’(2^53 â’ 1)). */ - MIN_SAFE_INTEGER: number; + readonly MIN_SAFE_INTEGER: number; /** * Converts a string to a floating-point number. @@ -4405,7 +4487,7 @@ interface IterableIterator extends Iterator { } interface GeneratorFunction extends Function { - + readonly [Symbol.toStringTag]: "GeneratorFunction"; } interface GeneratorFunctionConstructor { @@ -4415,7 +4497,7 @@ interface GeneratorFunctionConstructor { */ new (...args: string[]): GeneratorFunction; (...args: string[]): GeneratorFunction; - prototype: GeneratorFunction; + readonly prototype: GeneratorFunction; } declare var GeneratorFunction: GeneratorFunctionConstructor; @@ -4530,7 +4612,7 @@ interface Math { */ cbrt(x: number): number; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "Math"; } interface Date { @@ -4616,19 +4698,19 @@ interface RegExp { * * If no flags are set, the value is the empty string. */ - flags: string; + readonly flags: string; /** * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular * expression. Default is false. Read-only. */ - sticky: boolean; + readonly sticky: boolean; /** * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular * expression. Default is false. Read-only. */ - unicode: boolean; + readonly unicode: boolean; } interface RegExpConstructor { @@ -4644,17 +4726,17 @@ interface Map { has(key: K): boolean; keys(): IterableIterator; set(key: K, value?: V): Map; - size: number; + readonly size: number; values(): IterableIterator; [Symbol.iterator]():IterableIterator<[K,V]>; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "Map"; } interface MapConstructor { new (): Map; new (): Map; new (iterable: Iterable<[K, V]>): Map; - prototype: Map; + readonly prototype: Map; } declare var Map: MapConstructor; @@ -4664,14 +4746,14 @@ interface WeakMap { get(key: K): V; has(key: K): boolean; set(key: K, value?: V): WeakMap; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "WeakMap"; } interface WeakMapConstructor { new (): WeakMap; new (): WeakMap; new (iterable: Iterable<[K, V]>): WeakMap; - prototype: WeakMap; + readonly prototype: WeakMap; } declare var WeakMap: WeakMapConstructor; @@ -4683,17 +4765,17 @@ interface Set { forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; has(value: T): boolean; keys(): IterableIterator; - size: number; + readonly size: number; values(): IterableIterator; [Symbol.iterator]():IterableIterator; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "Set"; } interface SetConstructor { new (): Set; new (): Set; new (iterable: Iterable): Set; - prototype: Set; + readonly prototype: Set; } declare var Set: SetConstructor; @@ -4702,19 +4784,19 @@ interface WeakSet { clear(): void; delete(value: T): boolean; has(value: T): boolean; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "WeakSet"; } interface WeakSetConstructor { new (): WeakSet; new (): WeakSet; new (iterable: Iterable): WeakSet; - prototype: WeakSet; + readonly prototype: WeakSet; } declare var WeakSet: WeakSetConstructor; interface JSON { - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "JSON"; } /** @@ -4724,11 +4806,11 @@ interface JSON { * buffer as needed. */ interface ArrayBuffer { - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "ArrayBuffer"; } interface DataView { - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "DataView"; } /** @@ -4749,6 +4831,7 @@ interface Int8Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int8Array"; } interface Int8ArrayConstructor { @@ -4781,6 +4864,7 @@ interface Uint8Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "UInt8Array"; } interface Uint8ArrayConstructor { @@ -4816,6 +4900,7 @@ interface Uint8ClampedArray { values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; } interface Uint8ClampedArrayConstructor { @@ -4853,6 +4938,7 @@ interface Int16Array { [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int16Array"; } interface Int16ArrayConstructor { @@ -4885,6 +4971,7 @@ interface Uint16Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint16Array"; } interface Uint16ArrayConstructor { @@ -4917,6 +5004,7 @@ interface Int32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int32Array"; } interface Int32ArrayConstructor { @@ -4949,6 +5037,7 @@ interface Uint32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint32Array"; } interface Uint32ArrayConstructor { @@ -4981,6 +5070,7 @@ interface Float32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Float32Array"; } interface Float32ArrayConstructor { @@ -5013,6 +5103,7 @@ interface Float64Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Float64Array"; } interface Float64ArrayConstructor { @@ -5064,7 +5155,7 @@ declare namespace Reflect { function isExtensible(target: any): boolean; function ownKeys(target: any): Array; function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: any, proto: any): boolean; } @@ -5089,14 +5180,14 @@ interface Promise { catch(onrejected?: (reason: any) => T | PromiseLike): Promise; catch(onrejected?: (reason: any) => void): Promise; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "Promise"; } interface PromiseConstructor { /** * A reference to the prototype. */ - prototype: Promise; + readonly prototype: Promise; /** * Creates a new Promise. @@ -5112,7 +5203,16 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - all(values: Iterable>): Promise; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + all(values: Iterable>): Promise; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved @@ -5149,7 +5249,7 @@ interface PromiseConstructor { */ resolve(): Promise; - [Symbol.species]: Function; + readonly [Symbol.species]: Function; } declare var Promise: PromiseConstructor; diff --git a/lib/lib.core.es7.d.ts b/lib/lib.core.es7.d.ts new file mode 100644 index 00000000000..b5552f62929 --- /dev/null +++ b/lib/lib.core.es7.d.ts @@ -0,0 +1,5344 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +/// +///////////////////////////// +/// ECMAScript APIs +///////////////////////////// + +declare const NaN: number; +declare const Infinity: number; + +/** + * Evaluates JavaScript code and executes it. + * @param x A String value that contains valid JavaScript code. + */ +declare function eval(x: string): any; + +/** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ +declare function parseInt(s: string, radix?: number): number; + +/** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ +declare function parseFloat(string: string): number; + +/** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ +declare function isNaN(number: number): boolean; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): boolean; + +/** + * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). + * @param encodedURI A value representing an encoded URI. + */ +declare function decodeURI(encodedURI: string): string; + +/** + * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). + * @param encodedURIComponent A value representing an encoded URI component. + */ +declare function decodeURIComponent(encodedURIComponent: string): string; + +/** + * Encodes a text string as a valid Uniform Resource Identifier (URI) + * @param uri A value representing an encoded URI. + */ +declare function encodeURI(uri: string): string; + +/** + * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). + * @param uriComponent A value representing an encoded URI component. + */ +declare function encodeURIComponent(uriComponent: string): string; + +interface PropertyDescriptor { + configurable?: boolean; + enumerable?: boolean; + value?: any; + writable?: boolean; + get? (): any; + set? (v: any): void; +} + +interface PropertyDescriptorMap { + [s: string]: PropertyDescriptor; +} + +interface Object { + /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ + constructor: Function; + + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns a date converted to a string using the current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: string): boolean; + + /** + * Determines whether an object exists in another object's prototype chain. + * @param v Another object whose prototype chain is to be checked. + */ + isPrototypeOf(v: Object): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: string): boolean; +} + +interface ObjectConstructor { + new (value?: any): Object; + (): any; + (value: any): any; + + /** A reference to the prototype for a class of objects. */ + readonly prototype: Object; + + /** + * Returns the prototype of an object. + * @param o The object that references the prototype. + */ + getPrototypeOf(o: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + + /** + * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly + * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. + * @param o Object that contains the own properties. + */ + getOwnPropertyNames(o: any): string[]; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + * @param properties JavaScript object that contains one or more property descriptors. + */ + create(o: any, properties?: PropertyDescriptorMap): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor property. + */ + defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; + + /** + * Adds one or more properties to an object, and/or modifies attributes of existing properties. + * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. + * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. + */ + defineProperties(o: any, properties: PropertyDescriptorMap): any; + + /** + * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + seal(o: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: T): T; + + /** + * Prevents the addition of new properties to an object. + * @param o Object to make non-extensible. + */ + preventExtensions(o: T): T; + + /** + * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. + * @param o Object to test. + */ + isSealed(o: any): boolean; + + /** + * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. + * @param o Object to test. + */ + isFrozen(o: any): boolean; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): boolean; + + /** + * Returns the names of the enumerable properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keys(o: any): string[]; +} + +/** + * Provides functionality common to all JavaScript objects. + */ +declare const Object: ObjectConstructor; + +/** + * Creates a new function. + */ +interface Function { + /** + * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. + * @param thisArg The object to be used as the this object. + * @param argArray A set of arguments to be passed to the function. + */ + apply(thisArg: any, argArray?: any): any; + + /** + * Calls a method of an object, substituting another object for the current object. + * @param thisArg The object to be used as the current object. + * @param argArray A list of arguments to be passed to the method. + */ + call(thisArg: any, ...argArray: any[]): any; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg An object to which the this keyword can refer inside the new function. + * @param argArray A list of arguments to be passed to the new function. + */ + bind(thisArg: any, ...argArray: any[]): any; + + prototype: any; + readonly length: number; + + // Non-standard extensions + arguments: any; + caller: Function; +} + +interface FunctionConstructor { + /** + * Creates a new function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): Function; + (...args: string[]): Function; + readonly prototype: Function; +} + +declare const Function: FunctionConstructor; + +interface IArguments { + [index: number]: any; + length: number; + callee: Function; +} + +interface String { + /** Returns a string representation of a string. */ + toString(): string; + + /** + * Returns the character at the specified index. + * @param pos The zero-based index of the desired character. + */ + charAt(pos: number): string; + + /** + * Returns the Unicode value of the character at the specified location. + * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + */ + charCodeAt(index: number): number; + + /** + * Returns a string that contains the concatenation of two or more strings. + * @param strings The strings to append to the end of the string. + */ + concat(...strings: string[]): string; + + /** + * Returns the position of the first occurrence of a substring. + * @param searchString The substring to search for in the string + * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. + */ + indexOf(searchString: string, position?: number): number; + + /** + * Returns the last occurrence of a substring in the string. + * @param searchString The substring to search for. + * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. + */ + lastIndexOf(searchString: string, position?: number): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + */ + localeCompare(that: string): number; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + match(regexp: string): RegExpMatchArray; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. + */ + match(regexp: RegExp): RegExpMatchArray; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string that represents the regular expression. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: string, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string that represents the regular expression. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: RegExp, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: string): number; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: RegExp): number; + + /** + * Returns a section of a string. + * @param start The index to the beginning of the specified portion of stringObj. + * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. + * If this value is not specified, the substring continues to the end of stringObj. + */ + slice(start?: number, end?: number): string; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: string, limit?: number): string[]; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: RegExp, limit?: number): string[]; + + /** + * Returns the substring at the specified location within a String object. + * @param start The zero-based index number indicating the beginning of the substring. + * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. + * If end is omitted, the characters from start through the end of the original string are returned. + */ + substring(start: number, end?: number): string; + + /** Converts all the alphabetic characters in a string to lowercase. */ + toLowerCase(): string; + + /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ + toLocaleLowerCase(): string; + + /** Converts all the alphabetic characters in a string to uppercase. */ + toUpperCase(): string; + + /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ + toLocaleUpperCase(): string; + + /** Removes the leading and trailing white space and line terminator characters from a string. */ + trim(): string; + + /** Returns the length of a String object. */ + readonly length: number; + + // IE extensions + /** + * Gets a substring beginning at the specified location and having the specified length. + * @param from The starting position of the desired substring. The index of the first character in the string is zero. + * @param length The number of characters to include in the returned substring. + */ + substr(from: number, length?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): string; + + readonly [index: number]: string; +} + +interface StringConstructor { + new (value?: any): String; + (value?: any): string; + readonly prototype: String; + fromCharCode(...codes: number[]): string; +} + +/** + * Allows manipulation and formatting of text strings and determination and location of substrings within strings. + */ +declare const String: StringConstructor; + +interface Boolean { + /** Returns the primitive value of the specified object. */ + valueOf(): boolean; +} + +interface BooleanConstructor { + new (value?: any): Boolean; + (value?: any): boolean; + readonly prototype: Boolean; +} + +declare const Boolean: BooleanConstructor; + +interface Number { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. + */ + toString(radix?: number): string; + + /** + * Returns a string representing a number in fixed-point notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toFixed(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented in exponential notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toExponential(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. + * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + */ + toPrecision(precision?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): number; +} + +interface NumberConstructor { + new (value?: any): Number; + (value?: any): number; + readonly prototype: Number; + + /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ + readonly MAX_VALUE: number; + + /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ + readonly MIN_VALUE: number; + + /** + * A value that is not a number. + * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. + */ + readonly NaN: number; + + /** + * A value that is less than the largest negative number that can be represented in JavaScript. + * JavaScript displays NEGATIVE_INFINITY values as -infinity. + */ + readonly NEGATIVE_INFINITY: number; + + /** + * A value greater than the largest number that can be represented in JavaScript. + * JavaScript displays POSITIVE_INFINITY values as infinity. + */ + readonly POSITIVE_INFINITY: number; +} + +/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ +declare const Number: NumberConstructor; + +interface TemplateStringsArray extends Array { + readonly raw: string[]; +} + +interface Math { + /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ + readonly E: number; + /** The natural logarithm of 10. */ + readonly LN10: number; + /** The natural logarithm of 2. */ + readonly LN2: number; + /** The base-2 logarithm of e. */ + readonly LOG2E: number; + /** The base-10 logarithm of e. */ + readonly LOG10E: number; + /** Pi. This is the ratio of the circumference of a circle to its diameter. */ + readonly PI: number; + /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ + readonly SQRT1_2: number; + /** The square root of 2. */ + readonly SQRT2: number; + /** + * Returns the absolute value of a number (the value without regard to whether it is positive or negative). + * For example, the absolute value of -5 is the same as the absolute value of 5. + * @param x A numeric expression for which the absolute value is needed. + */ + abs(x: number): number; + /** + * Returns the arc cosine (or inverse cosine) of a number. + * @param x A numeric expression. + */ + acos(x: number): number; + /** + * Returns the arcsine of a number. + * @param x A numeric expression. + */ + asin(x: number): number; + /** + * Returns the arctangent of a number. + * @param x A numeric expression for which the arctangent is needed. + */ + atan(x: number): number; + /** + * Returns the angle (in radians) from the X axis to a point. + * @param y A numeric expression representing the cartesian y-coordinate. + * @param x A numeric expression representing the cartesian x-coordinate. + */ + atan2(y: number, x: number): number; + /** + * Returns the smallest number greater than or equal to its numeric argument. + * @param x A numeric expression. + */ + ceil(x: number): number; + /** + * Returns the cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cos(x: number): number; + /** + * Returns e (the base of natural logarithms) raised to a power. + * @param x A numeric expression representing the power of e. + */ + exp(x: number): number; + /** + * Returns the greatest number less than or equal to its numeric argument. + * @param x A numeric expression. + */ + floor(x: number): number; + /** + * Returns the natural logarithm (base e) of a number. + * @param x A numeric expression. + */ + log(x: number): number; + /** + * Returns the larger of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + max(...values: number[]): number; + /** + * Returns the smaller of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + min(...values: number[]): number; + /** + * Returns the value of a base expression taken to a specified power. + * @param x The base value of the expression. + * @param y The exponent value of the expression. + */ + pow(x: number, y: number): number; + /** Returns a pseudorandom number between 0 and 1. */ + random(): number; + /** + * Returns a supplied numeric expression rounded to the nearest number. + * @param x The value to be rounded to the nearest number. + */ + round(x: number): number; + /** + * Returns the sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sin(x: number): number; + /** + * Returns the square root of a number. + * @param x A numeric expression. + */ + sqrt(x: number): number; + /** + * Returns the tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tan(x: number): number; +} +/** An intrinsic object that provides basic mathematics functionality and constants. */ +declare const Math: Math; + +/** Enables basic storage and retrieval of dates and times. */ +interface Date { + /** Returns a string representation of a date. The format of the string depends on the locale. */ + toString(): string; + /** Returns a date as a string value. */ + toDateString(): string; + /** Returns a time as a string value. */ + toTimeString(): string; + /** Returns a value as a string value appropriate to the host environment's current locale. */ + toLocaleString(): string; + /** Returns a date as a string value appropriate to the host environment's current locale. */ + toLocaleDateString(): string; + /** Returns a time as a string value appropriate to the host environment's current locale. */ + toLocaleTimeString(): string; + /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ + valueOf(): number; + /** Gets the time value in milliseconds. */ + getTime(): number; + /** Gets the year, using local time. */ + getFullYear(): number; + /** Gets the year using Universal Coordinated Time (UTC). */ + getUTCFullYear(): number; + /** Gets the month, using local time. */ + getMonth(): number; + /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ + getUTCMonth(): number; + /** Gets the day-of-the-month, using local time. */ + getDate(): number; + /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ + getUTCDate(): number; + /** Gets the day of the week, using local time. */ + getDay(): number; + /** Gets the day of the week using Universal Coordinated Time (UTC). */ + getUTCDay(): number; + /** Gets the hours in a date, using local time. */ + getHours(): number; + /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ + getUTCHours(): number; + /** Gets the minutes of a Date object, using local time. */ + getMinutes(): number; + /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ + getUTCMinutes(): number; + /** Gets the seconds of a Date object, using local time. */ + getSeconds(): number; + /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCSeconds(): number; + /** Gets the milliseconds of a Date, using local time. */ + getMilliseconds(): number; + /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCMilliseconds(): number; + /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ + getTimezoneOffset(): number; + /** + * Sets the date and time value in the Date object. + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + */ + setTime(time: number): number; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): number; + /** + * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). + * @param ms A numeric value equal to the millisecond value. + */ + setUTCMilliseconds(ms: number): number; + + /** + * Sets the seconds value in the Date object using local time. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setSeconds(sec: number, ms?: number): number; + /** + * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCSeconds(sec: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using local time. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the hour value in the Date object using local time. + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the hours value in the Date object using Universal Coordinated Time (UTC). + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the numeric day-of-the-month value of the Date object using local time. + * @param date A numeric value equal to the day of the month. + */ + setDate(date: number): number; + /** + * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). + * @param date A numeric value equal to the day of the month. + */ + setUTCDate(date: number): number; + /** + * Sets the month value in the Date object using local time. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. + */ + setMonth(month: number, date?: number): number; + /** + * Sets the month value in the Date object using Universal Coordinated Time (UTC). + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. + */ + setUTCMonth(month: number, date?: number): number; + /** + * Sets the year of the Date object using local time. + * @param year A numeric value for the year. + * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. + * @param date A numeric value equal for the day of the month. + */ + setFullYear(year: number, month?: number, date?: number): number; + /** + * Sets the year value in the Date object using Universal Coordinated Time (UTC). + * @param year A numeric value equal to the year. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. + * @param date A numeric value equal to the day of the month. + */ + setUTCFullYear(year: number, month?: number, date?: number): number; + /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ + toUTCString(): string; + /** Returns a date as a string value in ISO format. */ + toISOString(): string; + /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ + toJSON(key?: any): string; +} + +interface DateConstructor { + new (): Date; + new (value: number): Date; + new (value: string): Date; + new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + (): string; + readonly prototype: Date; + /** + * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. + * @param s A date string + */ + parse(s: string): number; + /** + * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param month The month as an number between 0 and 11 (January to December). + * @param date The date as an number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. + * @param ms An number from 0 to 999 that specifies the milliseconds. + */ + UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + now(): number; +} + +declare const Date: DateConstructor; + +interface RegExpMatchArray extends Array { + index?: number; + input?: string; +} + +interface RegExpExecArray extends Array { + index: number; + input: string; +} + +interface RegExp { + /** + * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. + * @param string The String object or string literal on which to perform the search. + */ + exec(string: string): RegExpExecArray; + + /** + * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. + * @param string String on which to perform the search. + */ + test(string: string): boolean; + + /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ + readonly source: string; + + /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ + readonly global: boolean; + + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + readonly ignoreCase: boolean; + + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + readonly multiline: boolean; + + lastIndex: number; + + // Non-standard extensions + compile(): RegExp; +} + +interface RegExpConstructor { + new (pattern: string, flags?: string): RegExp; + (pattern: string, flags?: string): RegExp; + readonly prototype: RegExp; + + // Non-standard extensions + $1: string; + $2: string; + $3: string; + $4: string; + $5: string; + $6: string; + $7: string; + $8: string; + $9: string; + lastMatch: string; +} + +declare const RegExp: RegExpConstructor; + +interface Error { + name: string; + message: string; +} + +interface ErrorConstructor { + new (message?: string): Error; + (message?: string): Error; + readonly prototype: Error; +} + +declare const Error: ErrorConstructor; + +interface EvalError extends Error { +} + +interface EvalErrorConstructor { + new (message?: string): EvalError; + (message?: string): EvalError; + readonly prototype: EvalError; +} + +declare const EvalError: EvalErrorConstructor; + +interface RangeError extends Error { +} + +interface RangeErrorConstructor { + new (message?: string): RangeError; + (message?: string): RangeError; + readonly prototype: RangeError; +} + +declare const RangeError: RangeErrorConstructor; + +interface ReferenceError extends Error { +} + +interface ReferenceErrorConstructor { + new (message?: string): ReferenceError; + (message?: string): ReferenceError; + readonly prototype: ReferenceError; +} + +declare const ReferenceError: ReferenceErrorConstructor; + +interface SyntaxError extends Error { +} + +interface SyntaxErrorConstructor { + new (message?: string): SyntaxError; + (message?: string): SyntaxError; + readonly prototype: SyntaxError; +} + +declare const SyntaxError: SyntaxErrorConstructor; + +interface TypeError extends Error { +} + +interface TypeErrorConstructor { + new (message?: string): TypeError; + (message?: string): TypeError; + readonly prototype: TypeError; +} + +declare const TypeError: TypeErrorConstructor; + +interface URIError extends Error { +} + +interface URIErrorConstructor { + new (message?: string): URIError; + (message?: string): URIError; + readonly prototype: URIError; +} + +declare const URIError: URIErrorConstructor; + +interface JSON { + /** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + parse(text: string, reviver?: (key: any, value: any) => any): any; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + */ + stringify(value: any): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + */ + stringify(value: any, replacer: (key: string, value: any) => any): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer Array that transforms the results. + */ + stringify(value: any, replacer: any[]): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer: (key: string, value: any) => any, space: string | number): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer Array that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer: any[], space: string | number): string; +} +/** + * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. + */ +declare const JSON: JSON; + + +///////////////////////////// +/// ECMAScript Array API (specially handled by compiler) +///////////////////////////// + +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat>(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + + readonly [n: number]: T; +} + +interface Array { + /** + * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. + */ + length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(...items: T[]): number; + /** + * Removes the last element from an array and returns it. + */ + pop(): T; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Reverses the elements in an Array. + */ + reverse(): T[]; + /** + * Removes the first element from an array and returns it. + */ + shift(): T; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: T, b: T) => number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + */ + splice(start: number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(...items: T[]): number; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + [n: number]: T; +} + +interface ArrayConstructor { + new (arrayLength?: number): any[]; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): arg is Array; + readonly prototype: Array; +} + +declare const Array: ArrayConstructor; + +interface TypedPropertyDescriptor { + enumerable?: boolean; + configurable?: boolean; + writable?: boolean; + value?: T; + get?: () => T; + set?: (value: T) => void; +} + +declare type ClassDecorator = (target: TFunction) => TFunction | void; +declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; +declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; +declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; + +declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike; + +interface PromiseLike { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; +} + +interface ArrayLike { + readonly length: number; + readonly [n: number]: T; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + readonly byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin:number, end?:number): ArrayBuffer; +} + +interface ArrayBufferConstructor { + readonly prototype: ArrayBuffer; + new (byteLength: number): ArrayBuffer; + isView(arg: any): arg is ArrayBufferView; +} +declare const ArrayBuffer: ArrayBufferConstructor; + +interface ArrayBufferView { + /** + * The ArrayBuffer instance referenced by the array. + */ + buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + byteLength: number; + + /** + * The offset in bytes of the array. + */ + byteOffset: number; +} + +interface DataView { + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + /** + * Gets the Float32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat64(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Int8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt8(byteOffset: number): number; + + /** + * Gets the Int16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt16(byteOffset: number, littleEndian?: boolean): number; + /** + * Gets the Int32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint8(byteOffset: number): number; + + /** + * Gets the Uint16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Stores an Float32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setInt8(byteOffset: number, value: number): void; + + /** + * Stores an Int16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setUint8(byteOffset: number, value: number): void; + + /** + * Stores an Uint16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; +} + +interface DataViewConstructor { + new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; +} +declare const DataView: DataViewConstructor; + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Int8Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Int8Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): Int8Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int8Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Int8Array; + + /** + * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} +interface Int8ArrayConstructor { + readonly prototype: Int8Array; + new (length: number): Int8Array; + new (array: ArrayLike): Int8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; + +} +declare const Int8Array: Int8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Uint8Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Uint8Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): Uint8Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Uint8Array; + + /** + * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ArrayConstructor { + readonly prototype: Uint8Array; + new (length: number): Uint8Array; + new (array: ArrayLike): Uint8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; + +} +declare const Uint8Array: Uint8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Uint8ClampedArray; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Uint8ClampedArray; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): Uint8ClampedArray; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8ClampedArray; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint8ClampedArray, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8ClampedArray; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Uint8ClampedArray; + + /** + * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8ClampedArray; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ClampedArrayConstructor { + readonly prototype: Uint8ClampedArray; + new (length: number): Uint8ClampedArray; + new (array: ArrayLike): Uint8ClampedArray; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8ClampedArray; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} +declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Int16Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Int16Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): Int16Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int16Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Int16Array; + + /** + * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int16ArrayConstructor { + readonly prototype: Int16Array; + new (length: number): Int16Array; + new (array: ArrayLike): Int16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; + +} +declare const Int16Array: Int16ArrayConstructor; + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Uint16Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Uint16Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): Uint16Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint16Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Uint16Array; + + /** + * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint16ArrayConstructor { + readonly prototype: Uint16Array; + new (length: number): Uint16Array; + new (array: ArrayLike): Uint16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; + +} +declare const Uint16Array: Uint16ArrayConstructor; +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Int32Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Int32Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): Int32Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Int32Array; + + /** + * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int32ArrayConstructor { + readonly prototype: Int32Array; + new (length: number): Int32Array; + new (array: ArrayLike): Int32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; +} +declare const Int32Array: Int32ArrayConstructor; + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Uint32Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Uint32Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): Uint32Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Uint32Array; + + /** + * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint32ArrayConstructor { + readonly prototype: Uint32Array; + new (length: number): Uint32Array; + new (array: ArrayLike): Uint32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; +} +declare const Uint32Array: Uint32ArrayConstructor; + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Float32Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Float32Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): Float32Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Float32Array; + + /** + * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float32ArrayConstructor { + readonly prototype: Float32Array; + new (length: number): Float32Array; + new (array: ArrayLike): Float32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; + +} +declare const Float32Array: Float32ArrayConstructor; + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Float64Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Float64Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): Float64Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float64Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Float64Array; + + /** + * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float64Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float64ArrayConstructor { + readonly prototype: Float64Array; + new (length: number): Float64Array; + new (array: ArrayLike): Float64Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; +} +declare const Float64Array: Float64ArrayConstructor; +declare type PropertyKey = string | number | symbol; + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + readonly [Symbol.toStringTag]: "Symbol"; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string|number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string; + + // Well-known Symbols + + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} +declare var Symbol: SymbolConstructor; + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ + assign(target: any, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + */ + setPrototypeOf(o: any, proto: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: string; + + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍â’‍16. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 â’ 1. + */ + readonly MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n â’ 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is â’9007199254740991 (â’(2^53 â’ 1)). + */ + readonly MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: T) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): T[]; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): T[]; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + // Overloads for objects with methods of well-known symbols. + + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray; }): RegExpMatchArray; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + +interface IteratorResult { + done: boolean; + value?: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface GeneratorFunction extends Function { + readonly [Symbol.toStringTag]: "GeneratorFunction"; +} + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + (...args: string[]): GeneratorFunction; + readonly prototype: GeneratorFunction; +} +declare var GeneratorFunction: GeneratorFunctionConstructor; + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or â’0, the result is +0. + */ + hypot(...values: number[] ): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; + + readonly [Symbol.toStringTag]: "Math"; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; + + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + [Symbol.species](): RegExpConstructor; +} + +interface Map { + clear(): void; + delete(key: K): boolean; + entries(): IterableIterator<[K, V]>; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V; + has(key: K): boolean; + keys(): IterableIterator; + set(key: K, value?: V): Map; + readonly size: number; + values(): IterableIterator; + [Symbol.iterator]():IterableIterator<[K,V]>; + readonly [Symbol.toStringTag]: "Map"; +} + +interface MapConstructor { + new (): Map; + new (): Map; + new (iterable: Iterable<[K, V]>): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface WeakMap { + clear(): void; + delete(key: K): boolean; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): WeakMap; + readonly [Symbol.toStringTag]: "WeakMap"; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (): WeakMap; + new (iterable: Iterable<[K, V]>): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + entries(): IterableIterator<[T, T]>; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + keys(): IterableIterator; + readonly size: number; + values(): IterableIterator; + [Symbol.iterator]():IterableIterator; + readonly [Symbol.toStringTag]: "Set"; +} + +interface SetConstructor { + new (): Set; + new (): Set; + new (iterable: Iterable): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface WeakSet { + add(value: T): WeakSet; + clear(): void; + delete(value: T): boolean; + has(value: T): boolean; + readonly [Symbol.toStringTag]: "WeakSet"; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (): WeakSet; + new (iterable: Iterable): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; + +interface JSON { + readonly [Symbol.toStringTag]: "JSON"; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + readonly [Symbol.toStringTag]: "ArrayBuffer"; +} + +interface DataView { + readonly [Symbol.toStringTag]: "DataView"; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int8Array"; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + + + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int16Array"; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int32Array"; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Float32Array"; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Float64Array"; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; +} + +interface ProxyHandler { + getPrototypeOf? (target: T): any; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, thisArg: any, argArray?: any): any; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T +} +declare var Proxy: ProxyConstructor; + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): IterableIterator; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: string): boolean; + function has(target: any, propertyKey: symbol): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; +} + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: (reason: any) => T | PromiseLike): Promise; + catch(onrejected?: (reason: any) => void): Promise; + + readonly [Symbol.toStringTag]: "Promise"; +} + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + all(values: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; + + readonly [Symbol.species]: Function; +} + +declare var Promise: PromiseConstructor; +interface Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: T, fromIndex?: number): boolean; +} + +interface Int8Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint8Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint8ClampedArray { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Int16Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint16Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Int32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Float32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Float64Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} \ No newline at end of file diff --git a/lib/lib.d.ts b/lib/lib.d.ts index fd4c05da220..68245cdefbf 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -14,13 +14,12 @@ and limitations under the License. ***************************************************************************** */ /// - ///////////////////////////// /// ECMAScript APIs ///////////////////////////// -declare var NaN: number; -declare var Infinity: number; +declare const NaN: number; +declare const Infinity: number; /** * Evaluates JavaScript code and executes it. @@ -130,7 +129,7 @@ interface ObjectConstructor { (value: any): any; /** A reference to the prototype for a class of objects. */ - prototype: Object; + readonly prototype: Object; /** * Returns the prototype of an object. @@ -221,7 +220,7 @@ interface ObjectConstructor { /** * Provides functionality common to all JavaScript objects. */ -declare var Object: ObjectConstructor; +declare const Object: ObjectConstructor; /** * Creates a new function. @@ -250,7 +249,7 @@ interface Function { bind(thisArg: any, ...argArray: any[]): any; prototype: any; - length: number; + readonly length: number; // Non-standard extensions arguments: any; @@ -264,10 +263,10 @@ interface FunctionConstructor { */ new (...args: string[]): Function; (...args: string[]): Function; - prototype: Function; + readonly prototype: Function; } -declare var Function: FunctionConstructor; +declare const Function: FunctionConstructor; interface IArguments { [index: number]: any; @@ -415,7 +414,7 @@ interface String { trim(): string; /** Returns the length of a String object. */ - length: number; + readonly length: number; // IE extensions /** @@ -428,20 +427,20 @@ interface String { /** Returns the primitive value of the specified object. */ valueOf(): string; - [index: number]: string; + readonly [index: number]: string; } interface StringConstructor { new (value?: any): String; (value?: any): string; - prototype: String; + readonly prototype: String; fromCharCode(...codes: number[]): string; } /** * Allows manipulation and formatting of text strings and determination and location of substrings within strings. */ -declare var String: StringConstructor; +declare const String: StringConstructor; interface Boolean { /** Returns the primitive value of the specified object. */ @@ -451,10 +450,10 @@ interface Boolean { interface BooleanConstructor { new (value?: any): Boolean; (value?: any): boolean; - prototype: Boolean; + readonly prototype: Boolean; } -declare var Boolean: BooleanConstructor; +declare const Boolean: BooleanConstructor; interface Number { /** @@ -488,57 +487,57 @@ interface Number { interface NumberConstructor { new (value?: any): Number; (value?: any): number; - prototype: Number; + readonly prototype: Number; /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ - MAX_VALUE: number; + readonly MAX_VALUE: number; /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ - MIN_VALUE: number; + readonly MIN_VALUE: number; /** * A value that is not a number. * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. */ - NaN: number; + readonly NaN: number; /** * A value that is less than the largest negative number that can be represented in JavaScript. * JavaScript displays NEGATIVE_INFINITY values as -infinity. */ - NEGATIVE_INFINITY: number; + readonly NEGATIVE_INFINITY: number; /** * A value greater than the largest number that can be represented in JavaScript. * JavaScript displays POSITIVE_INFINITY values as infinity. */ - POSITIVE_INFINITY: number; + readonly POSITIVE_INFINITY: number; } /** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ -declare var Number: NumberConstructor; +declare const Number: NumberConstructor; interface TemplateStringsArray extends Array { - raw: string[]; + readonly raw: string[]; } interface Math { /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ - E: number; + readonly E: number; /** The natural logarithm of 10. */ - LN10: number; + readonly LN10: number; /** The natural logarithm of 2. */ - LN2: number; + readonly LN2: number; /** The base-2 logarithm of e. */ - LOG2E: number; + readonly LOG2E: number; /** The base-10 logarithm of e. */ - LOG10E: number; + readonly LOG10E: number; /** Pi. This is the ratio of the circumference of a circle to its diameter. */ - PI: number; + readonly PI: number; /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ - SQRT1_2: number; + readonly SQRT1_2: number; /** The square root of 2. */ - SQRT2: number; + readonly SQRT2: number; /** * Returns the absolute value of a number (the value without regard to whether it is positive or negative). * For example, the absolute value of -5 is the same as the absolute value of 5. @@ -631,7 +630,7 @@ interface Math { tan(x: number): number; } /** An intrinsic object that provides basic mathematics functionality and constants. */ -declare var Math: Math; +declare const Math: Math; /** Enables basic storage and retrieval of dates and times. */ interface Date { @@ -793,7 +792,7 @@ interface DateConstructor { new (value: string): Date; new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; - prototype: Date; + readonly prototype: Date; /** * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. * @param s A date string @@ -813,7 +812,7 @@ interface DateConstructor { now(): number; } -declare var Date: DateConstructor; +declare const Date: DateConstructor; interface RegExpMatchArray extends Array { index?: number; @@ -839,16 +838,16 @@ interface RegExp { test(string: string): boolean; /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ - source: string; + readonly source: string; /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ - global: boolean; + readonly global: boolean; /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ - ignoreCase: boolean; + readonly ignoreCase: boolean; /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ - multiline: boolean; + readonly multiline: boolean; lastIndex: number; @@ -859,7 +858,7 @@ interface RegExp { interface RegExpConstructor { new (pattern: string, flags?: string): RegExp; (pattern: string, flags?: string): RegExp; - prototype: RegExp; + readonly prototype: RegExp; // Non-standard extensions $1: string; @@ -874,7 +873,7 @@ interface RegExpConstructor { lastMatch: string; } -declare var RegExp: RegExpConstructor; +declare const RegExp: RegExpConstructor; interface Error { name: string; @@ -884,10 +883,10 @@ interface Error { interface ErrorConstructor { new (message?: string): Error; (message?: string): Error; - prototype: Error; + readonly prototype: Error; } -declare var Error: ErrorConstructor; +declare const Error: ErrorConstructor; interface EvalError extends Error { } @@ -895,10 +894,10 @@ interface EvalError extends Error { interface EvalErrorConstructor { new (message?: string): EvalError; (message?: string): EvalError; - prototype: EvalError; + readonly prototype: EvalError; } -declare var EvalError: EvalErrorConstructor; +declare const EvalError: EvalErrorConstructor; interface RangeError extends Error { } @@ -906,10 +905,10 @@ interface RangeError extends Error { interface RangeErrorConstructor { new (message?: string): RangeError; (message?: string): RangeError; - prototype: RangeError; + readonly prototype: RangeError; } -declare var RangeError: RangeErrorConstructor; +declare const RangeError: RangeErrorConstructor; interface ReferenceError extends Error { } @@ -917,10 +916,10 @@ interface ReferenceError extends Error { interface ReferenceErrorConstructor { new (message?: string): ReferenceError; (message?: string): ReferenceError; - prototype: ReferenceError; + readonly prototype: ReferenceError; } -declare var ReferenceError: ReferenceErrorConstructor; +declare const ReferenceError: ReferenceErrorConstructor; interface SyntaxError extends Error { } @@ -928,10 +927,10 @@ interface SyntaxError extends Error { interface SyntaxErrorConstructor { new (message?: string): SyntaxError; (message?: string): SyntaxError; - prototype: SyntaxError; + readonly prototype: SyntaxError; } -declare var SyntaxError: SyntaxErrorConstructor; +declare const SyntaxError: SyntaxErrorConstructor; interface TypeError extends Error { } @@ -939,10 +938,10 @@ interface TypeError extends Error { interface TypeErrorConstructor { new (message?: string): TypeError; (message?: string): TypeError; - prototype: TypeError; + readonly prototype: TypeError; } -declare var TypeError: TypeErrorConstructor; +declare const TypeError: TypeErrorConstructor; interface URIError extends Error { } @@ -950,10 +949,10 @@ interface URIError extends Error { interface URIErrorConstructor { new (message?: string): URIError; (message?: string): URIError; - prototype: URIError; + readonly prototype: URIError; } -declare var URIError: URIErrorConstructor; +declare const URIError: URIErrorConstructor; interface JSON { /** @@ -998,13 +997,115 @@ interface JSON { /** * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. */ -declare var JSON: JSON; +declare const JSON: JSON; ///////////////////////////// /// ECMAScript Array API (specially handled by compiler) ///////////////////////////// +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat>(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + + readonly [n: number]: T; +} + interface Array { /** * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. @@ -1028,12 +1129,7 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: U[]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: T[]): T[]; + concat(...items: (T | T[])[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1053,19 +1149,16 @@ interface Array { * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): T[]; - /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: T, b: T) => number): T[]; - /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. */ splice(start: number): T[]; - /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. @@ -1073,62 +1166,53 @@ interface Array { * @param items Elements to insert into the array in place of the deleted elements. */ splice(start: number, deleteCount: number, ...items: T[]): T[]; - /** * Inserts new elements at the start of an array. * @param items Elements to insert at the start of the Array. */ unshift(...items: T[]): number; - /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; - /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. */ lastIndexOf(searchElement: T, fromIndex?: number): number; - /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; - /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; - /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1141,7 +1225,6 @@ interface Array { * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. @@ -1166,10 +1249,10 @@ interface ArrayConstructor { (arrayLength: number): T[]; (...items: T[]): T[]; isArray(arg: any): arg is Array; - prototype: Array; + readonly prototype: Array; } -declare var Array: ArrayConstructor; +declare const Array: ArrayConstructor; interface TypedPropertyDescriptor { enumerable?: boolean; @@ -1199,11 +1282,10 @@ interface PromiseLike { } interface ArrayLike { - length: number; - [n: number]: T; + readonly length: number; + readonly [n: number]: T; } - /** * Represents a raw buffer of binary data, which is used to store data for the * different typed arrays. ArrayBuffers cannot be read from or written to directly, @@ -1214,7 +1296,7 @@ interface ArrayBuffer { /** * Read-only. The length of the ArrayBuffer (in bytes). */ - byteLength: number; + readonly byteLength: number; /** * Returns a section of an ArrayBuffer. @@ -1223,11 +1305,11 @@ interface ArrayBuffer { } interface ArrayBufferConstructor { - prototype: ArrayBuffer; + readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } -declare var ArrayBuffer: ArrayBufferConstructor; +declare const ArrayBuffer: ArrayBufferConstructor; interface ArrayBufferView { /** @@ -1247,9 +1329,9 @@ interface ArrayBufferView { } interface DataView { - buffer: ArrayBuffer; - byteLength: number; - byteOffset: number; + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; /** * Gets the Float32 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. @@ -1377,7 +1459,7 @@ interface DataView { interface DataViewConstructor { new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; } -declare var DataView: DataViewConstructor; +declare const DataView: DataViewConstructor; /** * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested @@ -1387,22 +1469,22 @@ interface Int8Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -1501,7 +1583,7 @@ interface Int8Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -1625,7 +1707,7 @@ interface Int8Array { [index: number]: number; } interface Int8ArrayConstructor { - prototype: Int8Array; + readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; @@ -1633,7 +1715,7 @@ interface Int8ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -1650,7 +1732,7 @@ interface Int8ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } -declare var Int8Array: Int8ArrayConstructor; +declare const Int8Array: Int8ArrayConstructor; /** * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the @@ -1660,22 +1742,22 @@ interface Uint8Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -1774,7 +1856,7 @@ interface Uint8Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -1899,7 +1981,7 @@ interface Uint8Array { } interface Uint8ArrayConstructor { - prototype: Uint8Array; + readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; @@ -1907,7 +1989,7 @@ interface Uint8ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -1924,7 +2006,7 @@ interface Uint8ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } -declare var Uint8Array: Uint8ArrayConstructor; +declare const Uint8Array: Uint8ArrayConstructor; /** * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. @@ -1934,22 +2016,22 @@ interface Uint8ClampedArray { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2048,7 +2130,7 @@ interface Uint8ClampedArray { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2173,7 +2255,7 @@ interface Uint8ClampedArray { } interface Uint8ClampedArrayConstructor { - prototype: Uint8ClampedArray; + readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; @@ -2181,7 +2263,7 @@ interface Uint8ClampedArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -2197,7 +2279,7 @@ interface Uint8ClampedArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } -declare var Uint8ClampedArray: Uint8ClampedArrayConstructor; +declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; /** * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the @@ -2207,22 +2289,22 @@ interface Int16Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2321,7 +2403,7 @@ interface Int16Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2446,7 +2528,7 @@ interface Int16Array { } interface Int16ArrayConstructor { - prototype: Int16Array; + readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; @@ -2454,7 +2536,7 @@ interface Int16ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -2471,7 +2553,7 @@ interface Int16ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } -declare var Int16Array: Int16ArrayConstructor; +declare const Int16Array: Int16ArrayConstructor; /** * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the @@ -2481,22 +2563,22 @@ interface Uint16Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2595,7 +2677,7 @@ interface Uint16Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2720,7 +2802,7 @@ interface Uint16Array { } interface Uint16ArrayConstructor { - prototype: Uint16Array; + readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; @@ -2728,7 +2810,7 @@ interface Uint16ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -2745,7 +2827,7 @@ interface Uint16ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } -declare var Uint16Array: Uint16ArrayConstructor; +declare const Uint16Array: Uint16ArrayConstructor; /** * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. @@ -2754,22 +2836,22 @@ interface Int32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2868,7 +2950,7 @@ interface Int32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2993,7 +3075,7 @@ interface Int32Array { } interface Int32ArrayConstructor { - prototype: Int32Array; + readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; @@ -3001,7 +3083,7 @@ interface Int32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3017,7 +3099,7 @@ interface Int32ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } -declare var Int32Array: Int32ArrayConstructor; +declare const Int32Array: Int32ArrayConstructor; /** * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the @@ -3027,22 +3109,22 @@ interface Uint32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3141,7 +3223,7 @@ interface Uint32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3266,7 +3348,7 @@ interface Uint32Array { } interface Uint32ArrayConstructor { - prototype: Uint32Array; + readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; @@ -3274,7 +3356,7 @@ interface Uint32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3290,7 +3372,7 @@ interface Uint32ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } -declare var Uint32Array: Uint32ArrayConstructor; +declare const Uint32Array: Uint32ArrayConstructor; /** * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number @@ -3300,22 +3382,22 @@ interface Float32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3414,7 +3496,7 @@ interface Float32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3539,7 +3621,7 @@ interface Float32Array { } interface Float32ArrayConstructor { - prototype: Float32Array; + readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; @@ -3547,7 +3629,7 @@ interface Float32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3564,7 +3646,7 @@ interface Float32ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } -declare var Float32Array: Float32ArrayConstructor; +declare const Float32Array: Float32ArrayConstructor; /** * A typed array of 64-bit float values. The contents are initialized to 0. If the requested @@ -3574,22 +3656,22 @@ interface Float64Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3688,7 +3770,7 @@ interface Float64Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3813,7 +3895,7 @@ interface Float64Array { } interface Float64ArrayConstructor { - prototype: Float64Array; + readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; @@ -3821,7 +3903,7 @@ interface Float64ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3837,7 +3919,7 @@ interface Float64ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } -declare var Float64Array: Float64ArrayConstructor; +declare const Float64Array: Float64ArrayConstructor; ///////////////////////////// /// ECMAScript Internationalization API ///////////////////////////// @@ -4362,6 +4444,7 @@ interface AudioContext extends EventTarget { destination: AudioDestinationNode; listener: AudioListener; sampleRate: number; + state: string; createAnalyser(): AnalyserNode; createBiquadFilter(): BiquadFilterNode; createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; @@ -4418,6 +4501,8 @@ interface AudioNode extends EventTarget { numberOfOutputs: number; connect(destination: AudioNode, output?: number, input?: number): void; disconnect(output?: number): void; + disconnect(destination: AudioNode, output?: number, input?: number): void; + disconnect(destination: AudioParam, output?: number): void; } declare var AudioNode: { @@ -5295,7 +5380,7 @@ interface Console { select(element: Element): void; time(timerName?: string): void; timeEnd(timerName?: string): void; - trace(): void; + trace(message?: any, ...optionalParams: any[]): void; warn(message?: any, ...optionalParams: any[]): void; } @@ -5554,9 +5639,9 @@ interface DataTransferItemList { length: number; add(data: File): DataTransferItem; clear(): void; - item(index: number): File; + item(index: number): DataTransferItem; remove(index: number): void; - [index: number]: File; + [index: number]: DataTransferItem; } declare var DataTransferItemList: { @@ -6099,6 +6184,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string; + currentScript: HTMLScriptElement; adoptNode(source: Node): Node; captureEvents(): void; clear(): void; @@ -6608,6 +6694,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; + createElement(tagName: "picture"): HTMLPictureElement; + getElementsByTagName(tagname: "picture"): NodeListOf; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -6814,6 +6902,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec tagName: string; id: string; className: string; + innerHTML: string; getAttribute(name?: string): string; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; @@ -7009,7 +7098,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec removeAttributeNode(oldAttr: Attr): Attr; requestFullscreen(): void; requestPointerLock(): void; - setAttribute(name?: string, value?: string): void; + setAttribute(name: string, value: string): void; setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; @@ -7018,6 +7107,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; + getElementsByTagName(tagname: "picture"): NodeListOf; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -7807,6 +7898,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; + toBlob(): Blob; } declare var HTMLCanvasElement: { @@ -8002,7 +8094,6 @@ interface HTMLElement extends Element { title: string; blur(): void; click(): void; - contains(child: HTMLElement): boolean; dragDrop(): boolean; focus(): void; insertAdjacentElement(position: string, insertedElement: Element): Element; @@ -9552,7 +9643,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: any; + readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -10176,7 +10267,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLSelectElement; + options: HTMLCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -10209,6 +10300,7 @@ interface HTMLSelectElement extends HTMLElement { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; + selectedOptions: HTMLCollection; /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. @@ -10462,19 +10554,19 @@ interface HTMLTableElement extends HTMLElement { /** * Creates an empty caption element in the table. */ - createCaption(): HTMLElement; + createCaption(): HTMLTableCaptionElement; /** * Creates an empty tBody element in the table. */ - createTBody(): HTMLElement; + createTBody(): HTMLTableSectionElement; /** * Creates an empty tFoot element in the table. */ - createTFoot(): HTMLElement; + createTFoot(): HTMLTableSectionElement; /** * Returns the tHead element object if successful, or null otherwise. */ - createTHead(): HTMLElement; + createTHead(): HTMLTableSectionElement; /** * Deletes the caption element and its contents from the table. */ @@ -10496,7 +10588,7 @@ interface HTMLTableElement extends HTMLElement { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; } declare var HTMLTableElement: { @@ -10547,7 +10639,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Creates a new cell in the table row, and adds the cell to the cells collection. * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ - insertCell(index?: number): HTMLElement; + insertCell(index?: number): HTMLTableCellElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10574,7 +10666,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10927,7 +11019,7 @@ interface IDBCursor { direction: string; key: any; primaryKey: any; - source: any; + source: IDBObjectStore | IDBIndex; advance(count: number): void; continue(key?: any): void; delete(): IDBRequest; @@ -10961,11 +11053,11 @@ interface IDBDatabase extends EventTarget { objectStoreNames: DOMStringList; onabort: (ev: Event) => any; onerror: (ev: Event) => any; - version: string; + version: number; close(): void; - createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: any, mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: string): IDBTransaction; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -10988,10 +11080,11 @@ declare var IDBFactory: { } interface IDBIndex { - keyPath: string; + keyPath: string | string[]; name: string; objectStore: IDBObjectStore; unique: boolean; + multiEntry: boolean; count(key?: any): IDBRequest; get(key: any): IDBRequest; getKey(key: any): IDBRequest; @@ -11022,13 +11115,14 @@ declare var IDBKeyRange: { interface IDBObjectStore { indexNames: DOMStringList; - keyPath: string; + keyPath: string | string[]; name: string; transaction: IDBTransaction; + autoIncrement: boolean; add(value: any, key?: any): IDBRequest; clear(): IDBRequest; count(key?: any): IDBRequest; - createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; delete(key: any): IDBRequest; deleteIndex(indexName: string): void; get(key: any): IDBRequest; @@ -11063,7 +11157,7 @@ interface IDBRequest extends EventTarget { onsuccess: (ev: Event) => any; readyState: string; result: any; - source: any; + source: IDBObjectStore | IDBIndex | IDBCursor; transaction: IDBTransaction; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; @@ -11112,7 +11206,7 @@ declare var IDBVersionChangeEvent: { } interface ImageData { - data: number[]; + data: Uint8ClampedArray; height: number; width: number; } @@ -11676,7 +11770,7 @@ declare var MediaQueryList: { interface MediaSource extends EventTarget { activeSourceBuffers: SourceBufferList; duration: number; - readyState: number; + readyState: string; sourceBuffers: SourceBufferList; addSourceBuffer(type: string): SourceBuffer; endOfStream(error?: number): void; @@ -11910,6 +12004,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + vibrate(pattern: number | number[]): boolean; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11950,6 +12045,7 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; + contains(node: Node): boolean; ATTRIBUTE_NODE: number; CDATA_SECTION_NODE: number; COMMENT_NODE: number; @@ -14248,11 +14344,14 @@ declare var SVGViewElement: { } interface SVGZoomAndPan { + zoomAndPan: number; +} + +declare var SVGZoomAndPan: { SVG_ZOOMANDPAN_DISABLE: number; SVG_ZOOMANDPAN_MAGNIFY: number; SVG_ZOOMANDPAN_UNKNOWN: number; } -declare var SVGZoomAndPan: SVGZoomAndPan; interface SVGZoomEvent extends UIEvent { newScale: number; @@ -14403,17 +14502,16 @@ declare var Storage: { } interface StorageEvent extends Event { - key: string; - newValue: any; - oldValue: any; - storageArea: Storage; url: string; - initStorageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } declare var StorageEvent: { prototype: StorageEvent; - new(): StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; } interface StyleMedia { @@ -16011,7 +16109,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window msMatchMedia(mediaQuery: string): MediaQueryList; msRequestAnimationFrame(callback: FrameRequestCallback): number; msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): any; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; postMessage(message: any, targetOrigin: string, ports?: any): void; print(): void; prompt(message?: string, _default?: string): string; @@ -16613,6 +16711,24 @@ interface XMLHttpRequestEventTarget { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface StorageEventInit extends EventInit { + key?: string; + oldValue?: string; + newValue?: string; + url: string; + storageArea?: Storage; +} + +interface IDBObjectStoreParameters { + keyPath?: string | string[]; + autoIncrement?: boolean; +} + +interface IDBIndexParameters { + unique?: boolean; + multiEntry?: boolean; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -16648,6 +16764,23 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface HTMLTemplateElement extends HTMLElement { + content: DocumentFragment; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +} + +interface HTMLPictureElement extends HTMLElement { +} + +declare var HTMLPictureElement: { + prototype: HTMLPictureElement; + new(): HTMLPictureElement; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -16681,7 +16814,7 @@ interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } interface DecodeErrorCallback { - (): void; + (error: DOMException): void; } interface FunctionStringCallback { (data: string): void; @@ -16844,7 +16977,7 @@ declare function msCancelRequestAnimationFrame(handle: number): void; declare function msMatchMedia(mediaQuery: string): MediaQueryList; declare function msRequestAnimationFrame(callback: FrameRequestCallback): number; declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): any; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; declare function postMessage(message: any, targetOrigin: string, ports?: any): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string; diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 69014415c15..7bb2e8d4158 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -538,6 +538,7 @@ interface AudioContext extends EventTarget { destination: AudioDestinationNode; listener: AudioListener; sampleRate: number; + state: string; createAnalyser(): AnalyserNode; createBiquadFilter(): BiquadFilterNode; createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; @@ -594,6 +595,8 @@ interface AudioNode extends EventTarget { numberOfOutputs: number; connect(destination: AudioNode, output?: number, input?: number): void; disconnect(output?: number): void; + disconnect(destination: AudioNode, output?: number, input?: number): void; + disconnect(destination: AudioParam, output?: number): void; } declare var AudioNode: { @@ -1471,7 +1474,7 @@ interface Console { select(element: Element): void; time(timerName?: string): void; timeEnd(timerName?: string): void; - trace(): void; + trace(message?: any, ...optionalParams: any[]): void; warn(message?: any, ...optionalParams: any[]): void; } @@ -1730,9 +1733,9 @@ interface DataTransferItemList { length: number; add(data: File): DataTransferItem; clear(): void; - item(index: number): File; + item(index: number): DataTransferItem; remove(index: number): void; - [index: number]: File; + [index: number]: DataTransferItem; } declare var DataTransferItemList: { @@ -2275,6 +2278,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string; + currentScript: HTMLScriptElement; adoptNode(source: Node): Node; captureEvents(): void; clear(): void; @@ -2784,6 +2788,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; + createElement(tagName: "picture"): HTMLPictureElement; + getElementsByTagName(tagname: "picture"): NodeListOf; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -2990,6 +2996,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec tagName: string; id: string; className: string; + innerHTML: string; getAttribute(name?: string): string; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; @@ -3185,7 +3192,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec removeAttributeNode(oldAttr: Attr): Attr; requestFullscreen(): void; requestPointerLock(): void; - setAttribute(name?: string, value?: string): void; + setAttribute(name: string, value: string): void; setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; @@ -3194,6 +3201,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; + getElementsByTagName(tagname: "picture"): NodeListOf; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -3983,6 +3992,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; + toBlob(): Blob; } declare var HTMLCanvasElement: { @@ -4178,7 +4188,6 @@ interface HTMLElement extends Element { title: string; blur(): void; click(): void; - contains(child: HTMLElement): boolean; dragDrop(): boolean; focus(): void; insertAdjacentElement(position: string, insertedElement: Element): Element; @@ -5728,7 +5737,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: any; + readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -6352,7 +6361,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLSelectElement; + options: HTMLCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -6385,6 +6394,7 @@ interface HTMLSelectElement extends HTMLElement { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; + selectedOptions: HTMLCollection; /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. @@ -6638,19 +6648,19 @@ interface HTMLTableElement extends HTMLElement { /** * Creates an empty caption element in the table. */ - createCaption(): HTMLElement; + createCaption(): HTMLTableCaptionElement; /** * Creates an empty tBody element in the table. */ - createTBody(): HTMLElement; + createTBody(): HTMLTableSectionElement; /** * Creates an empty tFoot element in the table. */ - createTFoot(): HTMLElement; + createTFoot(): HTMLTableSectionElement; /** * Returns the tHead element object if successful, or null otherwise. */ - createTHead(): HTMLElement; + createTHead(): HTMLTableSectionElement; /** * Deletes the caption element and its contents from the table. */ @@ -6672,7 +6682,7 @@ interface HTMLTableElement extends HTMLElement { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; } declare var HTMLTableElement: { @@ -6723,7 +6733,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Creates a new cell in the table row, and adds the cell to the cells collection. * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ - insertCell(index?: number): HTMLElement; + insertCell(index?: number): HTMLTableCellElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -6750,7 +6760,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7103,7 +7113,7 @@ interface IDBCursor { direction: string; key: any; primaryKey: any; - source: any; + source: IDBObjectStore | IDBIndex; advance(count: number): void; continue(key?: any): void; delete(): IDBRequest; @@ -7137,11 +7147,11 @@ interface IDBDatabase extends EventTarget { objectStoreNames: DOMStringList; onabort: (ev: Event) => any; onerror: (ev: Event) => any; - version: string; + version: number; close(): void; - createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: any, mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: string): IDBTransaction; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -7164,10 +7174,11 @@ declare var IDBFactory: { } interface IDBIndex { - keyPath: string; + keyPath: string | string[]; name: string; objectStore: IDBObjectStore; unique: boolean; + multiEntry: boolean; count(key?: any): IDBRequest; get(key: any): IDBRequest; getKey(key: any): IDBRequest; @@ -7198,13 +7209,14 @@ declare var IDBKeyRange: { interface IDBObjectStore { indexNames: DOMStringList; - keyPath: string; + keyPath: string | string[]; name: string; transaction: IDBTransaction; + autoIncrement: boolean; add(value: any, key?: any): IDBRequest; clear(): IDBRequest; count(key?: any): IDBRequest; - createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; delete(key: any): IDBRequest; deleteIndex(indexName: string): void; get(key: any): IDBRequest; @@ -7239,7 +7251,7 @@ interface IDBRequest extends EventTarget { onsuccess: (ev: Event) => any; readyState: string; result: any; - source: any; + source: IDBObjectStore | IDBIndex | IDBCursor; transaction: IDBTransaction; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; @@ -7288,7 +7300,7 @@ declare var IDBVersionChangeEvent: { } interface ImageData { - data: number[]; + data: Uint8ClampedArray; height: number; width: number; } @@ -7852,7 +7864,7 @@ declare var MediaQueryList: { interface MediaSource extends EventTarget { activeSourceBuffers: SourceBufferList; duration: number; - readyState: number; + readyState: string; sourceBuffers: SourceBufferList; addSourceBuffer(type: string): SourceBuffer; endOfStream(error?: number): void; @@ -8086,6 +8098,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + vibrate(pattern: number | number[]): boolean; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -8126,6 +8139,7 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; + contains(node: Node): boolean; ATTRIBUTE_NODE: number; CDATA_SECTION_NODE: number; COMMENT_NODE: number; @@ -10424,11 +10438,14 @@ declare var SVGViewElement: { } interface SVGZoomAndPan { + zoomAndPan: number; +} + +declare var SVGZoomAndPan: { SVG_ZOOMANDPAN_DISABLE: number; SVG_ZOOMANDPAN_MAGNIFY: number; SVG_ZOOMANDPAN_UNKNOWN: number; } -declare var SVGZoomAndPan: SVGZoomAndPan; interface SVGZoomEvent extends UIEvent { newScale: number; @@ -10579,17 +10596,16 @@ declare var Storage: { } interface StorageEvent extends Event { - key: string; - newValue: any; - oldValue: any; - storageArea: Storage; url: string; - initStorageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } declare var StorageEvent: { prototype: StorageEvent; - new(): StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; } interface StyleMedia { @@ -12187,7 +12203,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window msMatchMedia(mediaQuery: string): MediaQueryList; msRequestAnimationFrame(callback: FrameRequestCallback): number; msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): any; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; postMessage(message: any, targetOrigin: string, ports?: any): void; print(): void; prompt(message?: string, _default?: string): string; @@ -12789,6 +12805,24 @@ interface XMLHttpRequestEventTarget { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface StorageEventInit extends EventInit { + key?: string; + oldValue?: string; + newValue?: string; + url: string; + storageArea?: Storage; +} + +interface IDBObjectStoreParameters { + keyPath?: string | string[]; + autoIncrement?: boolean; +} + +interface IDBIndexParameters { + unique?: boolean; + multiEntry?: boolean; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -12824,6 +12858,23 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface HTMLTemplateElement extends HTMLElement { + content: DocumentFragment; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +} + +interface HTMLPictureElement extends HTMLElement { +} + +declare var HTMLPictureElement: { + prototype: HTMLPictureElement; + new(): HTMLPictureElement; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -12857,7 +12908,7 @@ interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } interface DecodeErrorCallback { - (): void; + (error: DOMException): void; } interface FunctionStringCallback { (data: string): void; @@ -13020,7 +13071,7 @@ declare function msCancelRequestAnimationFrame(handle: number): void; declare function msMatchMedia(mediaQuery: string): MediaQueryList; declare function msRequestAnimationFrame(callback: FrameRequestCallback): number; declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): any; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; declare function postMessage(message: any, targetOrigin: string, ports?: any): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string; diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 564c302031d..7e973a82820 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -13,6 +13,7 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +/// declare type PropertyKey = string | number | symbol; interface Symbol { @@ -22,14 +23,14 @@ interface Symbol { /** Returns the primitive value of the specified object. */ valueOf(): Object; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "Symbol"; } interface SymbolConstructor { /** * A reference to the prototype. */ - prototype: Symbol; + readonly prototype: Symbol; /** * Returns a new unique Symbol value. @@ -57,67 +58,67 @@ interface SymbolConstructor { * A method that determines if a constructor object recognizes an object as one of the * constructor’s instances. Called by the semantics of the instanceof operator. */ - hasInstance: symbol; + readonly hasInstance: symbol; /** * A Boolean value that if true indicates that an object should flatten to its array elements * by Array.prototype.concat. */ - isConcatSpreadable: symbol; + readonly isConcatSpreadable: symbol; /** * A method that returns the default iterator for an object. Called by the semantics of the * for-of statement. */ - iterator: symbol; + readonly iterator: symbol; /** * A regular expression method that matches the regular expression against a string. Called * by the String.prototype.match method. */ - match: symbol; + readonly match: symbol; /** * A regular expression method that replaces matched substrings of a string. Called by the * String.prototype.replace method. */ - replace: symbol; + readonly replace: symbol; /** * A regular expression method that returns the index within a string that matches the * regular expression. Called by the String.prototype.search method. */ - search: symbol; + readonly search: symbol; /** * A function valued property that is the constructor function that is used to create * derived objects. */ - species: symbol; + readonly species: symbol; /** * A regular expression method that splits a string at the indices that match the regular * expression. Called by the String.prototype.split method. */ - split: symbol; + readonly split: symbol; /** * A method that converts an object to a corresponding primitive value. * Called by the ToPrimitive abstract operation. */ - toPrimitive: symbol; + readonly toPrimitive: symbol; /** * A String value that is used in the creation of the default string description of an object. * Called by the built-in method Object.prototype.toString. */ - toStringTag: symbol; + readonly toStringTag: symbol; /** * An Object whose own property names are property names that are excluded from the 'with' * environment bindings of the associated objects. */ - unscopables: symbol; + readonly unscopables: symbol; } declare var Symbol: SymbolConstructor; @@ -215,7 +216,7 @@ interface Function { /** * Returns the name of the function. Function names are read-only and can not be changed. */ - name: string; + readonly name: string; /** * Determines whether the given value inherits from this function if this function was used @@ -233,7 +234,7 @@ interface NumberConstructor { * that is representable as a Number value, which is approximately: * 2.2204460492503130808472633361816 x 10‍â’‍16. */ - EPSILON: number; + readonly EPSILON: number; /** * Returns true if passed value is finite. @@ -268,14 +269,14 @@ interface NumberConstructor { * a Number value. * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 â’ 1. */ - MAX_SAFE_INTEGER: number; + readonly MAX_SAFE_INTEGER: number; /** * The value of the smallest integer n such that n and n â’ 1 are both exactly representable as * a Number value. * The value of Number.MIN_SAFE_INTEGER is â’9007199254740991 (â’(2^53 â’ 1)). */ - MIN_SAFE_INTEGER: number; + readonly MIN_SAFE_INTEGER: number; /** * Converts a string to a floating-point number. @@ -580,7 +581,7 @@ interface IterableIterator extends Iterator { } interface GeneratorFunction extends Function { - + readonly [Symbol.toStringTag]: "GeneratorFunction"; } interface GeneratorFunctionConstructor { @@ -590,7 +591,7 @@ interface GeneratorFunctionConstructor { */ new (...args: string[]): GeneratorFunction; (...args: string[]): GeneratorFunction; - prototype: GeneratorFunction; + readonly prototype: GeneratorFunction; } declare var GeneratorFunction: GeneratorFunctionConstructor; @@ -705,7 +706,7 @@ interface Math { */ cbrt(x: number): number; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "Math"; } interface Date { @@ -791,19 +792,19 @@ interface RegExp { * * If no flags are set, the value is the empty string. */ - flags: string; + readonly flags: string; /** * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular * expression. Default is false. Read-only. */ - sticky: boolean; + readonly sticky: boolean; /** * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular * expression. Default is false. Read-only. */ - unicode: boolean; + readonly unicode: boolean; } interface RegExpConstructor { @@ -819,17 +820,17 @@ interface Map { has(key: K): boolean; keys(): IterableIterator; set(key: K, value?: V): Map; - size: number; + readonly size: number; values(): IterableIterator; [Symbol.iterator]():IterableIterator<[K,V]>; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "Map"; } interface MapConstructor { new (): Map; new (): Map; new (iterable: Iterable<[K, V]>): Map; - prototype: Map; + readonly prototype: Map; } declare var Map: MapConstructor; @@ -839,14 +840,14 @@ interface WeakMap { get(key: K): V; has(key: K): boolean; set(key: K, value?: V): WeakMap; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "WeakMap"; } interface WeakMapConstructor { new (): WeakMap; new (): WeakMap; new (iterable: Iterable<[K, V]>): WeakMap; - prototype: WeakMap; + readonly prototype: WeakMap; } declare var WeakMap: WeakMapConstructor; @@ -858,17 +859,17 @@ interface Set { forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; has(value: T): boolean; keys(): IterableIterator; - size: number; + readonly size: number; values(): IterableIterator; [Symbol.iterator]():IterableIterator; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "Set"; } interface SetConstructor { new (): Set; new (): Set; new (iterable: Iterable): Set; - prototype: Set; + readonly prototype: Set; } declare var Set: SetConstructor; @@ -877,19 +878,19 @@ interface WeakSet { clear(): void; delete(value: T): boolean; has(value: T): boolean; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "WeakSet"; } interface WeakSetConstructor { new (): WeakSet; new (): WeakSet; new (iterable: Iterable): WeakSet; - prototype: WeakSet; + readonly prototype: WeakSet; } declare var WeakSet: WeakSetConstructor; interface JSON { - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "JSON"; } /** @@ -899,11 +900,11 @@ interface JSON { * buffer as needed. */ interface ArrayBuffer { - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "ArrayBuffer"; } interface DataView { - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "DataView"; } /** @@ -924,6 +925,7 @@ interface Int8Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int8Array"; } interface Int8ArrayConstructor { @@ -956,6 +958,7 @@ interface Uint8Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "UInt8Array"; } interface Uint8ArrayConstructor { @@ -991,6 +994,7 @@ interface Uint8ClampedArray { values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; } interface Uint8ClampedArrayConstructor { @@ -1028,6 +1032,7 @@ interface Int16Array { [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int16Array"; } interface Int16ArrayConstructor { @@ -1060,6 +1065,7 @@ interface Uint16Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint16Array"; } interface Uint16ArrayConstructor { @@ -1092,6 +1098,7 @@ interface Int32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int32Array"; } interface Int32ArrayConstructor { @@ -1124,6 +1131,7 @@ interface Uint32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint32Array"; } interface Uint32ArrayConstructor { @@ -1156,6 +1164,7 @@ interface Float32Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Float32Array"; } interface Float32ArrayConstructor { @@ -1188,6 +1197,7 @@ interface Float64Array { */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Float64Array"; } interface Float64ArrayConstructor { @@ -1239,7 +1249,7 @@ declare namespace Reflect { function isExtensible(target: any): boolean; function ownKeys(target: any): Array; function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: any, proto: any): boolean; } @@ -1264,14 +1274,14 @@ interface Promise { catch(onrejected?: (reason: any) => T | PromiseLike): Promise; catch(onrejected?: (reason: any) => void): Promise; - [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "Promise"; } interface PromiseConstructor { /** * A reference to the prototype. */ - prototype: Promise; + readonly prototype: Promise; /** * Creates a new Promise. @@ -1287,7 +1297,16 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - all(values: Iterable>): Promise; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + all(values: Iterable>): Promise; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved @@ -1324,18 +1343,16 @@ interface PromiseConstructor { */ resolve(): Promise; - [Symbol.species]: Function; + readonly [Symbol.species]: Function; } declare var Promise: PromiseConstructor; -/// - ///////////////////////////// /// ECMAScript APIs ///////////////////////////// -declare var NaN: number; -declare var Infinity: number; +declare const NaN: number; +declare const Infinity: number; /** * Evaluates JavaScript code and executes it. @@ -1445,7 +1462,7 @@ interface ObjectConstructor { (value: any): any; /** A reference to the prototype for a class of objects. */ - prototype: Object; + readonly prototype: Object; /** * Returns the prototype of an object. @@ -1536,7 +1553,7 @@ interface ObjectConstructor { /** * Provides functionality common to all JavaScript objects. */ -declare var Object: ObjectConstructor; +declare const Object: ObjectConstructor; /** * Creates a new function. @@ -1565,7 +1582,7 @@ interface Function { bind(thisArg: any, ...argArray: any[]): any; prototype: any; - length: number; + readonly length: number; // Non-standard extensions arguments: any; @@ -1579,10 +1596,10 @@ interface FunctionConstructor { */ new (...args: string[]): Function; (...args: string[]): Function; - prototype: Function; + readonly prototype: Function; } -declare var Function: FunctionConstructor; +declare const Function: FunctionConstructor; interface IArguments { [index: number]: any; @@ -1730,7 +1747,7 @@ interface String { trim(): string; /** Returns the length of a String object. */ - length: number; + readonly length: number; // IE extensions /** @@ -1743,20 +1760,20 @@ interface String { /** Returns the primitive value of the specified object. */ valueOf(): string; - [index: number]: string; + readonly [index: number]: string; } interface StringConstructor { new (value?: any): String; (value?: any): string; - prototype: String; + readonly prototype: String; fromCharCode(...codes: number[]): string; } /** * Allows manipulation and formatting of text strings and determination and location of substrings within strings. */ -declare var String: StringConstructor; +declare const String: StringConstructor; interface Boolean { /** Returns the primitive value of the specified object. */ @@ -1766,10 +1783,10 @@ interface Boolean { interface BooleanConstructor { new (value?: any): Boolean; (value?: any): boolean; - prototype: Boolean; + readonly prototype: Boolean; } -declare var Boolean: BooleanConstructor; +declare const Boolean: BooleanConstructor; interface Number { /** @@ -1803,57 +1820,57 @@ interface Number { interface NumberConstructor { new (value?: any): Number; (value?: any): number; - prototype: Number; + readonly prototype: Number; /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ - MAX_VALUE: number; + readonly MAX_VALUE: number; /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ - MIN_VALUE: number; + readonly MIN_VALUE: number; /** * A value that is not a number. * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. */ - NaN: number; + readonly NaN: number; /** * A value that is less than the largest negative number that can be represented in JavaScript. * JavaScript displays NEGATIVE_INFINITY values as -infinity. */ - NEGATIVE_INFINITY: number; + readonly NEGATIVE_INFINITY: number; /** * A value greater than the largest number that can be represented in JavaScript. * JavaScript displays POSITIVE_INFINITY values as infinity. */ - POSITIVE_INFINITY: number; + readonly POSITIVE_INFINITY: number; } /** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ -declare var Number: NumberConstructor; +declare const Number: NumberConstructor; interface TemplateStringsArray extends Array { - raw: string[]; + readonly raw: string[]; } interface Math { /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ - E: number; + readonly E: number; /** The natural logarithm of 10. */ - LN10: number; + readonly LN10: number; /** The natural logarithm of 2. */ - LN2: number; + readonly LN2: number; /** The base-2 logarithm of e. */ - LOG2E: number; + readonly LOG2E: number; /** The base-10 logarithm of e. */ - LOG10E: number; + readonly LOG10E: number; /** Pi. This is the ratio of the circumference of a circle to its diameter. */ - PI: number; + readonly PI: number; /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ - SQRT1_2: number; + readonly SQRT1_2: number; /** The square root of 2. */ - SQRT2: number; + readonly SQRT2: number; /** * Returns the absolute value of a number (the value without regard to whether it is positive or negative). * For example, the absolute value of -5 is the same as the absolute value of 5. @@ -1946,7 +1963,7 @@ interface Math { tan(x: number): number; } /** An intrinsic object that provides basic mathematics functionality and constants. */ -declare var Math: Math; +declare const Math: Math; /** Enables basic storage and retrieval of dates and times. */ interface Date { @@ -2108,7 +2125,7 @@ interface DateConstructor { new (value: string): Date; new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; - prototype: Date; + readonly prototype: Date; /** * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. * @param s A date string @@ -2128,7 +2145,7 @@ interface DateConstructor { now(): number; } -declare var Date: DateConstructor; +declare const Date: DateConstructor; interface RegExpMatchArray extends Array { index?: number; @@ -2154,16 +2171,16 @@ interface RegExp { test(string: string): boolean; /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ - source: string; + readonly source: string; /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ - global: boolean; + readonly global: boolean; /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ - ignoreCase: boolean; + readonly ignoreCase: boolean; /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ - multiline: boolean; + readonly multiline: boolean; lastIndex: number; @@ -2174,7 +2191,7 @@ interface RegExp { interface RegExpConstructor { new (pattern: string, flags?: string): RegExp; (pattern: string, flags?: string): RegExp; - prototype: RegExp; + readonly prototype: RegExp; // Non-standard extensions $1: string; @@ -2189,7 +2206,7 @@ interface RegExpConstructor { lastMatch: string; } -declare var RegExp: RegExpConstructor; +declare const RegExp: RegExpConstructor; interface Error { name: string; @@ -2199,10 +2216,10 @@ interface Error { interface ErrorConstructor { new (message?: string): Error; (message?: string): Error; - prototype: Error; + readonly prototype: Error; } -declare var Error: ErrorConstructor; +declare const Error: ErrorConstructor; interface EvalError extends Error { } @@ -2210,10 +2227,10 @@ interface EvalError extends Error { interface EvalErrorConstructor { new (message?: string): EvalError; (message?: string): EvalError; - prototype: EvalError; + readonly prototype: EvalError; } -declare var EvalError: EvalErrorConstructor; +declare const EvalError: EvalErrorConstructor; interface RangeError extends Error { } @@ -2221,10 +2238,10 @@ interface RangeError extends Error { interface RangeErrorConstructor { new (message?: string): RangeError; (message?: string): RangeError; - prototype: RangeError; + readonly prototype: RangeError; } -declare var RangeError: RangeErrorConstructor; +declare const RangeError: RangeErrorConstructor; interface ReferenceError extends Error { } @@ -2232,10 +2249,10 @@ interface ReferenceError extends Error { interface ReferenceErrorConstructor { new (message?: string): ReferenceError; (message?: string): ReferenceError; - prototype: ReferenceError; + readonly prototype: ReferenceError; } -declare var ReferenceError: ReferenceErrorConstructor; +declare const ReferenceError: ReferenceErrorConstructor; interface SyntaxError extends Error { } @@ -2243,10 +2260,10 @@ interface SyntaxError extends Error { interface SyntaxErrorConstructor { new (message?: string): SyntaxError; (message?: string): SyntaxError; - prototype: SyntaxError; + readonly prototype: SyntaxError; } -declare var SyntaxError: SyntaxErrorConstructor; +declare const SyntaxError: SyntaxErrorConstructor; interface TypeError extends Error { } @@ -2254,10 +2271,10 @@ interface TypeError extends Error { interface TypeErrorConstructor { new (message?: string): TypeError; (message?: string): TypeError; - prototype: TypeError; + readonly prototype: TypeError; } -declare var TypeError: TypeErrorConstructor; +declare const TypeError: TypeErrorConstructor; interface URIError extends Error { } @@ -2265,10 +2282,10 @@ interface URIError extends Error { interface URIErrorConstructor { new (message?: string): URIError; (message?: string): URIError; - prototype: URIError; + readonly prototype: URIError; } -declare var URIError: URIErrorConstructor; +declare const URIError: URIErrorConstructor; interface JSON { /** @@ -2313,13 +2330,115 @@ interface JSON { /** * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. */ -declare var JSON: JSON; +declare const JSON: JSON; ///////////////////////////// /// ECMAScript Array API (specially handled by compiler) ///////////////////////////// +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat>(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + + readonly [n: number]: T; +} + interface Array { /** * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. @@ -2343,12 +2462,7 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: U[]): T[]; - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: T[]): T[]; + concat(...items: (T | T[])[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -2368,19 +2482,16 @@ interface Array { * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): T[]; - /** * Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. */ sort(compareFn?: (a: T, b: T) => number): T[]; - /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. */ splice(start: number): T[]; - /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. @@ -2388,62 +2499,53 @@ interface Array { * @param items Elements to insert into the array in place of the deleted elements. */ splice(start: number, deleteCount: number, ...items: T[]): T[]; - /** * Inserts new elements at the start of an array. * @param items Elements to insert at the start of the Array. */ unshift(...items: T[]): number; - /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; - /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. */ lastIndexOf(searchElement: T, fromIndex?: number): number; - /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; - /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; - /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -2456,7 +2558,6 @@ interface Array { * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. @@ -2481,10 +2582,10 @@ interface ArrayConstructor { (arrayLength: number): T[]; (...items: T[]): T[]; isArray(arg: any): arg is Array; - prototype: Array; + readonly prototype: Array; } -declare var Array: ArrayConstructor; +declare const Array: ArrayConstructor; interface TypedPropertyDescriptor { enumerable?: boolean; @@ -2514,11 +2615,10 @@ interface PromiseLike { } interface ArrayLike { - length: number; - [n: number]: T; + readonly length: number; + readonly [n: number]: T; } - /** * Represents a raw buffer of binary data, which is used to store data for the * different typed arrays. ArrayBuffers cannot be read from or written to directly, @@ -2529,7 +2629,7 @@ interface ArrayBuffer { /** * Read-only. The length of the ArrayBuffer (in bytes). */ - byteLength: number; + readonly byteLength: number; /** * Returns a section of an ArrayBuffer. @@ -2538,11 +2638,11 @@ interface ArrayBuffer { } interface ArrayBufferConstructor { - prototype: ArrayBuffer; + readonly prototype: ArrayBuffer; new (byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } -declare var ArrayBuffer: ArrayBufferConstructor; +declare const ArrayBuffer: ArrayBufferConstructor; interface ArrayBufferView { /** @@ -2562,9 +2662,9 @@ interface ArrayBufferView { } interface DataView { - buffer: ArrayBuffer; - byteLength: number; - byteOffset: number; + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; /** * Gets the Float32 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. @@ -2692,7 +2792,7 @@ interface DataView { interface DataViewConstructor { new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; } -declare var DataView: DataViewConstructor; +declare const DataView: DataViewConstructor; /** * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested @@ -2702,22 +2802,22 @@ interface Int8Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -2816,7 +2916,7 @@ interface Int8Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -2940,7 +3040,7 @@ interface Int8Array { [index: number]: number; } interface Int8ArrayConstructor { - prototype: Int8Array; + readonly prototype: Int8Array; new (length: number): Int8Array; new (array: ArrayLike): Int8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; @@ -2948,7 +3048,7 @@ interface Int8ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -2965,7 +3065,7 @@ interface Int8ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } -declare var Int8Array: Int8ArrayConstructor; +declare const Int8Array: Int8ArrayConstructor; /** * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the @@ -2975,22 +3075,22 @@ interface Uint8Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3089,7 +3189,7 @@ interface Uint8Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3214,7 +3314,7 @@ interface Uint8Array { } interface Uint8ArrayConstructor { - prototype: Uint8Array; + readonly prototype: Uint8Array; new (length: number): Uint8Array; new (array: ArrayLike): Uint8Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; @@ -3222,7 +3322,7 @@ interface Uint8ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3239,7 +3339,7 @@ interface Uint8ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } -declare var Uint8Array: Uint8ArrayConstructor; +declare const Uint8Array: Uint8ArrayConstructor; /** * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. @@ -3249,22 +3349,22 @@ interface Uint8ClampedArray { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3363,7 +3463,7 @@ interface Uint8ClampedArray { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3488,7 +3588,7 @@ interface Uint8ClampedArray { } interface Uint8ClampedArrayConstructor { - prototype: Uint8ClampedArray; + readonly prototype: Uint8ClampedArray; new (length: number): Uint8ClampedArray; new (array: ArrayLike): Uint8ClampedArray; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; @@ -3496,7 +3596,7 @@ interface Uint8ClampedArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3512,7 +3612,7 @@ interface Uint8ClampedArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } -declare var Uint8ClampedArray: Uint8ClampedArrayConstructor; +declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; /** * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the @@ -3522,22 +3622,22 @@ interface Int16Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3636,7 +3736,7 @@ interface Int16Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -3761,7 +3861,7 @@ interface Int16Array { } interface Int16ArrayConstructor { - prototype: Int16Array; + readonly prototype: Int16Array; new (length: number): Int16Array; new (array: ArrayLike): Int16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; @@ -3769,7 +3869,7 @@ interface Int16ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -3786,7 +3886,7 @@ interface Int16ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } -declare var Int16Array: Int16ArrayConstructor; +declare const Int16Array: Int16ArrayConstructor; /** * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the @@ -3796,22 +3896,22 @@ interface Uint16Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -3910,7 +4010,7 @@ interface Uint16Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -4035,7 +4135,7 @@ interface Uint16Array { } interface Uint16ArrayConstructor { - prototype: Uint16Array; + readonly prototype: Uint16Array; new (length: number): Uint16Array; new (array: ArrayLike): Uint16Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; @@ -4043,7 +4143,7 @@ interface Uint16ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -4060,7 +4160,7 @@ interface Uint16ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } -declare var Uint16Array: Uint16ArrayConstructor; +declare const Uint16Array: Uint16ArrayConstructor; /** * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. @@ -4069,22 +4169,22 @@ interface Int32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -4183,7 +4283,7 @@ interface Int32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -4308,7 +4408,7 @@ interface Int32Array { } interface Int32ArrayConstructor { - prototype: Int32Array; + readonly prototype: Int32Array; new (length: number): Int32Array; new (array: ArrayLike): Int32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; @@ -4316,7 +4416,7 @@ interface Int32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -4332,7 +4432,7 @@ interface Int32ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } -declare var Int32Array: Int32ArrayConstructor; +declare const Int32Array: Int32ArrayConstructor; /** * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the @@ -4342,22 +4442,22 @@ interface Uint32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -4456,7 +4556,7 @@ interface Uint32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -4581,7 +4681,7 @@ interface Uint32Array { } interface Uint32ArrayConstructor { - prototype: Uint32Array; + readonly prototype: Uint32Array; new (length: number): Uint32Array; new (array: ArrayLike): Uint32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; @@ -4589,7 +4689,7 @@ interface Uint32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -4605,7 +4705,7 @@ interface Uint32ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } -declare var Uint32Array: Uint32ArrayConstructor; +declare const Uint32Array: Uint32ArrayConstructor; /** * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number @@ -4615,22 +4715,22 @@ interface Float32Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -4729,7 +4829,7 @@ interface Float32Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -4854,7 +4954,7 @@ interface Float32Array { } interface Float32ArrayConstructor { - prototype: Float32Array; + readonly prototype: Float32Array; new (length: number): Float32Array; new (array: ArrayLike): Float32Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; @@ -4862,7 +4962,7 @@ interface Float32ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -4879,7 +4979,7 @@ interface Float32ArrayConstructor { from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } -declare var Float32Array: Float32ArrayConstructor; +declare const Float32Array: Float32ArrayConstructor; /** * A typed array of 64-bit float values. The contents are initialized to 0. If the requested @@ -4889,22 +4989,22 @@ interface Float64Array { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBuffer; + readonly buffer: ArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end @@ -5003,7 +5103,7 @@ interface Float64Array { /** * The length of the array. */ - length: number; + readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that @@ -5128,7 +5228,7 @@ interface Float64Array { } interface Float64ArrayConstructor { - prototype: Float64Array; + readonly prototype: Float64Array; new (length: number): Float64Array; new (array: ArrayLike): Float64Array; new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; @@ -5136,7 +5236,7 @@ interface Float64ArrayConstructor { /** * The size in bytes of each element in the array. */ - BYTES_PER_ELEMENT: number; + readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. @@ -5152,7 +5252,7 @@ interface Float64ArrayConstructor { */ from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } -declare var Float64Array: Float64ArrayConstructor; +declare const Float64Array: Float64ArrayConstructor; ///////////////////////////// /// ECMAScript Internationalization API ///////////////////////////// @@ -5677,6 +5777,7 @@ interface AudioContext extends EventTarget { destination: AudioDestinationNode; listener: AudioListener; sampleRate: number; + state: string; createAnalyser(): AnalyserNode; createBiquadFilter(): BiquadFilterNode; createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; @@ -5733,6 +5834,8 @@ interface AudioNode extends EventTarget { numberOfOutputs: number; connect(destination: AudioNode, output?: number, input?: number): void; disconnect(output?: number): void; + disconnect(destination: AudioNode, output?: number, input?: number): void; + disconnect(destination: AudioParam, output?: number): void; } declare var AudioNode: { @@ -6610,7 +6713,7 @@ interface Console { select(element: Element): void; time(timerName?: string): void; timeEnd(timerName?: string): void; - trace(): void; + trace(message?: any, ...optionalParams: any[]): void; warn(message?: any, ...optionalParams: any[]): void; } @@ -6869,9 +6972,9 @@ interface DataTransferItemList { length: number; add(data: File): DataTransferItem; clear(): void; - item(index: number): File; + item(index: number): DataTransferItem; remove(index: number): void; - [index: number]: File; + [index: number]: DataTransferItem; } declare var DataTransferItemList: { @@ -7414,6 +7517,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Gets or sets the version attribute specified in the declaration of an XML document. */ xmlVersion: string; + currentScript: HTMLScriptElement; adoptNode(source: Node): Node; captureEvents(): void; clear(): void; @@ -7923,6 +8027,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; + createElement(tagName: "picture"): HTMLPictureElement; + getElementsByTagName(tagname: "picture"): NodeListOf; addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -8129,6 +8235,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec tagName: string; id: string; className: string; + innerHTML: string; getAttribute(name?: string): string; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; @@ -8324,7 +8431,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec removeAttributeNode(oldAttr: Attr): Attr; requestFullscreen(): void; requestPointerLock(): void; - setAttribute(name?: string, value?: string): void; + setAttribute(name: string, value: string): void; setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; setAttributeNode(newAttr: Attr): Attr; setAttributeNodeNS(newAttr: Attr): Attr; @@ -8333,6 +8440,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullScreen(): void; webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; + getElementsByTagName(tagname: "picture"): NodeListOf; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -9122,6 +9231,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; + toBlob(): Blob; } declare var HTMLCanvasElement: { @@ -9317,7 +9427,6 @@ interface HTMLElement extends Element { title: string; blur(): void; click(): void; - contains(child: HTMLElement): boolean; dragDrop(): boolean; focus(): void; insertAdjacentElement(position: string, insertedElement: Element): Element; @@ -10867,7 +10976,7 @@ interface HTMLMediaElement extends HTMLElement { * Gets or sets the current playback position, in seconds. */ preload: string; - readyState: any; + readyState: number; /** * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. */ @@ -11491,7 +11600,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLSelectElement; + options: HTMLCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -11524,6 +11633,7 @@ interface HTMLSelectElement extends HTMLElement { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ willValidate: boolean; + selectedOptions: HTMLCollection; /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. @@ -11777,19 +11887,19 @@ interface HTMLTableElement extends HTMLElement { /** * Creates an empty caption element in the table. */ - createCaption(): HTMLElement; + createCaption(): HTMLTableCaptionElement; /** * Creates an empty tBody element in the table. */ - createTBody(): HTMLElement; + createTBody(): HTMLTableSectionElement; /** * Creates an empty tFoot element in the table. */ - createTFoot(): HTMLElement; + createTFoot(): HTMLTableSectionElement; /** * Returns the tHead element object if successful, or null otherwise. */ - createTHead(): HTMLElement; + createTHead(): HTMLTableSectionElement; /** * Deletes the caption element and its contents from the table. */ @@ -11811,7 +11921,7 @@ interface HTMLTableElement extends HTMLElement { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; } declare var HTMLTableElement: { @@ -11862,7 +11972,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { * Creates a new cell in the table row, and adds the cell to the cells collection. * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. */ - insertCell(index?: number): HTMLElement; + insertCell(index?: number): HTMLTableCellElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11889,7 +11999,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { * Creates a new row (tr) in the table, and adds the row to the rows collection. * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. */ - insertRow(index?: number): HTMLElement; + insertRow(index?: number): HTMLTableRowElement; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -12242,7 +12352,7 @@ interface IDBCursor { direction: string; key: any; primaryKey: any; - source: any; + source: IDBObjectStore | IDBIndex; advance(count: number): void; continue(key?: any): void; delete(): IDBRequest; @@ -12276,11 +12386,11 @@ interface IDBDatabase extends EventTarget { objectStoreNames: DOMStringList; onabort: (ev: Event) => any; onerror: (ev: Event) => any; - version: string; + version: number; close(): void; - createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: any, mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: string): IDBTransaction; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -12303,10 +12413,11 @@ declare var IDBFactory: { } interface IDBIndex { - keyPath: string; + keyPath: string | string[]; name: string; objectStore: IDBObjectStore; unique: boolean; + multiEntry: boolean; count(key?: any): IDBRequest; get(key: any): IDBRequest; getKey(key: any): IDBRequest; @@ -12337,13 +12448,14 @@ declare var IDBKeyRange: { interface IDBObjectStore { indexNames: DOMStringList; - keyPath: string; + keyPath: string | string[]; name: string; transaction: IDBTransaction; + autoIncrement: boolean; add(value: any, key?: any): IDBRequest; clear(): IDBRequest; count(key?: any): IDBRequest; - createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; delete(key: any): IDBRequest; deleteIndex(indexName: string): void; get(key: any): IDBRequest; @@ -12378,7 +12490,7 @@ interface IDBRequest extends EventTarget { onsuccess: (ev: Event) => any; readyState: string; result: any; - source: any; + source: IDBObjectStore | IDBIndex | IDBCursor; transaction: IDBTransaction; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; @@ -12427,7 +12539,7 @@ declare var IDBVersionChangeEvent: { } interface ImageData { - data: number[]; + data: Uint8ClampedArray; height: number; width: number; } @@ -12991,7 +13103,7 @@ declare var MediaQueryList: { interface MediaSource extends EventTarget { activeSourceBuffers: SourceBufferList; duration: number; - readyState: number; + readyState: string; sourceBuffers: SourceBufferList; addSourceBuffer(type: string): SourceBuffer; endOfStream(error?: number): void; @@ -13225,6 +13337,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + vibrate(pattern: number | number[]): boolean; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13265,6 +13378,7 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; + contains(node: Node): boolean; ATTRIBUTE_NODE: number; CDATA_SECTION_NODE: number; COMMENT_NODE: number; @@ -15563,11 +15677,14 @@ declare var SVGViewElement: { } interface SVGZoomAndPan { + zoomAndPan: number; +} + +declare var SVGZoomAndPan: { SVG_ZOOMANDPAN_DISABLE: number; SVG_ZOOMANDPAN_MAGNIFY: number; SVG_ZOOMANDPAN_UNKNOWN: number; } -declare var SVGZoomAndPan: SVGZoomAndPan; interface SVGZoomEvent extends UIEvent { newScale: number; @@ -15718,17 +15835,16 @@ declare var Storage: { } interface StorageEvent extends Event { - key: string; - newValue: any; - oldValue: any; - storageArea: Storage; url: string; - initStorageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; } declare var StorageEvent: { prototype: StorageEvent; - new(): StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; } interface StyleMedia { @@ -17326,7 +17442,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window msMatchMedia(mediaQuery: string): MediaQueryList; msRequestAnimationFrame(callback: FrameRequestCallback): number; msWriteProfilerMark(profilerMarkName: string): void; - open(url?: string, target?: string, features?: string, replace?: boolean): any; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; postMessage(message: any, targetOrigin: string, ports?: any): void; print(): void; prompt(message?: string, _default?: string): string; @@ -17928,6 +18044,24 @@ interface XMLHttpRequestEventTarget { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface StorageEventInit extends EventInit { + key?: string; + oldValue?: string; + newValue?: string; + url: string; + storageArea?: Storage; +} + +interface IDBObjectStoreParameters { + keyPath?: string | string[]; + autoIncrement?: boolean; +} + +interface IDBIndexParameters { + unique?: boolean; + multiEntry?: boolean; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -17963,6 +18097,23 @@ interface ProgressEventInit extends EventInit { total?: number; } +interface HTMLTemplateElement extends HTMLElement { + content: DocumentFragment; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +} + +interface HTMLPictureElement extends HTMLElement { +} + +declare var HTMLPictureElement: { + prototype: HTMLPictureElement; + new(): HTMLPictureElement; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -17996,7 +18147,7 @@ interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } interface DecodeErrorCallback { - (): void; + (error: DOMException): void; } interface FunctionStringCallback { (data: string): void; @@ -18159,7 +18310,7 @@ declare function msCancelRequestAnimationFrame(handle: number): void; declare function msMatchMedia(mediaQuery: string): MediaQueryList; declare function msRequestAnimationFrame(callback: FrameRequestCallback): number; declare function msWriteProfilerMark(profilerMarkName: string): void; -declare function open(url?: string, target?: string, features?: string, replace?: boolean): any; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; declare function postMessage(message: any, targetOrigin: string, ports?: any): void; declare function print(): void; declare function prompt(message?: string, _default?: string): string; diff --git a/lib/lib.es7.d.ts b/lib/lib.es7.d.ts new file mode 100644 index 00000000000..4da974fb3bc --- /dev/null +++ b/lib/lib.es7.d.ts @@ -0,0 +1,18829 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +/// +declare type PropertyKey = string | number | symbol; + +interface Symbol { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + readonly [Symbol.toStringTag]: "Symbol"; +} + +interface SymbolConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Symbol; + + /** + * Returns a new unique Symbol value. + * @param description Description of the new Symbol object. + */ + (description?: string|number): symbol; + + /** + * Returns a Symbol object from the global symbol registry matching the given key if found. + * Otherwise, returns a new symbol with this key. + * @param key key to search for. + */ + for(key: string): symbol; + + /** + * Returns a key from the global symbol registry matching the given Symbol if found. + * Otherwise, returns a undefined. + * @param sym Symbol to find the key for. + */ + keyFor(sym: symbol): string; + + // Well-known Symbols + + /** + * A method that determines if a constructor object recognizes an object as one of the + * constructor’s instances. Called by the semantics of the instanceof operator. + */ + readonly hasInstance: symbol; + + /** + * A Boolean value that if true indicates that an object should flatten to its array elements + * by Array.prototype.concat. + */ + readonly isConcatSpreadable: symbol; + + /** + * A method that returns the default iterator for an object. Called by the semantics of the + * for-of statement. + */ + readonly iterator: symbol; + + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.match method. + */ + readonly match: symbol; + + /** + * A regular expression method that replaces matched substrings of a string. Called by the + * String.prototype.replace method. + */ + readonly replace: symbol; + + /** + * A regular expression method that returns the index within a string that matches the + * regular expression. Called by the String.prototype.search method. + */ + readonly search: symbol; + + /** + * A function valued property that is the constructor function that is used to create + * derived objects. + */ + readonly species: symbol; + + /** + * A regular expression method that splits a string at the indices that match the regular + * expression. Called by the String.prototype.split method. + */ + readonly split: symbol; + + /** + * A method that converts an object to a corresponding primitive value. + * Called by the ToPrimitive abstract operation. + */ + readonly toPrimitive: symbol; + + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; + + /** + * An Object whose own property names are property names that are excluded from the 'with' + * environment bindings of the associated objects. + */ + readonly unscopables: symbol; +} +declare var Symbol: SymbolConstructor; + +interface Object { + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ + assign(target: any, ...sources: any[]): any; + + /** + * Returns an array of all symbol properties found directly on object o. + * @param o Object to retrieve the symbols from. + */ + getOwnPropertySymbols(o: any): symbol[]; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + */ + setPrototypeOf(o: any, proto: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not + * inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript + * object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor + * property. + */ + defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any; +} + +interface Function { + /** + * Returns the name of the function. Function names are read-only and can not be changed. + */ + readonly name: string; + + /** + * Determines whether the given value inherits from this function if this function was used + * as a constructor function. + * + * A constructor function can control which objects are recognized as its instances by + * 'instanceof' by overriding this method. + */ + [Symbol.hasInstance](value: any): boolean; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍â’‍16. + */ + readonly EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 â’ 1. + */ + readonly MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n â’ 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is â’9007199254740991 (â’(2^53 â’ 1)). + */ + readonly MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface Array { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns an object whose properties have the value 'true' + * when they will be absent when used in a 'with' statement. + */ + [Symbol.unscopables](): { + copyWithin: boolean; + entries: boolean; + fill: boolean; + find: boolean; + findIndex: boolean; + keys: boolean; + values: boolean; + }; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: T) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): T[]; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): T[]; +} + +interface IArguments { + /** Iterator */ + [Symbol.iterator](): IterableIterator; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: Iterable, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: Iterable): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface String { + /** Iterator */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns the String value result of normalizing the string into the normalization form + * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. + * @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default + * is "NFC" + */ + normalize(form?: string): string; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + // Overloads for objects with methods of well-known symbols. + + /** + * Matches a string an object that supports being matched against, and returns an array containing the results of that search. + * @param matcher An object that supports being matched against. + */ + match(matcher: { [Symbol.match](string: string): RegExpMatchArray; }): RegExpMatchArray; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; + + /** + * Replaces text in a string, using an object that supports replacement within a string. + * @param searchValue A object can search for and replace matches within a string. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param searcher An object which supports searching within a string. + */ + search(searcher: { [Symbol.search](string: string): number; }): number; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param splitter An object that can split a string. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + +interface IteratorResult { + done: boolean; + value?: T; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +interface IterableIterator extends Iterator { + [Symbol.iterator](): IterableIterator; +} + +interface GeneratorFunction extends Function { + readonly [Symbol.toStringTag]: "GeneratorFunction"; +} + +interface GeneratorFunctionConstructor { + /** + * Creates a new Generator function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): GeneratorFunction; + (...args: string[]): GeneratorFunction; + readonly prototype: GeneratorFunction; +} +declare var GeneratorFunction: GeneratorFunctionConstructor; + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or â’0, the result is +0. + */ + hypot(...values: number[] ): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; + + readonly [Symbol.toStringTag]: "Math"; +} + +interface Date { + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "default"): string; + /** + * Converts a Date object to a string. + */ + [Symbol.toPrimitive](hint: "string"): string; + /** + * Converts a Date object to a number. + */ + [Symbol.toPrimitive](hint: "number"): number; + /** + * Converts a Date object to a string or number. + * + * @param hint The strings "number", "string", or "default" to specify what primitive to return. + * + * @throws {TypeError} If 'hint' was given something other than "number", "string", or "default". + * @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default". + */ + [Symbol.toPrimitive](hint: string): string | number; +} + +interface RegExp { + /** + * Matches a string with this regular expression, and returns an array containing the results of + * that search. + * @param string A string to search within. + */ + [Symbol.match](string: string): RegExpMatchArray; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replaceValue A String object or string literal containing the text to replace for every + * successful match of this regular expression. + */ + [Symbol.replace](string: string, replaceValue: string): string; + + /** + * Replaces text in a string, using this regular expression. + * @param string A String object or string literal whose contents matching against + * this regular expression will be replaced + * @param replacer A function that returns the replacement text. + */ + [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the position beginning first substring match in a regular expression search + * using this regular expression. + * + * @param string The string to search within. + */ + [Symbol.search](string: string): number; + + /** + * Returns an array of substrings that were delimited by strings in the original input that + * match against this regular expression. + * + * If the regular expression contains capturing parentheses, then each time this + * regular expression matches, the results (including any undefined results) of the + * capturing parentheses are spliced. + * + * @param string string value to split + * @param limit if not undefined, the output array is truncated so that it contains no more + * than 'limit' elements. + */ + [Symbol.split](string: string, limit?: number): string[]; + + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + readonly flags: string; + + /** + * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular + * expression. Default is false. Read-only. + */ + readonly sticky: boolean; + + /** + * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular + * expression. Default is false. Read-only. + */ + readonly unicode: boolean; +} + +interface RegExpConstructor { + [Symbol.species](): RegExpConstructor; +} + +interface Map { + clear(): void; + delete(key: K): boolean; + entries(): IterableIterator<[K, V]>; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V; + has(key: K): boolean; + keys(): IterableIterator; + set(key: K, value?: V): Map; + readonly size: number; + values(): IterableIterator; + [Symbol.iterator]():IterableIterator<[K,V]>; + readonly [Symbol.toStringTag]: "Map"; +} + +interface MapConstructor { + new (): Map; + new (): Map; + new (iterable: Iterable<[K, V]>): Map; + readonly prototype: Map; +} +declare var Map: MapConstructor; + +interface WeakMap { + clear(): void; + delete(key: K): boolean; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): WeakMap; + readonly [Symbol.toStringTag]: "WeakMap"; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (): WeakMap; + new (iterable: Iterable<[K, V]>): WeakMap; + readonly prototype: WeakMap; +} +declare var WeakMap: WeakMapConstructor; + +interface Set { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + entries(): IterableIterator<[T, T]>; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + keys(): IterableIterator; + readonly size: number; + values(): IterableIterator; + [Symbol.iterator]():IterableIterator; + readonly [Symbol.toStringTag]: "Set"; +} + +interface SetConstructor { + new (): Set; + new (): Set; + new (iterable: Iterable): Set; + readonly prototype: Set; +} +declare var Set: SetConstructor; + +interface WeakSet { + add(value: T): WeakSet; + clear(): void; + delete(value: T): boolean; + has(value: T): boolean; + readonly [Symbol.toStringTag]: "WeakSet"; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (): WeakSet; + new (iterable: Iterable): WeakSet; + readonly prototype: WeakSet; +} +declare var WeakSet: WeakSetConstructor; + +interface JSON { + readonly [Symbol.toStringTag]: "JSON"; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + readonly [Symbol.toStringTag]: "ArrayBuffer"; +} + +interface DataView { + readonly [Symbol.toStringTag]: "DataView"; +} + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int8Array"; +} + +interface Int8ArrayConstructor { + new (elements: Iterable): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; +} + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "UInt8Array"; +} + +interface Uint8ArrayConstructor { + new (elements: Iterable): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; +} + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint8ClampedArray"; +} + +interface Uint8ClampedArrayConstructor { + new (elements: Iterable): Uint8ClampedArray; + + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + + + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int16Array"; +} + +interface Int16ArrayConstructor { + new (elements: Iterable): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; +} + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint16Array"; +} + +interface Uint16ArrayConstructor { + new (elements: Iterable): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; +} + +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Int32Array"; +} + +interface Int32ArrayConstructor { + new (elements: Iterable): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; +} + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Uint32Array"; +} + +interface Uint32ArrayConstructor { + new (elements: Iterable): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; +} + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Float32Array"; +} + +interface Float32ArrayConstructor { + new (elements: Iterable): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; +} + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIterator<[number, number]>; + /** + * Returns an list of keys in the array + */ + keys(): IterableIterator; + /** + * Returns an list of values in the array + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; + readonly [Symbol.toStringTag]: "Float64Array"; +} + +interface Float64ArrayConstructor { + new (elements: Iterable): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; +} + +interface ProxyHandler { + getPrototypeOf? (target: T): any; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, thisArg: any, argArray?: any): any; +} + +interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T +} +declare var Proxy: ProxyConstructor; + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): IterableIterator; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: string): boolean; + function has(target: any, propertyKey: symbol): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; +} + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: (reason: any) => T | PromiseLike): Promise; + catch(onrejected?: (reason: any) => void): Promise; + + readonly [Symbol.toStringTag]: "Promise"; +} + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + readonly prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + all(values: Iterable>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: Iterable>): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; + + readonly [Symbol.species]: Function; +} + +declare var Promise: PromiseConstructor; +interface Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: T, fromIndex?: number): boolean; +} + +interface Int8Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint8Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint8ClampedArray { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Int16Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint16Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Int32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Float32Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Float64Array { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +}///////////////////////////// +/// ECMAScript APIs +///////////////////////////// + +declare const NaN: number; +declare const Infinity: number; + +/** + * Evaluates JavaScript code and executes it. + * @param x A String value that contains valid JavaScript code. + */ +declare function eval(x: string): any; + +/** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ +declare function parseInt(s: string, radix?: number): number; + +/** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ +declare function parseFloat(string: string): number; + +/** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ +declare function isNaN(number: number): boolean; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): boolean; + +/** + * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). + * @param encodedURI A value representing an encoded URI. + */ +declare function decodeURI(encodedURI: string): string; + +/** + * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). + * @param encodedURIComponent A value representing an encoded URI component. + */ +declare function decodeURIComponent(encodedURIComponent: string): string; + +/** + * Encodes a text string as a valid Uniform Resource Identifier (URI) + * @param uri A value representing an encoded URI. + */ +declare function encodeURI(uri: string): string; + +/** + * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). + * @param uriComponent A value representing an encoded URI component. + */ +declare function encodeURIComponent(uriComponent: string): string; + +interface PropertyDescriptor { + configurable?: boolean; + enumerable?: boolean; + value?: any; + writable?: boolean; + get? (): any; + set? (v: any): void; +} + +interface PropertyDescriptorMap { + [s: string]: PropertyDescriptor; +} + +interface Object { + /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ + constructor: Function; + + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns a date converted to a string using the current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: string): boolean; + + /** + * Determines whether an object exists in another object's prototype chain. + * @param v Another object whose prototype chain is to be checked. + */ + isPrototypeOf(v: Object): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: string): boolean; +} + +interface ObjectConstructor { + new (value?: any): Object; + (): any; + (value: any): any; + + /** A reference to the prototype for a class of objects. */ + readonly prototype: Object; + + /** + * Returns the prototype of an object. + * @param o The object that references the prototype. + */ + getPrototypeOf(o: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + + /** + * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly + * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. + * @param o Object that contains the own properties. + */ + getOwnPropertyNames(o: any): string[]; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + * @param properties JavaScript object that contains one or more property descriptors. + */ + create(o: any, properties?: PropertyDescriptorMap): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor property. + */ + defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; + + /** + * Adds one or more properties to an object, and/or modifies attributes of existing properties. + * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. + * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. + */ + defineProperties(o: any, properties: PropertyDescriptorMap): any; + + /** + * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + seal(o: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: T): T; + + /** + * Prevents the addition of new properties to an object. + * @param o Object to make non-extensible. + */ + preventExtensions(o: T): T; + + /** + * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. + * @param o Object to test. + */ + isSealed(o: any): boolean; + + /** + * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. + * @param o Object to test. + */ + isFrozen(o: any): boolean; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): boolean; + + /** + * Returns the names of the enumerable properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keys(o: any): string[]; +} + +/** + * Provides functionality common to all JavaScript objects. + */ +declare const Object: ObjectConstructor; + +/** + * Creates a new function. + */ +interface Function { + /** + * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. + * @param thisArg The object to be used as the this object. + * @param argArray A set of arguments to be passed to the function. + */ + apply(thisArg: any, argArray?: any): any; + + /** + * Calls a method of an object, substituting another object for the current object. + * @param thisArg The object to be used as the current object. + * @param argArray A list of arguments to be passed to the method. + */ + call(thisArg: any, ...argArray: any[]): any; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg An object to which the this keyword can refer inside the new function. + * @param argArray A list of arguments to be passed to the new function. + */ + bind(thisArg: any, ...argArray: any[]): any; + + prototype: any; + readonly length: number; + + // Non-standard extensions + arguments: any; + caller: Function; +} + +interface FunctionConstructor { + /** + * Creates a new function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): Function; + (...args: string[]): Function; + readonly prototype: Function; +} + +declare const Function: FunctionConstructor; + +interface IArguments { + [index: number]: any; + length: number; + callee: Function; +} + +interface String { + /** Returns a string representation of a string. */ + toString(): string; + + /** + * Returns the character at the specified index. + * @param pos The zero-based index of the desired character. + */ + charAt(pos: number): string; + + /** + * Returns the Unicode value of the character at the specified location. + * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + */ + charCodeAt(index: number): number; + + /** + * Returns a string that contains the concatenation of two or more strings. + * @param strings The strings to append to the end of the string. + */ + concat(...strings: string[]): string; + + /** + * Returns the position of the first occurrence of a substring. + * @param searchString The substring to search for in the string + * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. + */ + indexOf(searchString: string, position?: number): number; + + /** + * Returns the last occurrence of a substring in the string. + * @param searchString The substring to search for. + * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. + */ + lastIndexOf(searchString: string, position?: number): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + */ + localeCompare(that: string): number; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + match(regexp: string): RegExpMatchArray; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. + */ + match(regexp: RegExp): RegExpMatchArray; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string that represents the regular expression. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: string, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string that represents the regular expression. + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: RegExp, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags + * @param replacer A function that returns the replacement text. + */ + replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: string): number; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: RegExp): number; + + /** + * Returns a section of a string. + * @param start The index to the beginning of the specified portion of stringObj. + * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. + * If this value is not specified, the substring continues to the end of stringObj. + */ + slice(start?: number, end?: number): string; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: string, limit?: number): string[]; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: RegExp, limit?: number): string[]; + + /** + * Returns the substring at the specified location within a String object. + * @param start The zero-based index number indicating the beginning of the substring. + * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. + * If end is omitted, the characters from start through the end of the original string are returned. + */ + substring(start: number, end?: number): string; + + /** Converts all the alphabetic characters in a string to lowercase. */ + toLowerCase(): string; + + /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ + toLocaleLowerCase(): string; + + /** Converts all the alphabetic characters in a string to uppercase. */ + toUpperCase(): string; + + /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ + toLocaleUpperCase(): string; + + /** Removes the leading and trailing white space and line terminator characters from a string. */ + trim(): string; + + /** Returns the length of a String object. */ + readonly length: number; + + // IE extensions + /** + * Gets a substring beginning at the specified location and having the specified length. + * @param from The starting position of the desired substring. The index of the first character in the string is zero. + * @param length The number of characters to include in the returned substring. + */ + substr(from: number, length?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): string; + + readonly [index: number]: string; +} + +interface StringConstructor { + new (value?: any): String; + (value?: any): string; + readonly prototype: String; + fromCharCode(...codes: number[]): string; +} + +/** + * Allows manipulation and formatting of text strings and determination and location of substrings within strings. + */ +declare const String: StringConstructor; + +interface Boolean { + /** Returns the primitive value of the specified object. */ + valueOf(): boolean; +} + +interface BooleanConstructor { + new (value?: any): Boolean; + (value?: any): boolean; + readonly prototype: Boolean; +} + +declare const Boolean: BooleanConstructor; + +interface Number { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. + */ + toString(radix?: number): string; + + /** + * Returns a string representing a number in fixed-point notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toFixed(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented in exponential notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toExponential(fractionDigits?: number): string; + + /** + * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. + * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + */ + toPrecision(precision?: number): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): number; +} + +interface NumberConstructor { + new (value?: any): Number; + (value?: any): number; + readonly prototype: Number; + + /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ + readonly MAX_VALUE: number; + + /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ + readonly MIN_VALUE: number; + + /** + * A value that is not a number. + * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. + */ + readonly NaN: number; + + /** + * A value that is less than the largest negative number that can be represented in JavaScript. + * JavaScript displays NEGATIVE_INFINITY values as -infinity. + */ + readonly NEGATIVE_INFINITY: number; + + /** + * A value greater than the largest number that can be represented in JavaScript. + * JavaScript displays POSITIVE_INFINITY values as infinity. + */ + readonly POSITIVE_INFINITY: number; +} + +/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ +declare const Number: NumberConstructor; + +interface TemplateStringsArray extends Array { + readonly raw: string[]; +} + +interface Math { + /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ + readonly E: number; + /** The natural logarithm of 10. */ + readonly LN10: number; + /** The natural logarithm of 2. */ + readonly LN2: number; + /** The base-2 logarithm of e. */ + readonly LOG2E: number; + /** The base-10 logarithm of e. */ + readonly LOG10E: number; + /** Pi. This is the ratio of the circumference of a circle to its diameter. */ + readonly PI: number; + /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ + readonly SQRT1_2: number; + /** The square root of 2. */ + readonly SQRT2: number; + /** + * Returns the absolute value of a number (the value without regard to whether it is positive or negative). + * For example, the absolute value of -5 is the same as the absolute value of 5. + * @param x A numeric expression for which the absolute value is needed. + */ + abs(x: number): number; + /** + * Returns the arc cosine (or inverse cosine) of a number. + * @param x A numeric expression. + */ + acos(x: number): number; + /** + * Returns the arcsine of a number. + * @param x A numeric expression. + */ + asin(x: number): number; + /** + * Returns the arctangent of a number. + * @param x A numeric expression for which the arctangent is needed. + */ + atan(x: number): number; + /** + * Returns the angle (in radians) from the X axis to a point. + * @param y A numeric expression representing the cartesian y-coordinate. + * @param x A numeric expression representing the cartesian x-coordinate. + */ + atan2(y: number, x: number): number; + /** + * Returns the smallest number greater than or equal to its numeric argument. + * @param x A numeric expression. + */ + ceil(x: number): number; + /** + * Returns the cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cos(x: number): number; + /** + * Returns e (the base of natural logarithms) raised to a power. + * @param x A numeric expression representing the power of e. + */ + exp(x: number): number; + /** + * Returns the greatest number less than or equal to its numeric argument. + * @param x A numeric expression. + */ + floor(x: number): number; + /** + * Returns the natural logarithm (base e) of a number. + * @param x A numeric expression. + */ + log(x: number): number; + /** + * Returns the larger of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + max(...values: number[]): number; + /** + * Returns the smaller of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + min(...values: number[]): number; + /** + * Returns the value of a base expression taken to a specified power. + * @param x The base value of the expression. + * @param y The exponent value of the expression. + */ + pow(x: number, y: number): number; + /** Returns a pseudorandom number between 0 and 1. */ + random(): number; + /** + * Returns a supplied numeric expression rounded to the nearest number. + * @param x The value to be rounded to the nearest number. + */ + round(x: number): number; + /** + * Returns the sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sin(x: number): number; + /** + * Returns the square root of a number. + * @param x A numeric expression. + */ + sqrt(x: number): number; + /** + * Returns the tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tan(x: number): number; +} +/** An intrinsic object that provides basic mathematics functionality and constants. */ +declare const Math: Math; + +/** Enables basic storage and retrieval of dates and times. */ +interface Date { + /** Returns a string representation of a date. The format of the string depends on the locale. */ + toString(): string; + /** Returns a date as a string value. */ + toDateString(): string; + /** Returns a time as a string value. */ + toTimeString(): string; + /** Returns a value as a string value appropriate to the host environment's current locale. */ + toLocaleString(): string; + /** Returns a date as a string value appropriate to the host environment's current locale. */ + toLocaleDateString(): string; + /** Returns a time as a string value appropriate to the host environment's current locale. */ + toLocaleTimeString(): string; + /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ + valueOf(): number; + /** Gets the time value in milliseconds. */ + getTime(): number; + /** Gets the year, using local time. */ + getFullYear(): number; + /** Gets the year using Universal Coordinated Time (UTC). */ + getUTCFullYear(): number; + /** Gets the month, using local time. */ + getMonth(): number; + /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ + getUTCMonth(): number; + /** Gets the day-of-the-month, using local time. */ + getDate(): number; + /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ + getUTCDate(): number; + /** Gets the day of the week, using local time. */ + getDay(): number; + /** Gets the day of the week using Universal Coordinated Time (UTC). */ + getUTCDay(): number; + /** Gets the hours in a date, using local time. */ + getHours(): number; + /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ + getUTCHours(): number; + /** Gets the minutes of a Date object, using local time. */ + getMinutes(): number; + /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ + getUTCMinutes(): number; + /** Gets the seconds of a Date object, using local time. */ + getSeconds(): number; + /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCSeconds(): number; + /** Gets the milliseconds of a Date, using local time. */ + getMilliseconds(): number; + /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCMilliseconds(): number; + /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ + getTimezoneOffset(): number; + /** + * Sets the date and time value in the Date object. + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + */ + setTime(time: number): number; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): number; + /** + * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). + * @param ms A numeric value equal to the millisecond value. + */ + setUTCMilliseconds(ms: number): number; + + /** + * Sets the seconds value in the Date object using local time. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setSeconds(sec: number, ms?: number): number; + /** + * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCSeconds(sec: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using local time. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCMinutes(min: number, sec?: number, ms?: number): number; + /** + * Sets the hour value in the Date object using local time. + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the hours value in the Date object using Universal Coordinated Time (UTC). + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + /** + * Sets the numeric day-of-the-month value of the Date object using local time. + * @param date A numeric value equal to the day of the month. + */ + setDate(date: number): number; + /** + * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). + * @param date A numeric value equal to the day of the month. + */ + setUTCDate(date: number): number; + /** + * Sets the month value in the Date object using local time. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. + */ + setMonth(month: number, date?: number): number; + /** + * Sets the month value in the Date object using Universal Coordinated Time (UTC). + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. + */ + setUTCMonth(month: number, date?: number): number; + /** + * Sets the year of the Date object using local time. + * @param year A numeric value for the year. + * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. + * @param date A numeric value equal for the day of the month. + */ + setFullYear(year: number, month?: number, date?: number): number; + /** + * Sets the year value in the Date object using Universal Coordinated Time (UTC). + * @param year A numeric value equal to the year. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. + * @param date A numeric value equal to the day of the month. + */ + setUTCFullYear(year: number, month?: number, date?: number): number; + /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ + toUTCString(): string; + /** Returns a date as a string value in ISO format. */ + toISOString(): string; + /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ + toJSON(key?: any): string; +} + +interface DateConstructor { + new (): Date; + new (value: number): Date; + new (value: string): Date; + new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + (): string; + readonly prototype: Date; + /** + * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. + * @param s A date string + */ + parse(s: string): number; + /** + * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param month The month as an number between 0 and 11 (January to December). + * @param date The date as an number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. + * @param ms An number from 0 to 999 that specifies the milliseconds. + */ + UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + now(): number; +} + +declare const Date: DateConstructor; + +interface RegExpMatchArray extends Array { + index?: number; + input?: string; +} + +interface RegExpExecArray extends Array { + index: number; + input: string; +} + +interface RegExp { + /** + * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. + * @param string The String object or string literal on which to perform the search. + */ + exec(string: string): RegExpExecArray; + + /** + * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. + * @param string String on which to perform the search. + */ + test(string: string): boolean; + + /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ + readonly source: string; + + /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ + readonly global: boolean; + + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + readonly ignoreCase: boolean; + + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + readonly multiline: boolean; + + lastIndex: number; + + // Non-standard extensions + compile(): RegExp; +} + +interface RegExpConstructor { + new (pattern: string, flags?: string): RegExp; + (pattern: string, flags?: string): RegExp; + readonly prototype: RegExp; + + // Non-standard extensions + $1: string; + $2: string; + $3: string; + $4: string; + $5: string; + $6: string; + $7: string; + $8: string; + $9: string; + lastMatch: string; +} + +declare const RegExp: RegExpConstructor; + +interface Error { + name: string; + message: string; +} + +interface ErrorConstructor { + new (message?: string): Error; + (message?: string): Error; + readonly prototype: Error; +} + +declare const Error: ErrorConstructor; + +interface EvalError extends Error { +} + +interface EvalErrorConstructor { + new (message?: string): EvalError; + (message?: string): EvalError; + readonly prototype: EvalError; +} + +declare const EvalError: EvalErrorConstructor; + +interface RangeError extends Error { +} + +interface RangeErrorConstructor { + new (message?: string): RangeError; + (message?: string): RangeError; + readonly prototype: RangeError; +} + +declare const RangeError: RangeErrorConstructor; + +interface ReferenceError extends Error { +} + +interface ReferenceErrorConstructor { + new (message?: string): ReferenceError; + (message?: string): ReferenceError; + readonly prototype: ReferenceError; +} + +declare const ReferenceError: ReferenceErrorConstructor; + +interface SyntaxError extends Error { +} + +interface SyntaxErrorConstructor { + new (message?: string): SyntaxError; + (message?: string): SyntaxError; + readonly prototype: SyntaxError; +} + +declare const SyntaxError: SyntaxErrorConstructor; + +interface TypeError extends Error { +} + +interface TypeErrorConstructor { + new (message?: string): TypeError; + (message?: string): TypeError; + readonly prototype: TypeError; +} + +declare const TypeError: TypeErrorConstructor; + +interface URIError extends Error { +} + +interface URIErrorConstructor { + new (message?: string): URIError; + (message?: string): URIError; + readonly prototype: URIError; +} + +declare const URIError: URIErrorConstructor; + +interface JSON { + /** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + parse(text: string, reviver?: (key: any, value: any) => any): any; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + */ + stringify(value: any): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + */ + stringify(value: any, replacer: (key: string, value: any) => any): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer Array that transforms the results. + */ + stringify(value: any, replacer: any[]): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer: (key: string, value: any) => any, space: string | number): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer Array that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer: any[], space: string | number): string; +} +/** + * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. + */ +declare const JSON: JSON; + + +///////////////////////////// +/// ECMAScript Array API (specially handled by compiler) +///////////////////////////// + +interface ReadonlyArray { + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + readonly length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat>(...items: U[]): T[]; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: T[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U; + + readonly [n: number]: T; +} + +interface Array { + /** + * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. + */ + length: number; + /** + * Returns a string representation of an array. + */ + toString(): string; + toLocaleString(): string; + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(...items: T[]): number; + /** + * Removes the last element from an array and returns it. + */ + pop(): T; + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat(...items: (T | T[])[]): T[]; + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + /** + * Reverses the elements in an Array. + */ + reverse(): T[]; + /** + * Removes the first element from an array and returns it. + */ + shift(): T; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): T[]; + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: T, b: T) => number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + */ + splice(start: number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(...items: T[]): number; + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; + + [n: number]: T; +} + +interface ArrayConstructor { + new (arrayLength?: number): any[]; + new (arrayLength: number): T[]; + new (...items: T[]): T[]; + (arrayLength?: number): any[]; + (arrayLength: number): T[]; + (...items: T[]): T[]; + isArray(arg: any): arg is Array; + readonly prototype: Array; +} + +declare const Array: ArrayConstructor; + +interface TypedPropertyDescriptor { + enumerable?: boolean; + configurable?: boolean; + writable?: boolean; + value?: T; + get?: () => T; + set?: (value: T) => void; +} + +declare type ClassDecorator = (target: TFunction) => TFunction | void; +declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; +declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; +declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; + +declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike; + +interface PromiseLike { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; +} + +interface ArrayLike { + readonly length: number; + readonly [n: number]: T; +} + +/** + * Represents a raw buffer of binary data, which is used to store data for the + * different typed arrays. ArrayBuffers cannot be read from or written to directly, + * but can be passed to a typed array or DataView Object to interpret the raw + * buffer as needed. + */ +interface ArrayBuffer { + /** + * Read-only. The length of the ArrayBuffer (in bytes). + */ + readonly byteLength: number; + + /** + * Returns a section of an ArrayBuffer. + */ + slice(begin:number, end?:number): ArrayBuffer; +} + +interface ArrayBufferConstructor { + readonly prototype: ArrayBuffer; + new (byteLength: number): ArrayBuffer; + isView(arg: any): arg is ArrayBufferView; +} +declare const ArrayBuffer: ArrayBufferConstructor; + +interface ArrayBufferView { + /** + * The ArrayBuffer instance referenced by the array. + */ + buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + byteLength: number; + + /** + * The offset in bytes of the array. + */ + byteOffset: number; +} + +interface DataView { + readonly buffer: ArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + /** + * Gets the Float32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Float64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getFloat64(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Int8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt8(byteOffset: number): number; + + /** + * Gets the Int16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt16(byteOffset: number, littleEndian?: boolean): number; + /** + * Gets the Int32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getInt32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint8 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint8(byteOffset: number): number; + + /** + * Gets the Uint16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Gets the Uint32 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getUint32(byteOffset: number, littleEndian?: boolean): number; + + /** + * Stores an Float32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Float64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setInt8(byteOffset: number, value: number): void; + + /** + * Stores an Int16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Int32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint8 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + */ + setUint8(byteOffset: number, value: number): void; + + /** + * Stores an Uint16 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; + + /** + * Stores an Uint32 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; +} + +interface DataViewConstructor { + new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView; +} +declare const DataView: DataViewConstructor; + +/** + * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Int8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Int8Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Int8Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): Int8Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int8Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Int8Array; + + /** + * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} +interface Int8ArrayConstructor { + readonly prototype: Int8Array; + new (length: number): Int8Array; + new (array: ArrayLike): Int8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; + +} +declare const Int8Array: Int8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Uint8Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Uint8Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): Uint8Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Uint8Array; + + /** + * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ArrayConstructor { + readonly prototype: Uint8Array; + new (length: number): Uint8Array; + new (array: ArrayLike): Uint8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; + +} +declare const Uint8Array: Uint8ArrayConstructor; + +/** + * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. + * If the requested number of bytes could not be allocated an exception is raised. + */ +interface Uint8ClampedArray { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Uint8ClampedArray; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Uint8ClampedArray; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): Uint8ClampedArray; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint8ClampedArray; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: Uint8ClampedArray, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint8ClampedArray; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Uint8ClampedArray; + + /** + * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint8ClampedArray; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint8ClampedArrayConstructor { + readonly prototype: Uint8ClampedArray; + new (length: number): Uint8ClampedArray; + new (array: ArrayLike): Uint8ClampedArray; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint8ClampedArray; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; +} +declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; + +/** + * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Int16Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Int16Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): Int16Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int16Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Int16Array; + + /** + * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int16ArrayConstructor { + readonly prototype: Int16Array; + new (length: number): Int16Array; + new (array: ArrayLike): Int16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; + +} +declare const Int16Array: Int16ArrayConstructor; + +/** + * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint16Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Uint16Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Uint16Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): Uint16Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint16Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint16Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Uint16Array; + + /** + * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint16Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint16ArrayConstructor { + readonly prototype: Uint16Array; + new (length: number): Uint16Array; + new (array: ArrayLike): Uint16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint16Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; + +} +declare const Uint16Array: Uint16ArrayConstructor; +/** + * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Int32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Int32Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Int32Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): Int32Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Int32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Int32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Int32Array; + + /** + * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Int32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Int32ArrayConstructor { + readonly prototype: Int32Array; + new (length: number): Int32Array; + new (array: ArrayLike): Int32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Int32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; +} +declare const Int32Array: Int32ArrayConstructor; + +/** + * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated an exception is raised. + */ +interface Uint32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Uint32Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Uint32Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): Uint32Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Uint32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Uint32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Uint32Array; + + /** + * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Uint32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Uint32ArrayConstructor { + readonly prototype: Uint32Array; + new (length: number): Uint32Array; + new (array: ArrayLike): Uint32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Uint32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; +} +declare const Uint32Array: Uint32ArrayConstructor; + +/** + * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number + * of bytes could not be allocated an exception is raised. + */ +interface Float32Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Float32Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Float32Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): Float32Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float32Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float32Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Float32Array; + + /** + * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float32Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float32ArrayConstructor { + readonly prototype: Float32Array; + new (length: number): Float32Array; + new (array: ArrayLike): Float32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float32Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; + +} +declare const Float32Array: Float32ArrayConstructor; + +/** + * A typed array of 64-bit float values. The contents are initialized to 0. If the requested + * number of bytes could not be allocated an exception is raised. + */ +interface Float64Array { + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * The ArrayBuffer instance referenced by the array. + */ + readonly buffer: ArrayBuffer; + + /** + * The length in bytes of the array. + */ + readonly byteLength: number; + + /** + * The offset in bytes of the array. + */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): Float64Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in array1 until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: number, start?: number, end?: number): Float64Array; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): Float64Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + + /** + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: number) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: number, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: number, fromIndex?: number): number; + + /** + * The length of the array. + */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue?: number): number; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Float64Array; + + /** + * Sets a value or an array of values. + * @param index The index of the location to set. + * @param value The value to set. + */ + set(index: number, value: number): void; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): Float64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in array1 until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If + * omitted, the elements are sorted in ascending, ASCII character order. + */ + sort(compareFn?: (a: number, b: number) => number): Float64Array; + + /** + * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): Float64Array; + + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + [index: number]: number; +} + +interface Float64ArrayConstructor { + readonly prototype: Float64Array; + new (length: number): Float64Array; + new (array: ArrayLike): Float64Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + + /** + * The size in bytes of each element in the array. + */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: number[]): Float64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; +} +declare const Float64Array: Float64ArrayConstructor; +///////////////////////////// +/// ECMAScript Internationalization API +///////////////////////////// + +declare module Intl { + interface CollatorOptions { + usage?: string; + localeMatcher?: string; + numeric?: boolean; + caseFirst?: string; + sensitivity?: string; + ignorePunctuation?: boolean; + } + + interface ResolvedCollatorOptions { + locale: string; + usage: string; + sensitivity: string; + ignorePunctuation: boolean; + collation: string; + caseFirst: string; + numeric: boolean; + } + + interface Collator { + compare(x: string, y: string): number; + resolvedOptions(): ResolvedCollatorOptions; + } + var Collator: { + new (locales?: string[], options?: CollatorOptions): Collator; + new (locale?: string, options?: CollatorOptions): Collator; + (locales?: string[], options?: CollatorOptions): Collator; + (locale?: string, options?: CollatorOptions): Collator; + supportedLocalesOf(locales: string[], options?: CollatorOptions): string[]; + supportedLocalesOf(locale: string, options?: CollatorOptions): string[]; + } + + interface NumberFormatOptions { + localeMatcher?: string; + style?: string; + currency?: string; + currencyDisplay?: string; + useGrouping?: boolean; + minimumIntegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + } + + interface ResolvedNumberFormatOptions { + locale: string; + numberingSystem: string; + style: string; + currency?: string; + currencyDisplay?: string; + minimumIntegerDigits: number; + minimumFractionDigits: number; + maximumFractionDigits: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + useGrouping: boolean; + } + + interface NumberFormat { + format(value: number): string; + resolvedOptions(): ResolvedNumberFormatOptions; + } + var NumberFormat: { + 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[]; + } + + interface DateTimeFormatOptions { + localeMatcher?: string; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + formatMatcher?: string; + hour12?: boolean; + timeZone?: string; + } + + interface ResolvedDateTimeFormatOptions { + locale: string; + calendar: string; + numberingSystem: string; + timeZone: string; + hour12?: boolean; + weekday?: string; + era?: string; + year?: string; + month?: string; + day?: string; + hour?: string; + minute?: string; + second?: string; + timeZoneName?: string; + } + + interface DateTimeFormat { + format(date?: Date | number): string; + resolvedOptions(): ResolvedDateTimeFormatOptions; + } + var DateTimeFormat: { + 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[]; + } +} + +interface String { + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. + * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. + */ + localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. + * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. + */ + localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number; +} + +interface Number { + /** + * Converts a number to a string by using the current or specified locale. + * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string; + + /** + * Converts a number to a string by using the current or specified locale. + * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string; +} + +interface Date { + /** + * Converts a date and time to a string by using the current or specified locale. + * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + /** + * Converts a date to a string by using the current or specified locale. + * @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string; + + /** + * Converts a time to a string by using the current or specified locale. + * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string; + + /** + * Converts a date and time to a string by using the current or specified locale. + * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string; + + /** + * Converts a date to a string by using the current or specified locale. + * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string; + + /** + * Converts a time to a string by using the current or specified locale. + * @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string; +} + + +///////////////////////////// +/// IE DOM APIs +///////////////////////////// + +interface Algorithm { + name?: string; +} + +interface AriaRequestEventInit extends EventInit { + attributeName?: string; + attributeValue?: string; +} + +interface ClipboardEventInit extends EventInit { + data?: string; + dataType?: string; +} + +interface CommandEventInit extends EventInit { + commandName?: string; + detail?: string; +} + +interface CompositionEventInit extends UIEventInit { + data?: string; +} + +interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { + arrayOfDomainStrings?: string[]; +} + +interface CustomEventInit extends EventInit { + detail?: any; +} + +interface DeviceAccelerationDict { + x?: number; + y?: number; + z?: number; +} + +interface DeviceRotationRateDict { + alpha?: number; + beta?: number; + gamma?: number; +} + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; +} + +interface ExceptionInformation { + domain?: string; +} + +interface FocusEventInit extends UIEventInit { + relatedTarget?: EventTarget; +} + +interface HashChangeEventInit extends EventInit { + newURL?: string; + oldURL?: string; +} + +interface KeyAlgorithm { + name?: string; +} + +interface KeyboardEventInit extends SharedKeyboardAndMouseEventInit { + key?: string; + location?: number; + repeat?: boolean; +} + +interface MouseEventInit extends SharedKeyboardAndMouseEventInit { + screenX?: number; + screenY?: number; + clientX?: number; + clientY?: number; + button?: number; + buttons?: number; + relatedTarget?: EventTarget; +} + +interface MsZoomToOptions { + contentX?: number; + contentY?: number; + viewportX?: string; + viewportY?: string; + scaleFactor?: number; + animate?: string; +} + +interface MutationObserverInit { + childList?: boolean; + attributes?: boolean; + characterData?: boolean; + subtree?: boolean; + attributeOldValue?: boolean; + characterDataOldValue?: boolean; + attributeFilter?: string[]; +} + +interface ObjectURLOptions { + oneTimeOnly?: boolean; +} + +interface PointerEventInit extends MouseEventInit { + pointerId?: number; + width?: number; + height?: number; + pressure?: number; + tiltX?: number; + tiltY?: number; + pointerType?: string; + isPrimary?: boolean; +} + +interface PositionOptions { + enableHighAccuracy?: boolean; + timeout?: number; + maximumAge?: number; +} + +interface SharedKeyboardAndMouseEventInit extends UIEventInit { + ctrlKey?: boolean; + shiftKey?: boolean; + altKey?: boolean; + metaKey?: boolean; + keyModifierStateAltGraph?: boolean; + keyModifierStateCapsLock?: boolean; + keyModifierStateFn?: boolean; + keyModifierStateFnLock?: boolean; + keyModifierStateHyper?: boolean; + keyModifierStateNumLock?: boolean; + keyModifierStateOS?: boolean; + keyModifierStateScrollLock?: boolean; + keyModifierStateSuper?: boolean; + keyModifierStateSymbol?: boolean; + keyModifierStateSymbolLock?: boolean; +} + +interface StoreExceptionsInformation extends ExceptionInformation { + siteName?: string; + explanationString?: string; + detailURI?: string; +} + +interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { + arrayOfDomainStrings?: string[]; +} + +interface UIEventInit extends EventInit { + view?: Window; + detail?: number; +} + +interface WebGLContextAttributes { + alpha?: boolean; + depth?: boolean; + stencil?: boolean; + antialias?: boolean; + premultipliedAlpha?: boolean; + preserveDrawingBuffer?: boolean; +} + +interface WebGLContextEventInit extends EventInit { + statusMessage?: string; +} + +interface WheelEventInit extends MouseEventInit { + deltaX?: number; + deltaY?: number; + deltaZ?: number; + deltaMode?: number; +} + +interface EventListener { + (evt: Event): void; +} + +interface ANGLE_instanced_arrays { + drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void; + drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void; + vertexAttribDivisorANGLE(index: number, divisor: number): void; + VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +} + +declare var ANGLE_instanced_arrays: { + prototype: ANGLE_instanced_arrays; + new(): ANGLE_instanced_arrays; + VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number; +} + +interface AnalyserNode extends AudioNode { + fftSize: number; + frequencyBinCount: number; + maxDecibels: number; + minDecibels: number; + smoothingTimeConstant: number; + getByteFrequencyData(array: Uint8Array): void; + getByteTimeDomainData(array: Uint8Array): void; + getFloatFrequencyData(array: Float32Array): void; + getFloatTimeDomainData(array: Float32Array): void; +} + +declare var AnalyserNode: { + prototype: AnalyserNode; + new(): AnalyserNode; +} + +interface AnimationEvent extends Event { + animationName: string; + elapsedTime: number; + initAnimationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, animationNameArg: string, elapsedTimeArg: number): void; +} + +declare var AnimationEvent: { + prototype: AnimationEvent; + new(): AnimationEvent; +} + +interface ApplicationCache extends EventTarget { + oncached: (ev: Event) => any; + onchecking: (ev: Event) => any; + ondownloading: (ev: Event) => any; + onerror: (ev: Event) => any; + onnoupdate: (ev: Event) => any; + onobsolete: (ev: Event) => any; + onprogress: (ev: ProgressEvent) => any; + onupdateready: (ev: Event) => any; + status: number; + abort(): void; + swapCache(): void; + update(): void; + CHECKING: number; + DOWNLOADING: number; + IDLE: number; + OBSOLETE: number; + UNCACHED: number; + UPDATEREADY: number; + addEventListener(type: "cached", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "checking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "downloading", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "noupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "obsolete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "updateready", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ApplicationCache: { + prototype: ApplicationCache; + new(): ApplicationCache; + CHECKING: number; + DOWNLOADING: number; + IDLE: number; + OBSOLETE: number; + UNCACHED: number; + UPDATEREADY: number; +} + +interface AriaRequestEvent extends Event { + attributeName: string; + attributeValue: string; +} + +declare var AriaRequestEvent: { + prototype: AriaRequestEvent; + new(type: string, eventInitDict?: AriaRequestEventInit): AriaRequestEvent; +} + +interface Attr extends Node { + name: string; + ownerElement: Element; + specified: boolean; + value: string; +} + +declare var Attr: { + prototype: Attr; + new(): Attr; +} + +interface AudioBuffer { + duration: number; + length: number; + numberOfChannels: number; + sampleRate: number; + getChannelData(channel: number): Float32Array; +} + +declare var AudioBuffer: { + prototype: AudioBuffer; + new(): AudioBuffer; +} + +interface AudioBufferSourceNode extends AudioNode { + buffer: AudioBuffer; + loop: boolean; + loopEnd: number; + loopStart: number; + onended: (ev: Event) => any; + playbackRate: AudioParam; + start(when?: number, offset?: number, duration?: number): void; + stop(when?: number): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var AudioBufferSourceNode: { + prototype: AudioBufferSourceNode; + new(): AudioBufferSourceNode; +} + +interface AudioContext extends EventTarget { + currentTime: number; + destination: AudioDestinationNode; + listener: AudioListener; + sampleRate: number; + state: string; + createAnalyser(): AnalyserNode; + createBiquadFilter(): BiquadFilterNode; + createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer; + createBufferSource(): AudioBufferSourceNode; + createChannelMerger(numberOfInputs?: number): ChannelMergerNode; + createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode; + createConvolver(): ConvolverNode; + createDelay(maxDelayTime?: number): DelayNode; + createDynamicsCompressor(): DynamicsCompressorNode; + createGain(): GainNode; + createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode; + createOscillator(): OscillatorNode; + createPanner(): PannerNode; + createPeriodicWave(real: Float32Array, imag: Float32Array): PeriodicWave; + createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode; + createStereoPanner(): StereoPannerNode; + createWaveShaper(): WaveShaperNode; + decodeAudioData(audioData: ArrayBuffer, successCallback: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): void; +} + +declare var AudioContext: { + prototype: AudioContext; + new(): AudioContext; +} + +interface AudioDestinationNode extends AudioNode { + maxChannelCount: number; +} + +declare var AudioDestinationNode: { + prototype: AudioDestinationNode; + new(): AudioDestinationNode; +} + +interface AudioListener { + dopplerFactor: number; + speedOfSound: number; + setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void; + setPosition(x: number, y: number, z: number): void; + setVelocity(x: number, y: number, z: number): void; +} + +declare var AudioListener: { + prototype: AudioListener; + new(): AudioListener; +} + +interface AudioNode extends EventTarget { + channelCount: number; + channelCountMode: string; + channelInterpretation: string; + context: AudioContext; + numberOfInputs: number; + numberOfOutputs: number; + connect(destination: AudioNode, output?: number, input?: number): void; + disconnect(output?: number): void; + disconnect(destination: AudioNode, output?: number, input?: number): void; + disconnect(destination: AudioParam, output?: number): void; +} + +declare var AudioNode: { + prototype: AudioNode; + new(): AudioNode; +} + +interface AudioParam { + defaultValue: number; + value: number; + cancelScheduledValues(startTime: number): void; + exponentialRampToValueAtTime(value: number, endTime: number): void; + linearRampToValueAtTime(value: number, endTime: number): void; + setTargetAtTime(target: number, startTime: number, timeConstant: number): void; + setValueAtTime(value: number, startTime: number): void; + setValueCurveAtTime(values: Float32Array, startTime: number, duration: number): void; +} + +declare var AudioParam: { + prototype: AudioParam; + new(): AudioParam; +} + +interface AudioProcessingEvent extends Event { + inputBuffer: AudioBuffer; + outputBuffer: AudioBuffer; + playbackTime: number; +} + +declare var AudioProcessingEvent: { + prototype: AudioProcessingEvent; + new(): AudioProcessingEvent; +} + +interface AudioTrack { + enabled: boolean; + id: string; + kind: string; + label: string; + language: string; + sourceBuffer: SourceBuffer; +} + +declare var AudioTrack: { + prototype: AudioTrack; + new(): AudioTrack; +} + +interface AudioTrackList extends EventTarget { + length: number; + onaddtrack: (ev: TrackEvent) => any; + onchange: (ev: Event) => any; + onremovetrack: (ev: TrackEvent) => any; + getTrackById(id: string): AudioTrack; + item(index: number): AudioTrack; + addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "removetrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: AudioTrack; +} + +declare var AudioTrackList: { + prototype: AudioTrackList; + new(): AudioTrackList; +} + +interface BarProp { + visible: boolean; +} + +declare var BarProp: { + prototype: BarProp; + new(): BarProp; +} + +interface BeforeUnloadEvent extends Event { + returnValue: any; +} + +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new(): BeforeUnloadEvent; +} + +interface BiquadFilterNode extends AudioNode { + Q: AudioParam; + detune: AudioParam; + frequency: AudioParam; + gain: AudioParam; + type: string; + getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; +} + +declare var BiquadFilterNode: { + prototype: BiquadFilterNode; + new(): BiquadFilterNode; +} + +interface Blob { + size: number; + type: string; + msClose(): void; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +declare var Blob: { + prototype: Blob; + new (blobParts?: any[], options?: BlobPropertyBag): Blob; +} + +interface CDATASection extends Text { +} + +declare var CDATASection: { + prototype: CDATASection; + new(): CDATASection; +} + +interface CSS { + supports(property: string, value?: string): boolean; +} +declare var CSS: CSS; + +interface CSSConditionRule extends CSSGroupingRule { + conditionText: string; +} + +declare var CSSConditionRule: { + prototype: CSSConditionRule; + new(): CSSConditionRule; +} + +interface CSSFontFaceRule extends CSSRule { + style: CSSStyleDeclaration; +} + +declare var CSSFontFaceRule: { + prototype: CSSFontFaceRule; + new(): CSSFontFaceRule; +} + +interface CSSGroupingRule extends CSSRule { + cssRules: CSSRuleList; + deleteRule(index?: number): void; + insertRule(rule: string, index?: number): number; +} + +declare var CSSGroupingRule: { + prototype: CSSGroupingRule; + new(): CSSGroupingRule; +} + +interface CSSImportRule extends CSSRule { + href: string; + media: MediaList; + styleSheet: CSSStyleSheet; +} + +declare var CSSImportRule: { + prototype: CSSImportRule; + new(): CSSImportRule; +} + +interface CSSKeyframeRule extends CSSRule { + keyText: string; + style: CSSStyleDeclaration; +} + +declare var CSSKeyframeRule: { + prototype: CSSKeyframeRule; + new(): CSSKeyframeRule; +} + +interface CSSKeyframesRule extends CSSRule { + cssRules: CSSRuleList; + name: string; + appendRule(rule: string): void; + deleteRule(rule: string): void; + findRule(rule: string): CSSKeyframeRule; +} + +declare var CSSKeyframesRule: { + prototype: CSSKeyframesRule; + new(): CSSKeyframesRule; +} + +interface CSSMediaRule extends CSSConditionRule { + media: MediaList; +} + +declare var CSSMediaRule: { + prototype: CSSMediaRule; + new(): CSSMediaRule; +} + +interface CSSNamespaceRule extends CSSRule { + namespaceURI: string; + prefix: string; +} + +declare var CSSNamespaceRule: { + prototype: CSSNamespaceRule; + new(): CSSNamespaceRule; +} + +interface CSSPageRule extends CSSRule { + pseudoClass: string; + selector: string; + selectorText: string; + style: CSSStyleDeclaration; +} + +declare var CSSPageRule: { + prototype: CSSPageRule; + new(): CSSPageRule; +} + +interface CSSRule { + cssText: string; + parentRule: CSSRule; + parentStyleSheet: CSSStyleSheet; + type: number; + CHARSET_RULE: number; + FONT_FACE_RULE: number; + IMPORT_RULE: number; + KEYFRAMES_RULE: number; + KEYFRAME_RULE: number; + MEDIA_RULE: number; + NAMESPACE_RULE: number; + PAGE_RULE: number; + STYLE_RULE: number; + SUPPORTS_RULE: number; + UNKNOWN_RULE: number; + VIEWPORT_RULE: number; +} + +declare var CSSRule: { + prototype: CSSRule; + new(): CSSRule; + CHARSET_RULE: number; + FONT_FACE_RULE: number; + IMPORT_RULE: number; + KEYFRAMES_RULE: number; + KEYFRAME_RULE: number; + MEDIA_RULE: number; + NAMESPACE_RULE: number; + PAGE_RULE: number; + STYLE_RULE: number; + SUPPORTS_RULE: number; + UNKNOWN_RULE: number; + VIEWPORT_RULE: number; +} + +interface CSSRuleList { + length: number; + item(index: number): CSSRule; + [index: number]: CSSRule; +} + +declare var CSSRuleList: { + prototype: CSSRuleList; + new(): CSSRuleList; +} + +interface CSSStyleDeclaration { + alignContent: string; + alignItems: string; + alignSelf: string; + alignmentBaseline: string; + animation: string; + animationDelay: string; + animationDirection: string; + animationDuration: string; + animationFillMode: string; + animationIterationCount: string; + animationName: string; + animationPlayState: string; + animationTimingFunction: string; + backfaceVisibility: string; + background: string; + backgroundAttachment: string; + backgroundClip: string; + backgroundColor: string; + backgroundImage: string; + backgroundOrigin: string; + backgroundPosition: string; + backgroundPositionX: string; + backgroundPositionY: string; + backgroundRepeat: string; + backgroundSize: string; + baselineShift: string; + border: string; + borderBottom: string; + borderBottomColor: string; + borderBottomLeftRadius: string; + borderBottomRightRadius: string; + borderBottomStyle: string; + borderBottomWidth: string; + borderCollapse: string; + borderColor: string; + borderImage: string; + borderImageOutset: string; + borderImageRepeat: string; + borderImageSlice: string; + borderImageSource: string; + borderImageWidth: string; + borderLeft: string; + borderLeftColor: string; + borderLeftStyle: string; + borderLeftWidth: string; + borderRadius: string; + borderRight: string; + borderRightColor: string; + borderRightStyle: string; + borderRightWidth: string; + borderSpacing: string; + borderStyle: string; + borderTop: string; + borderTopColor: string; + borderTopLeftRadius: string; + borderTopRightRadius: string; + borderTopStyle: string; + borderTopWidth: string; + borderWidth: string; + bottom: string; + boxShadow: string; + boxSizing: string; + breakAfter: string; + breakBefore: string; + breakInside: string; + captionSide: string; + clear: string; + clip: string; + clipPath: string; + clipRule: string; + color: string; + colorInterpolationFilters: string; + columnCount: any; + columnFill: string; + columnGap: any; + columnRule: string; + columnRuleColor: any; + columnRuleStyle: string; + columnRuleWidth: any; + columnSpan: string; + columnWidth: any; + columns: string; + content: string; + counterIncrement: string; + counterReset: string; + cssFloat: string; + cssText: string; + cursor: string; + direction: string; + display: string; + dominantBaseline: string; + emptyCells: string; + enableBackground: string; + fill: string; + fillOpacity: string; + fillRule: string; + filter: string; + flex: string; + flexBasis: string; + flexDirection: string; + flexFlow: string; + flexGrow: string; + flexShrink: string; + flexWrap: string; + floodColor: string; + floodOpacity: string; + font: string; + fontFamily: string; + fontFeatureSettings: string; + fontSize: string; + fontSizeAdjust: string; + fontStretch: string; + fontStyle: string; + fontVariant: string; + fontWeight: string; + glyphOrientationHorizontal: string; + glyphOrientationVertical: string; + height: string; + imeMode: string; + justifyContent: string; + kerning: string; + left: string; + length: number; + letterSpacing: string; + lightingColor: string; + lineHeight: string; + listStyle: string; + listStyleImage: string; + listStylePosition: string; + listStyleType: string; + margin: string; + marginBottom: string; + marginLeft: string; + marginRight: string; + marginTop: string; + marker: string; + markerEnd: string; + markerMid: string; + markerStart: string; + mask: string; + maxHeight: string; + maxWidth: string; + minHeight: string; + minWidth: string; + msContentZoomChaining: string; + msContentZoomLimit: string; + msContentZoomLimitMax: any; + msContentZoomLimitMin: any; + msContentZoomSnap: string; + msContentZoomSnapPoints: string; + msContentZoomSnapType: string; + msContentZooming: string; + msFlowFrom: string; + msFlowInto: string; + msFontFeatureSettings: string; + msGridColumn: any; + msGridColumnAlign: string; + msGridColumnSpan: any; + msGridColumns: string; + msGridRow: any; + msGridRowAlign: string; + msGridRowSpan: any; + msGridRows: string; + msHighContrastAdjust: string; + msHyphenateLimitChars: string; + msHyphenateLimitLines: any; + msHyphenateLimitZone: any; + msHyphens: string; + msImeAlign: string; + msOverflowStyle: string; + msScrollChaining: string; + msScrollLimit: string; + msScrollLimitXMax: any; + msScrollLimitXMin: any; + msScrollLimitYMax: any; + msScrollLimitYMin: any; + msScrollRails: string; + msScrollSnapPointsX: string; + msScrollSnapPointsY: string; + msScrollSnapType: string; + msScrollSnapX: string; + msScrollSnapY: string; + msScrollTranslation: string; + msTextCombineHorizontal: string; + msTextSizeAdjust: any; + msTouchAction: string; + msTouchSelect: string; + msUserSelect: string; + msWrapFlow: string; + msWrapMargin: any; + msWrapThrough: string; + opacity: string; + order: string; + orphans: string; + outline: string; + outlineColor: string; + outlineStyle: string; + outlineWidth: string; + overflow: string; + overflowX: string; + overflowY: string; + padding: string; + paddingBottom: string; + paddingLeft: string; + paddingRight: string; + paddingTop: string; + pageBreakAfter: string; + pageBreakBefore: string; + pageBreakInside: string; + parentRule: CSSRule; + perspective: string; + perspectiveOrigin: string; + pointerEvents: string; + position: string; + quotes: string; + right: string; + rubyAlign: string; + rubyOverhang: string; + rubyPosition: string; + stopColor: string; + stopOpacity: string; + stroke: string; + strokeDasharray: string; + strokeDashoffset: string; + strokeLinecap: string; + strokeLinejoin: string; + strokeMiterlimit: string; + strokeOpacity: string; + strokeWidth: string; + tableLayout: string; + textAlign: string; + textAlignLast: string; + textAnchor: string; + textDecoration: string; + textFillColor: string; + textIndent: string; + textJustify: string; + textKashida: string; + textKashidaSpace: string; + textOverflow: string; + textShadow: string; + textTransform: string; + textUnderlinePosition: string; + top: string; + touchAction: string; + transform: string; + transformOrigin: string; + transformStyle: string; + transition: string; + transitionDelay: string; + transitionDuration: string; + transitionProperty: string; + transitionTimingFunction: string; + unicodeBidi: string; + verticalAlign: string; + visibility: string; + webkitAlignContent: string; + webkitAlignItems: string; + webkitAlignSelf: string; + webkitAnimation: string; + webkitAnimationDelay: string; + webkitAnimationDirection: string; + webkitAnimationDuration: string; + webkitAnimationFillMode: string; + webkitAnimationIterationCount: string; + webkitAnimationName: string; + webkitAnimationPlayState: string; + webkitAnimationTimingFunction: string; + webkitAppearance: string; + webkitBackfaceVisibility: string; + webkitBackground: string; + webkitBackgroundAttachment: string; + webkitBackgroundClip: string; + webkitBackgroundColor: string; + webkitBackgroundImage: string; + webkitBackgroundOrigin: string; + webkitBackgroundPosition: string; + webkitBackgroundPositionX: string; + webkitBackgroundPositionY: string; + webkitBackgroundRepeat: string; + webkitBackgroundSize: string; + webkitBorderBottomLeftRadius: string; + webkitBorderBottomRightRadius: string; + webkitBorderImage: string; + webkitBorderImageOutset: string; + webkitBorderImageRepeat: string; + webkitBorderImageSlice: string; + webkitBorderImageSource: string; + webkitBorderImageWidth: string; + webkitBorderRadius: string; + webkitBorderTopLeftRadius: string; + webkitBorderTopRightRadius: string; + webkitBoxAlign: string; + webkitBoxDirection: string; + webkitBoxFlex: string; + webkitBoxOrdinalGroup: string; + webkitBoxOrient: string; + webkitBoxPack: string; + webkitBoxSizing: string; + webkitColumnBreakAfter: string; + webkitColumnBreakBefore: string; + webkitColumnBreakInside: string; + webkitColumnCount: any; + webkitColumnGap: any; + webkitColumnRule: string; + webkitColumnRuleColor: any; + webkitColumnRuleStyle: string; + webkitColumnRuleWidth: any; + webkitColumnSpan: string; + webkitColumnWidth: any; + webkitColumns: string; + webkitFilter: string; + webkitFlex: string; + webkitFlexBasis: string; + webkitFlexDirection: string; + webkitFlexFlow: string; + webkitFlexGrow: string; + webkitFlexShrink: string; + webkitFlexWrap: string; + webkitJustifyContent: string; + webkitOrder: string; + webkitPerspective: string; + webkitPerspectiveOrigin: string; + webkitTapHighlightColor: string; + webkitTextFillColor: string; + webkitTextSizeAdjust: any; + webkitTransform: string; + webkitTransformOrigin: string; + webkitTransformStyle: string; + webkitTransition: string; + webkitTransitionDelay: string; + webkitTransitionDuration: string; + webkitTransitionProperty: string; + webkitTransitionTimingFunction: string; + webkitUserSelect: string; + webkitWritingMode: string; + whiteSpace: string; + widows: string; + width: string; + wordBreak: string; + wordSpacing: string; + wordWrap: string; + writingMode: string; + zIndex: string; + zoom: string; + getPropertyPriority(propertyName: string): string; + getPropertyValue(propertyName: string): string; + item(index: number): string; + removeProperty(propertyName: string): string; + setProperty(propertyName: string, value: string, priority?: string): void; + [index: number]: string; +} + +declare var CSSStyleDeclaration: { + prototype: CSSStyleDeclaration; + new(): CSSStyleDeclaration; +} + +interface CSSStyleRule extends CSSRule { + readOnly: boolean; + selectorText: string; + style: CSSStyleDeclaration; +} + +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new(): CSSStyleRule; +} + +interface CSSStyleSheet extends StyleSheet { + cssRules: CSSRuleList; + cssText: string; + href: string; + id: string; + imports: StyleSheetList; + isAlternate: boolean; + isPrefAlternate: boolean; + ownerRule: CSSRule; + owningElement: Element; + pages: StyleSheetPageList; + readOnly: boolean; + rules: CSSRuleList; + addImport(bstrURL: string, lIndex?: number): number; + addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; + addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; + deleteRule(index?: number): void; + insertRule(rule: string, index?: number): number; + removeImport(lIndex: number): void; + removeRule(lIndex: number): void; +} + +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new(): CSSStyleSheet; +} + +interface CSSSupportsRule extends CSSConditionRule { +} + +declare var CSSSupportsRule: { + prototype: CSSSupportsRule; + new(): CSSSupportsRule; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} + +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +} + +interface CanvasPattern { +} + +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +} + +interface CanvasRenderingContext2D { + canvas: HTMLCanvasElement; + fillStyle: string | CanvasGradient | CanvasPattern; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + lineCap: string; + lineDashOffset: number; + lineJoin: string; + lineWidth: number; + miterLimit: number; + msFillRule: string; + msImageSmoothingEnabled: boolean; + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; + strokeStyle: string | CanvasGradient | CanvasPattern; + textAlign: string; + textBaseline: string; + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + beginPath(): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + clearRect(x: number, y: number, w: number, h: number): void; + clip(fillRule?: string): void; + closePath(): void; + createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; + fill(fillRule?: string): void; + fillRect(x: number, y: number, w: number, h: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + getLineDash(): number[]; + isPointInPath(x: number, y: number, fillRule?: string): boolean; + lineTo(x: number, y: number): void; + measureText(text: string): TextMetrics; + moveTo(x: number, y: number): void; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + rect(x: number, y: number, w: number, h: number): void; + restore(): void; + rotate(angle: number): void; + save(): void; + scale(x: number, y: number): void; + setLineDash(segments: number[]): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + translate(x: number, y: number): void; +} + +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +} + +interface ChannelMergerNode extends AudioNode { +} + +declare var ChannelMergerNode: { + prototype: ChannelMergerNode; + new(): ChannelMergerNode; +} + +interface ChannelSplitterNode extends AudioNode { +} + +declare var ChannelSplitterNode: { + prototype: ChannelSplitterNode; + new(): ChannelSplitterNode; +} + +interface CharacterData extends Node, ChildNode { + data: string; + length: number; + appendData(arg: string): void; + deleteData(offset: number, count: number): void; + insertData(offset: number, arg: string): void; + replaceData(offset: number, count: number, arg: string): void; + substringData(offset: number, count: number): string; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +} + +interface ClientRect { + bottom: number; + height: number; + left: number; + right: number; + top: number; + width: number; +} + +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +} + +interface ClientRectList { + length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} + +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +} + +interface ClipboardEvent extends Event { + clipboardData: DataTransfer; +} + +declare var ClipboardEvent: { + prototype: ClipboardEvent; + new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent; +} + +interface CloseEvent extends Event { + code: number; + reason: string; + wasClean: boolean; + initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void; +} + +declare var CloseEvent: { + prototype: CloseEvent; + new(): CloseEvent; +} + +interface CommandEvent extends Event { + commandName: string; + detail: string; +} + +declare var CommandEvent: { + prototype: CommandEvent; + new(type: string, eventInitDict?: CommandEventInit): CommandEvent; +} + +interface Comment extends CharacterData { + text: string; +} + +declare var Comment: { + prototype: Comment; + new(): Comment; +} + +interface CompositionEvent extends UIEvent { + data: string; + locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void; +} + +declare var CompositionEvent: { + prototype: CompositionEvent; + new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent; +} + +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + clear(): void; + count(countTitle?: string): void; + debug(message?: string, ...optionalParams: any[]): void; + dir(value?: any, ...optionalParams: any[]): void; + dirxml(value: any): void; + error(message?: any, ...optionalParams: any[]): void; + group(groupTitle?: string): void; + groupCollapsed(groupTitle?: string): void; + groupEnd(): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): boolean; + profile(reportName?: string): void; + profileEnd(): void; + select(element: Element): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +declare var Console: { + prototype: Console; + new(): Console; +} + +interface ConvolverNode extends AudioNode { + buffer: AudioBuffer; + normalize: boolean; +} + +declare var ConvolverNode: { + prototype: ConvolverNode; + new(): ConvolverNode; +} + +interface Coordinates { + accuracy: number; + altitude: number; + altitudeAccuracy: number; + heading: number; + latitude: number; + longitude: number; + speed: number; +} + +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +} + +interface Crypto extends Object, RandomSource { + subtle: SubtleCrypto; +} + +declare var Crypto: { + prototype: Crypto; + new(): Crypto; +} + +interface CryptoKey { + algorithm: KeyAlgorithm; + extractable: boolean; + type: string; + usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +} + +interface CryptoKeyPair { + privateKey: CryptoKey; + publicKey: CryptoKey; +} + +declare var CryptoKeyPair: { + prototype: CryptoKeyPair; + new(): CryptoKeyPair; +} + +interface CustomEvent extends Event { + detail: any; + initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: any): void; +} + +declare var CustomEvent: { + prototype: CustomEvent; + new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent; +} + +interface DOMError { + name: string; + toString(): string; +} + +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +} + +interface DOMException { + code: number; + message: string; + name: string; + toString(): string; + ABORT_ERR: number; + DATA_CLONE_ERR: number; + DOMSTRING_SIZE_ERR: number; + HIERARCHY_REQUEST_ERR: number; + INDEX_SIZE_ERR: number; + INUSE_ATTRIBUTE_ERR: number; + INVALID_ACCESS_ERR: number; + INVALID_CHARACTER_ERR: number; + INVALID_MODIFICATION_ERR: number; + INVALID_NODE_TYPE_ERR: number; + INVALID_STATE_ERR: number; + NAMESPACE_ERR: number; + NETWORK_ERR: number; + NOT_FOUND_ERR: number; + NOT_SUPPORTED_ERR: number; + NO_DATA_ALLOWED_ERR: number; + NO_MODIFICATION_ALLOWED_ERR: number; + PARSE_ERR: number; + QUOTA_EXCEEDED_ERR: number; + SECURITY_ERR: number; + SERIALIZE_ERR: number; + SYNTAX_ERR: number; + TIMEOUT_ERR: number; + TYPE_MISMATCH_ERR: number; + URL_MISMATCH_ERR: number; + VALIDATION_ERR: number; + WRONG_DOCUMENT_ERR: number; +} + +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + ABORT_ERR: number; + DATA_CLONE_ERR: number; + DOMSTRING_SIZE_ERR: number; + HIERARCHY_REQUEST_ERR: number; + INDEX_SIZE_ERR: number; + INUSE_ATTRIBUTE_ERR: number; + INVALID_ACCESS_ERR: number; + INVALID_CHARACTER_ERR: number; + INVALID_MODIFICATION_ERR: number; + INVALID_NODE_TYPE_ERR: number; + INVALID_STATE_ERR: number; + NAMESPACE_ERR: number; + NETWORK_ERR: number; + NOT_FOUND_ERR: number; + NOT_SUPPORTED_ERR: number; + NO_DATA_ALLOWED_ERR: number; + NO_MODIFICATION_ALLOWED_ERR: number; + PARSE_ERR: number; + QUOTA_EXCEEDED_ERR: number; + SECURITY_ERR: number; + SERIALIZE_ERR: number; + SYNTAX_ERR: number; + TIMEOUT_ERR: number; + TYPE_MISMATCH_ERR: number; + URL_MISMATCH_ERR: number; + VALIDATION_ERR: number; + WRONG_DOCUMENT_ERR: number; +} + +interface DOMImplementation { + createDocument(namespaceURI: string, qualifiedName: string, doctype: DocumentType): Document; + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createHTMLDocument(title: string): Document; + hasFeature(feature: string, version: string): boolean; +} + +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} + +declare var DOMParser: { + prototype: DOMParser; + new(): DOMParser; +} + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} + +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +} + +interface DOMStringList { + length: number; + contains(str: string): boolean; + item(index: number): string; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +} + +interface DOMStringMap { + [name: string]: string; +} + +declare var DOMStringMap: { + prototype: DOMStringMap; + new(): DOMStringMap; +} + +interface DOMTokenList { + length: number; + add(...token: string[]): void; + contains(token: string): boolean; + item(index: number): string; + remove(...token: string[]): void; + toString(): string; + toggle(token: string, force?: boolean): boolean; + [index: number]: string; +} + +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +} + +interface DataCue extends TextTrackCue { + data: ArrayBuffer; +} + +declare var DataCue: { + prototype: DataCue; + new(): DataCue; +} + +interface DataTransfer { + dropEffect: string; + effectAllowed: string; + files: FileList; + items: DataTransferItemList; + types: DOMStringList; + clearData(format?: string): boolean; + getData(format: string): string; + setData(format: string, data: string): boolean; +} + +declare var DataTransfer: { + prototype: DataTransfer; + new(): DataTransfer; +} + +interface DataTransferItem { + kind: string; + type: string; + getAsFile(): File; + getAsString(_callback: FunctionStringCallback): void; +} + +declare var DataTransferItem: { + prototype: DataTransferItem; + new(): DataTransferItem; +} + +interface DataTransferItemList { + length: number; + add(data: File): DataTransferItem; + clear(): void; + item(index: number): DataTransferItem; + remove(index: number): void; + [index: number]: DataTransferItem; +} + +declare var DataTransferItemList: { + prototype: DataTransferItemList; + new(): DataTransferItemList; +} + +interface DeferredPermissionRequest { + id: number; + type: string; + uri: string; + allow(): void; + deny(): void; +} + +declare var DeferredPermissionRequest: { + prototype: DeferredPermissionRequest; + new(): DeferredPermissionRequest; +} + +interface DelayNode extends AudioNode { + delayTime: AudioParam; +} + +declare var DelayNode: { + prototype: DelayNode; + new(): DelayNode; +} + +interface DeviceAcceleration { + x: number; + y: number; + z: number; +} + +declare var DeviceAcceleration: { + prototype: DeviceAcceleration; + new(): DeviceAcceleration; +} + +interface DeviceMotionEvent extends Event { + acceleration: DeviceAcceleration; + accelerationIncludingGravity: DeviceAcceleration; + interval: number; + rotationRate: DeviceRotationRate; + initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict, accelerationIncludingGravity: DeviceAccelerationDict, rotationRate: DeviceRotationRateDict, interval: number): void; +} + +declare var DeviceMotionEvent: { + prototype: DeviceMotionEvent; + new(): DeviceMotionEvent; +} + +interface DeviceOrientationEvent extends Event { + absolute: boolean; + alpha: number; + beta: number; + gamma: number; + initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number, beta: number, gamma: number, absolute: boolean): void; +} + +declare var DeviceOrientationEvent: { + prototype: DeviceOrientationEvent; + new(): DeviceOrientationEvent; +} + +interface DeviceRotationRate { + alpha: number; + beta: number; + gamma: number; +} + +declare var DeviceRotationRate: { + prototype: DeviceRotationRate; + new(): DeviceRotationRate; +} + +interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { + /** + * Sets or gets the URL for the current document. + */ + URL: string; + /** + * Gets the URL for the document, stripped of any character encoding. + */ + URLUnencoded: string; + /** + * Gets the object that has the focus when the parent document has focus. + */ + activeElement: Element; + /** + * Sets or gets the color of all active links in the document. + */ + alinkColor: string; + /** + * Returns a reference to the collection of elements contained by the object. + */ + all: HTMLCollection; + /** + * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order. + */ + anchors: HTMLCollection; + /** + * Retrieves a collection of all applet objects in the document. + */ + applets: HTMLCollection; + /** + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + */ + bgColor: string; + /** + * Specifies the beginning and end of the document body. + */ + body: HTMLElement; + characterSet: string; + /** + * Gets or sets the character set used to encode the object. + */ + charset: string; + /** + * Gets a value that indicates whether standards-compliant mode is switched on for the object. + */ + compatMode: string; + cookie: string; + /** + * Gets the default character set from the current regional language settings. + */ + defaultCharset: string; + defaultView: Window; + /** + * Sets or gets a value that indicates whether the document can be edited. + */ + designMode: string; + /** + * Sets or retrieves a value that indicates the reading order of the object. + */ + dir: string; + /** + * Gets an object representing the document type declaration associated with the current document. + */ + doctype: DocumentType; + /** + * Gets a reference to the root node of the document. + */ + documentElement: HTMLElement; + /** + * Sets or gets the security domain of the document. + */ + domain: string; + /** + * Retrieves a collection of all embed objects in the document. + */ + embeds: HTMLCollection; + /** + * Sets or gets the foreground (text) color of the document. + */ + fgColor: string; + /** + * Retrieves a collection, in source order, of all form objects in the document. + */ + forms: HTMLCollection; + fullscreenElement: Element; + fullscreenEnabled: boolean; + head: HTMLHeadElement; + hidden: boolean; + /** + * Retrieves a collection, in source order, of img objects in the document. + */ + images: HTMLCollection; + /** + * Gets the implementation object of the current document. + */ + implementation: DOMImplementation; + /** + * Returns the character encoding used to create the webpage that is loaded into the document object. + */ + inputEncoding: string; + /** + * Gets the date that the page was last modified, if the page supplies one. + */ + lastModified: string; + /** + * Sets or gets the color of the document links. + */ + linkColor: string; + /** + * Retrieves a collection of all a objects that specify the href property and all area objects in the document. + */ + links: HTMLCollection; + /** + * Contains information about the current URL. + */ + location: Location; + media: string; + msCSSOMElementFloatMetrics: boolean; + msCapsLockWarningOff: boolean; + msHidden: boolean; + msVisibilityState: string; + /** + * Fires when the user aborts the download. + * @param ev The event. + */ + onabort: (ev: Event) => any; + /** + * Fires when the object is set as the active element. + * @param ev The event. + */ + onactivate: (ev: UIEvent) => any; + /** + * Fires immediately before the object is set as the active element. + * @param ev The event. + */ + onbeforeactivate: (ev: UIEvent) => any; + /** + * Fires immediately before the activeElement is changed from the current object to another object in the parent document. + * @param ev The event. + */ + onbeforedeactivate: (ev: UIEvent) => any; + /** + * Fires when the object loses the input focus. + * @param ev The focus event. + */ + onblur: (ev: FocusEvent) => any; + /** + * Occurs when playback is possible, but would require further buffering. + * @param ev The event. + */ + oncanplay: (ev: Event) => any; + oncanplaythrough: (ev: Event) => any; + /** + * Fires when the contents of the object or selection have changed. + * @param ev The event. + */ + onchange: (ev: Event) => any; + /** + * Fires when the user clicks the left mouse button on the object + * @param ev The mouse event. + */ + onclick: (ev: MouseEvent) => any; + /** + * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * @param ev The mouse event. + */ + oncontextmenu: (ev: PointerEvent) => any; + /** + * Fires when the user double-clicks the object. + * @param ev The mouse event. + */ + ondblclick: (ev: MouseEvent) => any; + /** + * Fires when the activeElement is changed from the current object to another object in the parent document. + * @param ev The UI Event + */ + ondeactivate: (ev: UIEvent) => any; + /** + * Fires on the source object continuously during a drag operation. + * @param ev The event. + */ + ondrag: (ev: DragEvent) => any; + /** + * Fires on the source object when the user releases the mouse at the close of a drag operation. + * @param ev The event. + */ + ondragend: (ev: DragEvent) => any; + /** + * Fires on the target element when the user drags the object to a valid drop target. + * @param ev The drag event. + */ + ondragenter: (ev: DragEvent) => any; + /** + * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. + * @param ev The drag event. + */ + ondragleave: (ev: DragEvent) => any; + /** + * Fires on the target element continuously while the user drags the object over a valid drop target. + * @param ev The event. + */ + ondragover: (ev: DragEvent) => any; + /** + * Fires on the source object when the user starts to drag a text selection or selected object. + * @param ev The event. + */ + ondragstart: (ev: DragEvent) => any; + ondrop: (ev: DragEvent) => any; + /** + * Occurs when the duration attribute is updated. + * @param ev The event. + */ + ondurationchange: (ev: Event) => any; + /** + * Occurs when the media element is reset to its initial state. + * @param ev The event. + */ + onemptied: (ev: Event) => any; + /** + * Occurs when the end of playback is reached. + * @param ev The event + */ + onended: (ev: Event) => any; + /** + * Fires when an error occurs during object loading. + * @param ev The event. + */ + onerror: (ev: Event) => any; + /** + * Fires when the object receives focus. + * @param ev The event. + */ + onfocus: (ev: FocusEvent) => any; + onfullscreenchange: (ev: Event) => any; + onfullscreenerror: (ev: Event) => any; + oninput: (ev: Event) => any; + /** + * Fires when the user presses a key. + * @param ev The keyboard event + */ + onkeydown: (ev: KeyboardEvent) => any; + /** + * Fires when the user presses an alphanumeric key. + * @param ev The event. + */ + onkeypress: (ev: KeyboardEvent) => any; + /** + * Fires when the user releases a key. + * @param ev The keyboard event + */ + onkeyup: (ev: KeyboardEvent) => any; + /** + * Fires immediately after the browser loads the object. + * @param ev The event. + */ + onload: (ev: Event) => any; + /** + * Occurs when media data is loaded at the current playback position. + * @param ev The event. + */ + onloadeddata: (ev: Event) => any; + /** + * Occurs when the duration and dimensions of the media have been determined. + * @param ev The event. + */ + onloadedmetadata: (ev: Event) => any; + /** + * Occurs when Internet Explorer begins looking for media data. + * @param ev The event. + */ + onloadstart: (ev: Event) => any; + /** + * Fires when the user clicks the object with either mouse button. + * @param ev The mouse event. + */ + onmousedown: (ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse over the object. + * @param ev The mouse event. + */ + onmousemove: (ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse pointer outside the boundaries of the object. + * @param ev The mouse event. + */ + onmouseout: (ev: MouseEvent) => any; + /** + * Fires when the user moves the mouse pointer into the object. + * @param ev The mouse event. + */ + onmouseover: (ev: MouseEvent) => any; + /** + * Fires when the user releases a mouse button while the mouse is over the object. + * @param ev The mouse event. + */ + onmouseup: (ev: MouseEvent) => any; + /** + * Fires when the wheel button is rotated. + * @param ev The mouse event + */ + onmousewheel: (ev: MouseWheelEvent) => any; + onmscontentzoom: (ev: UIEvent) => any; + onmsgesturechange: (ev: MSGestureEvent) => any; + onmsgesturedoubletap: (ev: MSGestureEvent) => any; + onmsgestureend: (ev: MSGestureEvent) => any; + onmsgesturehold: (ev: MSGestureEvent) => any; + onmsgesturestart: (ev: MSGestureEvent) => any; + onmsgesturetap: (ev: MSGestureEvent) => any; + onmsinertiastart: (ev: MSGestureEvent) => any; + onmsmanipulationstatechanged: (ev: MSManipulationEvent) => any; + onmspointercancel: (ev: MSPointerEvent) => any; + onmspointerdown: (ev: MSPointerEvent) => any; + onmspointerenter: (ev: MSPointerEvent) => any; + onmspointerleave: (ev: MSPointerEvent) => any; + onmspointermove: (ev: MSPointerEvent) => any; + onmspointerout: (ev: MSPointerEvent) => any; + onmspointerover: (ev: MSPointerEvent) => any; + onmspointerup: (ev: MSPointerEvent) => any; + /** + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * @param ev The event. + */ + onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; + /** + * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode. + * @param ev The event. + */ + onmsthumbnailclick: (ev: MSSiteModeEvent) => any; + /** + * Occurs when playback is paused. + * @param ev The event. + */ + onpause: (ev: Event) => any; + /** + * Occurs when the play method is requested. + * @param ev The event. + */ + onplay: (ev: Event) => any; + /** + * Occurs when the audio or video has started playing. + * @param ev The event. + */ + onplaying: (ev: Event) => any; + onpointerlockchange: (ev: Event) => any; + onpointerlockerror: (ev: Event) => any; + /** + * Occurs to indicate progress while downloading media data. + * @param ev The event. + */ + onprogress: (ev: ProgressEvent) => any; + /** + * Occurs when the playback rate is increased or decreased. + * @param ev The event. + */ + onratechange: (ev: Event) => any; + /** + * Fires when the state of the object has changed. + * @param ev The event + */ + onreadystatechange: (ev: ProgressEvent) => any; + /** + * Fires when the user resets a form. + * @param ev The event. + */ + onreset: (ev: Event) => any; + /** + * Fires when the user repositions the scroll box in the scroll bar on the object. + * @param ev The event. + */ + onscroll: (ev: UIEvent) => any; + /** + * Occurs when the seek operation ends. + * @param ev The event. + */ + onseeked: (ev: Event) => any; + /** + * Occurs when the current playback position is moved. + * @param ev The event. + */ + onseeking: (ev: Event) => any; + /** + * Fires when the current selection changes. + * @param ev The event. + */ + onselect: (ev: UIEvent) => any; + onselectstart: (ev: Event) => any; + /** + * Occurs when the download has stopped. + * @param ev The event. + */ + onstalled: (ev: Event) => any; + /** + * Fires when the user clicks the Stop button or leaves the Web page. + * @param ev The event. + */ + onstop: (ev: Event) => any; + onsubmit: (ev: Event) => any; + /** + * Occurs if the load operation has been intentionally halted. + * @param ev The event. + */ + onsuspend: (ev: Event) => any; + /** + * Occurs to indicate the current playback position. + * @param ev The event. + */ + ontimeupdate: (ev: Event) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + /** + * Occurs when the volume is changed, or playback is muted or unmuted. + * @param ev The event. + */ + onvolumechange: (ev: Event) => any; + /** + * Occurs when playback stops because the next frame of a video resource is not available. + * @param ev The event. + */ + onwaiting: (ev: Event) => any; + onwebkitfullscreenchange: (ev: Event) => any; + onwebkitfullscreenerror: (ev: Event) => any; + plugins: HTMLCollection; + pointerLockElement: Element; + /** + * Retrieves a value that indicates the current state of the object. + */ + readyState: string; + /** + * Gets the URL of the location that referred the user to the current page. + */ + referrer: string; + /** + * Gets the root svg element in the document hierarchy. + */ + rootElement: SVGSVGElement; + /** + * Retrieves a collection of all script objects in the document. + */ + scripts: HTMLCollection; + security: string; + /** + * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document. + */ + styleSheets: StyleSheetList; + /** + * Contains the title of the document. + */ + title: string; + visibilityState: string; + /** + * Sets or gets the color of the links that the user has visited. + */ + vlinkColor: string; + webkitCurrentFullScreenElement: Element; + webkitFullscreenElement: Element; + webkitFullscreenEnabled: boolean; + webkitIsFullScreen: boolean; + xmlEncoding: string; + xmlStandalone: boolean; + /** + * Gets or sets the version attribute specified in the declaration of an XML document. + */ + xmlVersion: string; + currentScript: HTMLScriptElement; + adoptNode(source: Node): Node; + captureEvents(): void; + clear(): void; + /** + * Closes an output stream and forces the sent data to display. + */ + close(): void; + /** + * Creates an attribute object with a specified name. + * @param name String that sets the attribute object's name. + */ + createAttribute(name: string): Attr; + createAttributeNS(namespaceURI: string, qualifiedName: string): Attr; + createCDATASection(data: string): CDATASection; + /** + * Creates a comment object with the specified data. + * @param data Sets the comment object's data. + */ + createComment(data: string): Comment; + /** + * Creates a new document. + */ + createDocumentFragment(): DocumentFragment; + /** + * Creates an instance of the element for the specified tag. + * @param tagName The name of an element. + */ + createElement(tagName: "a"): HTMLAnchorElement; + createElement(tagName: "abbr"): HTMLPhraseElement; + createElement(tagName: "acronym"): HTMLPhraseElement; + createElement(tagName: "address"): HTMLBlockElement; + createElement(tagName: "applet"): HTMLAppletElement; + createElement(tagName: "area"): HTMLAreaElement; + createElement(tagName: "audio"): HTMLAudioElement; + createElement(tagName: "b"): HTMLPhraseElement; + createElement(tagName: "base"): HTMLBaseElement; + createElement(tagName: "basefont"): HTMLBaseFontElement; + createElement(tagName: "bdo"): HTMLPhraseElement; + createElement(tagName: "big"): HTMLPhraseElement; + createElement(tagName: "blockquote"): HTMLBlockElement; + createElement(tagName: "body"): HTMLBodyElement; + createElement(tagName: "br"): HTMLBRElement; + createElement(tagName: "button"): HTMLButtonElement; + createElement(tagName: "canvas"): HTMLCanvasElement; + createElement(tagName: "caption"): HTMLTableCaptionElement; + createElement(tagName: "center"): HTMLBlockElement; + createElement(tagName: "cite"): HTMLPhraseElement; + createElement(tagName: "code"): HTMLPhraseElement; + createElement(tagName: "col"): HTMLTableColElement; + createElement(tagName: "colgroup"): HTMLTableColElement; + createElement(tagName: "datalist"): HTMLDataListElement; + createElement(tagName: "dd"): HTMLDDElement; + createElement(tagName: "del"): HTMLModElement; + createElement(tagName: "dfn"): HTMLPhraseElement; + createElement(tagName: "dir"): HTMLDirectoryElement; + createElement(tagName: "div"): HTMLDivElement; + createElement(tagName: "dl"): HTMLDListElement; + createElement(tagName: "dt"): HTMLDTElement; + createElement(tagName: "em"): HTMLPhraseElement; + createElement(tagName: "embed"): HTMLEmbedElement; + createElement(tagName: "fieldset"): HTMLFieldSetElement; + createElement(tagName: "font"): HTMLFontElement; + createElement(tagName: "form"): HTMLFormElement; + createElement(tagName: "frame"): HTMLFrameElement; + createElement(tagName: "frameset"): HTMLFrameSetElement; + createElement(tagName: "h1"): HTMLHeadingElement; + createElement(tagName: "h2"): HTMLHeadingElement; + createElement(tagName: "h3"): HTMLHeadingElement; + createElement(tagName: "h4"): HTMLHeadingElement; + createElement(tagName: "h5"): HTMLHeadingElement; + createElement(tagName: "h6"): HTMLHeadingElement; + createElement(tagName: "head"): HTMLHeadElement; + createElement(tagName: "hr"): HTMLHRElement; + createElement(tagName: "html"): HTMLHtmlElement; + createElement(tagName: "i"): HTMLPhraseElement; + createElement(tagName: "iframe"): HTMLIFrameElement; + createElement(tagName: "img"): HTMLImageElement; + createElement(tagName: "input"): HTMLInputElement; + createElement(tagName: "ins"): HTMLModElement; + createElement(tagName: "isindex"): HTMLIsIndexElement; + createElement(tagName: "kbd"): HTMLPhraseElement; + createElement(tagName: "keygen"): HTMLBlockElement; + createElement(tagName: "label"): HTMLLabelElement; + createElement(tagName: "legend"): HTMLLegendElement; + createElement(tagName: "li"): HTMLLIElement; + createElement(tagName: "link"): HTMLLinkElement; + createElement(tagName: "listing"): HTMLBlockElement; + createElement(tagName: "map"): HTMLMapElement; + createElement(tagName: "marquee"): HTMLMarqueeElement; + createElement(tagName: "menu"): HTMLMenuElement; + createElement(tagName: "meta"): HTMLMetaElement; + createElement(tagName: "nextid"): HTMLNextIdElement; + createElement(tagName: "nobr"): HTMLPhraseElement; + createElement(tagName: "object"): HTMLObjectElement; + createElement(tagName: "ol"): HTMLOListElement; + createElement(tagName: "optgroup"): HTMLOptGroupElement; + createElement(tagName: "option"): HTMLOptionElement; + createElement(tagName: "p"): HTMLParagraphElement; + createElement(tagName: "param"): HTMLParamElement; + createElement(tagName: "plaintext"): HTMLBlockElement; + createElement(tagName: "pre"): HTMLPreElement; + createElement(tagName: "progress"): HTMLProgressElement; + createElement(tagName: "q"): HTMLQuoteElement; + createElement(tagName: "rt"): HTMLPhraseElement; + createElement(tagName: "ruby"): HTMLPhraseElement; + createElement(tagName: "s"): HTMLPhraseElement; + createElement(tagName: "samp"): HTMLPhraseElement; + createElement(tagName: "script"): HTMLScriptElement; + createElement(tagName: "select"): HTMLSelectElement; + createElement(tagName: "small"): HTMLPhraseElement; + createElement(tagName: "source"): HTMLSourceElement; + createElement(tagName: "span"): HTMLSpanElement; + createElement(tagName: "strike"): HTMLPhraseElement; + createElement(tagName: "strong"): HTMLPhraseElement; + createElement(tagName: "style"): HTMLStyleElement; + createElement(tagName: "sub"): HTMLPhraseElement; + createElement(tagName: "sup"): HTMLPhraseElement; + createElement(tagName: "table"): HTMLTableElement; + createElement(tagName: "tbody"): HTMLTableSectionElement; + createElement(tagName: "td"): HTMLTableDataCellElement; + createElement(tagName: "textarea"): HTMLTextAreaElement; + createElement(tagName: "tfoot"): HTMLTableSectionElement; + createElement(tagName: "th"): HTMLTableHeaderCellElement; + createElement(tagName: "thead"): HTMLTableSectionElement; + createElement(tagName: "title"): HTMLTitleElement; + createElement(tagName: "tr"): HTMLTableRowElement; + createElement(tagName: "track"): HTMLTrackElement; + createElement(tagName: "tt"): HTMLPhraseElement; + createElement(tagName: "u"): HTMLPhraseElement; + createElement(tagName: "ul"): HTMLUListElement; + createElement(tagName: "var"): HTMLPhraseElement; + createElement(tagName: "video"): HTMLVideoElement; + createElement(tagName: "x-ms-webview"): MSHTMLWebViewElement; + createElement(tagName: "xmp"): HTMLBlockElement; + createElement(tagName: string): HTMLElement; + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "a"): SVGAElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "circle"): SVGCircleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "clipPath"): SVGClipPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "componentTransferFunction"): SVGComponentTransferFunctionElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "desc"): SVGDescElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "ellipse"): SVGEllipseElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feBlend"): SVGFEBlendElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feColorMatrix"): SVGFEColorMatrixElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDiffuseLighting"): SVGFEDiffuseLightingElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDisplacementMap"): SVGFEDisplacementMapElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feDistantLight"): SVGFEDistantLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFlood"): SVGFEFloodElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feImage"): SVGFEImageElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feOffset"): SVGFEOffsetElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "fePointLight"): SVGFEPointLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpecularLighting"): SVGFESpecularLightingElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feSpotLight"): SVGFESpotLightElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTile"): SVGFETileElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feTurbulence"): SVGFETurbulenceElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "foreignObject"): SVGForeignObjectElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "image"): SVGImageElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "gradient"): SVGGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "line"): SVGLineElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "linearGradient"): SVGLinearGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "marker"): SVGMarkerElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "mask"): SVGMaskElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "metadata"): SVGMetadataElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "pattern"): SVGPatternElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polygon"): SVGPolygonElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "polyline"): SVGPolylineElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "radialGradient"): SVGRadialGradientElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "rect"): SVGRectElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "script"): SVGScriptElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "stop"): SVGStopElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "style"): SVGStyleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "switch"): SVGSwitchElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "symbol"): SVGSymbolElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "tspan"): SVGTSpanElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textContent"): SVGTextContentElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "text"): SVGTextElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPath"): SVGTextPathElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "textPositioning"): SVGTextPositioningElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "title"): SVGTitleElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "use"): SVGUseElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "view"): SVGViewElement + createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: string): SVGElement + createElementNS(namespaceURI: string, qualifiedName: string): Element; + createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver: Node): XPathNSResolver; + /** + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list + * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; + createProcessingInstruction(target: string, data: string): ProcessingInstruction; + /** + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + */ + createRange(): Range; + /** + * Creates a text string from the specified value. + * @param data String that specifies the nodeValue property of the text node. + */ + createTextNode(data: string): Text; + createTouch(view: any, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch; + createTouchList(...touches: Touch[]): TouchList; + /** + * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document. + * @param root The root element or node to start traversing on. + * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow. + * @param filter A custom NodeFilter function to use. + * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded. + */ + createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; + /** + * Returns the element for the specified x coordinate and the specified y coordinate. + * @param x The x-offset + * @param y The y-offset + */ + elementFromPoint(x: number, y: number): Element; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; + /** + * Executes a command on the current document, current selection, or the given range. + * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. + * @param showUI Display the user interface, defaults to false. + * @param value Value to assign. + */ + execCommand(commandId: string, showUI?: boolean, value?: any): boolean; + /** + * Displays help information for the given command identifier. + * @param commandId Displays help information for the given command identifier. + */ + execCommandShowHelp(commandId: string): boolean; + exitFullscreen(): void; + exitPointerLock(): void; + /** + * Causes the element to receive the focus and executes the code specified by the onfocus event. + */ + focus(): void; + /** + * Returns a reference to the first object with the specified value of the ID or NAME attribute. + * @param elementId String that specifies the ID value. Case-insensitive. + */ + getElementById(elementId: string): HTMLElement; + getElementsByClassName(classNames: string): NodeListOf; + /** + * Gets a collection of objects based on the value of the NAME or ID attribute. + * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute. + */ + getElementsByName(elementName: string): NodeListOf; + /** + * Retrieves a collection of objects based on the specified element name. + * @param name Specifies the name of an element. + */ + getElementsByTagName(tagname: "a"): NodeListOf; + getElementsByTagName(tagname: "abbr"): NodeListOf; + getElementsByTagName(tagname: "acronym"): NodeListOf; + getElementsByTagName(tagname: "address"): NodeListOf; + getElementsByTagName(tagname: "applet"): NodeListOf; + getElementsByTagName(tagname: "area"): NodeListOf; + getElementsByTagName(tagname: "article"): NodeListOf; + getElementsByTagName(tagname: "aside"): NodeListOf; + getElementsByTagName(tagname: "audio"): NodeListOf; + getElementsByTagName(tagname: "b"): NodeListOf; + getElementsByTagName(tagname: "base"): NodeListOf; + getElementsByTagName(tagname: "basefont"): NodeListOf; + getElementsByTagName(tagname: "bdo"): NodeListOf; + getElementsByTagName(tagname: "big"): NodeListOf; + getElementsByTagName(tagname: "blockquote"): NodeListOf; + getElementsByTagName(tagname: "body"): NodeListOf; + getElementsByTagName(tagname: "br"): NodeListOf; + getElementsByTagName(tagname: "button"): NodeListOf; + getElementsByTagName(tagname: "canvas"): NodeListOf; + getElementsByTagName(tagname: "caption"): NodeListOf; + getElementsByTagName(tagname: "center"): NodeListOf; + getElementsByTagName(tagname: "circle"): NodeListOf; + getElementsByTagName(tagname: "cite"): NodeListOf; + getElementsByTagName(tagname: "clippath"): NodeListOf; + getElementsByTagName(tagname: "code"): NodeListOf; + getElementsByTagName(tagname: "col"): NodeListOf; + getElementsByTagName(tagname: "colgroup"): NodeListOf; + getElementsByTagName(tagname: "datalist"): NodeListOf; + getElementsByTagName(tagname: "dd"): NodeListOf; + getElementsByTagName(tagname: "defs"): NodeListOf; + getElementsByTagName(tagname: "del"): NodeListOf; + getElementsByTagName(tagname: "desc"): NodeListOf; + getElementsByTagName(tagname: "dfn"): NodeListOf; + getElementsByTagName(tagname: "dir"): NodeListOf; + getElementsByTagName(tagname: "div"): NodeListOf; + getElementsByTagName(tagname: "dl"): NodeListOf; + getElementsByTagName(tagname: "dt"): NodeListOf; + getElementsByTagName(tagname: "ellipse"): NodeListOf; + getElementsByTagName(tagname: "em"): NodeListOf; + getElementsByTagName(tagname: "embed"): NodeListOf; + getElementsByTagName(tagname: "feblend"): NodeListOf; + getElementsByTagName(tagname: "fecolormatrix"): NodeListOf; + getElementsByTagName(tagname: "fecomponenttransfer"): NodeListOf; + getElementsByTagName(tagname: "fecomposite"): NodeListOf; + getElementsByTagName(tagname: "feconvolvematrix"): NodeListOf; + getElementsByTagName(tagname: "fediffuselighting"): NodeListOf; + getElementsByTagName(tagname: "fedisplacementmap"): NodeListOf; + getElementsByTagName(tagname: "fedistantlight"): NodeListOf; + getElementsByTagName(tagname: "feflood"): NodeListOf; + getElementsByTagName(tagname: "fefunca"): NodeListOf; + getElementsByTagName(tagname: "fefuncb"): NodeListOf; + getElementsByTagName(tagname: "fefuncg"): NodeListOf; + getElementsByTagName(tagname: "fefuncr"): NodeListOf; + getElementsByTagName(tagname: "fegaussianblur"): NodeListOf; + getElementsByTagName(tagname: "feimage"): NodeListOf; + getElementsByTagName(tagname: "femerge"): NodeListOf; + getElementsByTagName(tagname: "femergenode"): NodeListOf; + getElementsByTagName(tagname: "femorphology"): NodeListOf; + getElementsByTagName(tagname: "feoffset"): NodeListOf; + getElementsByTagName(tagname: "fepointlight"): NodeListOf; + getElementsByTagName(tagname: "fespecularlighting"): NodeListOf; + getElementsByTagName(tagname: "fespotlight"): NodeListOf; + getElementsByTagName(tagname: "fetile"): NodeListOf; + getElementsByTagName(tagname: "feturbulence"): NodeListOf; + getElementsByTagName(tagname: "fieldset"): NodeListOf; + getElementsByTagName(tagname: "figcaption"): NodeListOf; + getElementsByTagName(tagname: "figure"): NodeListOf; + getElementsByTagName(tagname: "filter"): NodeListOf; + getElementsByTagName(tagname: "font"): NodeListOf; + getElementsByTagName(tagname: "footer"): NodeListOf; + getElementsByTagName(tagname: "foreignobject"): NodeListOf; + getElementsByTagName(tagname: "form"): NodeListOf; + getElementsByTagName(tagname: "frame"): NodeListOf; + getElementsByTagName(tagname: "frameset"): NodeListOf; + getElementsByTagName(tagname: "g"): NodeListOf; + getElementsByTagName(tagname: "h1"): NodeListOf; + getElementsByTagName(tagname: "h2"): NodeListOf; + getElementsByTagName(tagname: "h3"): NodeListOf; + getElementsByTagName(tagname: "h4"): NodeListOf; + getElementsByTagName(tagname: "h5"): NodeListOf; + getElementsByTagName(tagname: "h6"): NodeListOf; + getElementsByTagName(tagname: "head"): NodeListOf; + getElementsByTagName(tagname: "header"): NodeListOf; + getElementsByTagName(tagname: "hgroup"): NodeListOf; + getElementsByTagName(tagname: "hr"): NodeListOf; + getElementsByTagName(tagname: "html"): NodeListOf; + getElementsByTagName(tagname: "i"): NodeListOf; + getElementsByTagName(tagname: "iframe"): NodeListOf; + getElementsByTagName(tagname: "image"): NodeListOf; + getElementsByTagName(tagname: "img"): NodeListOf; + getElementsByTagName(tagname: "input"): NodeListOf; + getElementsByTagName(tagname: "ins"): NodeListOf; + getElementsByTagName(tagname: "isindex"): NodeListOf; + getElementsByTagName(tagname: "kbd"): NodeListOf; + getElementsByTagName(tagname: "keygen"): NodeListOf; + getElementsByTagName(tagname: "label"): NodeListOf; + getElementsByTagName(tagname: "legend"): NodeListOf; + getElementsByTagName(tagname: "li"): NodeListOf; + getElementsByTagName(tagname: "line"): NodeListOf; + getElementsByTagName(tagname: "lineargradient"): NodeListOf; + getElementsByTagName(tagname: "link"): NodeListOf; + getElementsByTagName(tagname: "listing"): NodeListOf; + getElementsByTagName(tagname: "map"): NodeListOf; + getElementsByTagName(tagname: "mark"): NodeListOf; + getElementsByTagName(tagname: "marker"): NodeListOf; + getElementsByTagName(tagname: "marquee"): NodeListOf; + getElementsByTagName(tagname: "mask"): NodeListOf; + getElementsByTagName(tagname: "menu"): NodeListOf; + getElementsByTagName(tagname: "meta"): NodeListOf; + getElementsByTagName(tagname: "metadata"): NodeListOf; + getElementsByTagName(tagname: "nav"): NodeListOf; + getElementsByTagName(tagname: "nextid"): NodeListOf; + getElementsByTagName(tagname: "nobr"): NodeListOf; + getElementsByTagName(tagname: "noframes"): NodeListOf; + getElementsByTagName(tagname: "noscript"): NodeListOf; + getElementsByTagName(tagname: "object"): NodeListOf; + getElementsByTagName(tagname: "ol"): NodeListOf; + getElementsByTagName(tagname: "optgroup"): NodeListOf; + getElementsByTagName(tagname: "option"): NodeListOf; + getElementsByTagName(tagname: "p"): NodeListOf; + getElementsByTagName(tagname: "param"): NodeListOf; + getElementsByTagName(tagname: "path"): NodeListOf; + getElementsByTagName(tagname: "pattern"): NodeListOf; + getElementsByTagName(tagname: "plaintext"): NodeListOf; + getElementsByTagName(tagname: "polygon"): NodeListOf; + getElementsByTagName(tagname: "polyline"): NodeListOf; + getElementsByTagName(tagname: "pre"): NodeListOf; + getElementsByTagName(tagname: "progress"): NodeListOf; + getElementsByTagName(tagname: "q"): NodeListOf; + getElementsByTagName(tagname: "radialgradient"): NodeListOf; + getElementsByTagName(tagname: "rect"): NodeListOf; + getElementsByTagName(tagname: "rt"): NodeListOf; + getElementsByTagName(tagname: "ruby"): NodeListOf; + getElementsByTagName(tagname: "s"): NodeListOf; + getElementsByTagName(tagname: "samp"): NodeListOf; + getElementsByTagName(tagname: "script"): NodeListOf; + getElementsByTagName(tagname: "section"): NodeListOf; + getElementsByTagName(tagname: "select"): NodeListOf; + getElementsByTagName(tagname: "small"): NodeListOf; + getElementsByTagName(tagname: "source"): NodeListOf; + getElementsByTagName(tagname: "span"): NodeListOf; + getElementsByTagName(tagname: "stop"): NodeListOf; + getElementsByTagName(tagname: "strike"): NodeListOf; + getElementsByTagName(tagname: "strong"): NodeListOf; + getElementsByTagName(tagname: "style"): NodeListOf; + getElementsByTagName(tagname: "sub"): NodeListOf; + getElementsByTagName(tagname: "sup"): NodeListOf; + getElementsByTagName(tagname: "svg"): NodeListOf; + getElementsByTagName(tagname: "switch"): NodeListOf; + getElementsByTagName(tagname: "symbol"): NodeListOf; + getElementsByTagName(tagname: "table"): NodeListOf; + getElementsByTagName(tagname: "tbody"): NodeListOf; + getElementsByTagName(tagname: "td"): NodeListOf; + getElementsByTagName(tagname: "text"): NodeListOf; + getElementsByTagName(tagname: "textpath"): NodeListOf; + getElementsByTagName(tagname: "textarea"): NodeListOf; + getElementsByTagName(tagname: "tfoot"): NodeListOf; + getElementsByTagName(tagname: "th"): NodeListOf; + getElementsByTagName(tagname: "thead"): NodeListOf; + getElementsByTagName(tagname: "title"): NodeListOf; + getElementsByTagName(tagname: "tr"): NodeListOf; + getElementsByTagName(tagname: "track"): NodeListOf; + getElementsByTagName(tagname: "tspan"): NodeListOf; + getElementsByTagName(tagname: "tt"): NodeListOf; + getElementsByTagName(tagname: "u"): NodeListOf; + getElementsByTagName(tagname: "ul"): NodeListOf; + getElementsByTagName(tagname: "use"): NodeListOf; + getElementsByTagName(tagname: "var"): NodeListOf; + getElementsByTagName(tagname: "video"): NodeListOf; + getElementsByTagName(tagname: "view"): NodeListOf; + getElementsByTagName(tagname: "wbr"): NodeListOf; + getElementsByTagName(tagname: "x-ms-webview"): NodeListOf; + getElementsByTagName(tagname: "xmp"): NodeListOf; + getElementsByTagName(tagname: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf; + /** + * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage. + */ + getSelection(): Selection; + /** + * Gets a value indicating whether the object currently has focus. + */ + hasFocus(): boolean; + importNode(importedNode: Node, deep: boolean): Node; + msElementsFromPoint(x: number, y: number): NodeList; + msElementsFromRect(left: number, top: number, width: number, height: number): NodeList; + /** + * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method. + * @param url Specifies a MIME type for the document. + * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element. + * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported. + * @param replace Specifies whether the existing entry for the document is replaced in the history list. + */ + open(url?: string, name?: string, features?: string, replace?: boolean): Document; + /** + * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. + * @param commandId Specifies a command identifier. + */ + queryCommandEnabled(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the specified command is in the indeterminate state. + * @param commandId String that specifies a command identifier. + */ + queryCommandIndeterm(commandId: string): boolean; + /** + * Returns a Boolean value that indicates the current state of the command. + * @param commandId String that specifies a command identifier. + */ + queryCommandState(commandId: string): boolean; + /** + * Returns a Boolean value that indicates whether the current command is supported on the current range. + * @param commandId Specifies a command identifier. + */ + queryCommandSupported(commandId: string): boolean; + /** + * Retrieves the string associated with a command. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + */ + queryCommandText(commandId: string): string; + /** + * Returns the current value of the document, range, or current selection for the given command. + * @param commandId String that specifies a command identifier. + */ + queryCommandValue(commandId: string): string; + releaseEvents(): void; + /** + * Allows updating the print settings for the page. + */ + updateSettings(): void; + webkitCancelFullScreen(): void; + webkitExitFullscreen(): void; + /** + * Writes one or more HTML expressions to a document in the specified window. + * @param content Specifies the text and HTML tags to write. + */ + write(...content: string[]): void; + /** + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * @param content The text and HTML tags to write. + */ + writeln(...content: string[]): void; + createElement(tagName: "picture"): HTMLPictureElement; + getElementsByTagName(tagname: "picture"): NodeListOf; + addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "fullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "fullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mssitemodejumplistitemremoved", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "msthumbnailclick", listener: (ev: MSSiteModeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerlockchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointerlockerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stop", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Document: { + prototype: Document; + new(): Document; +} + +interface DocumentFragment extends Node, NodeSelector { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var DocumentFragment: { + prototype: DocumentFragment; + new(): DocumentFragment; +} + +interface DocumentType extends Node, ChildNode { + entities: NamedNodeMap; + internalSubset: string; + name: string; + notations: NamedNodeMap; + publicId: string; + systemId: string; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var DocumentType: { + prototype: DocumentType; + new(): DocumentType; +} + +interface DragEvent extends MouseEvent { + dataTransfer: DataTransfer; + initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; + msConvertURL(file: File, targetType: string, targetURL?: string): void; +} + +declare var DragEvent: { + prototype: DragEvent; + new(): DragEvent; +} + +interface DynamicsCompressorNode extends AudioNode { + attack: AudioParam; + knee: AudioParam; + ratio: AudioParam; + reduction: AudioParam; + release: AudioParam; + threshold: AudioParam; +} + +declare var DynamicsCompressorNode: { + prototype: DynamicsCompressorNode; + new(): DynamicsCompressorNode; +} + +interface EXT_texture_filter_anisotropic { + MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +declare var EXT_texture_filter_anisotropic: { + prototype: EXT_texture_filter_anisotropic; + new(): EXT_texture_filter_anisotropic; + MAX_TEXTURE_MAX_ANISOTROPY_EXT: number; + TEXTURE_MAX_ANISOTROPY_EXT: number; +} + +interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode { + classList: DOMTokenList; + clientHeight: number; + clientLeft: number; + clientTop: number; + clientWidth: number; + msContentZoomFactor: number; + msRegionOverflow: string; + onariarequest: (ev: AriaRequestEvent) => any; + oncommand: (ev: CommandEvent) => any; + ongotpointercapture: (ev: PointerEvent) => any; + onlostpointercapture: (ev: PointerEvent) => any; + onmsgesturechange: (ev: MSGestureEvent) => any; + onmsgesturedoubletap: (ev: MSGestureEvent) => any; + onmsgestureend: (ev: MSGestureEvent) => any; + onmsgesturehold: (ev: MSGestureEvent) => any; + onmsgesturestart: (ev: MSGestureEvent) => any; + onmsgesturetap: (ev: MSGestureEvent) => any; + onmsgotpointercapture: (ev: MSPointerEvent) => any; + onmsinertiastart: (ev: MSGestureEvent) => any; + onmslostpointercapture: (ev: MSPointerEvent) => any; + onmspointercancel: (ev: MSPointerEvent) => any; + onmspointerdown: (ev: MSPointerEvent) => any; + onmspointerenter: (ev: MSPointerEvent) => any; + onmspointerleave: (ev: MSPointerEvent) => any; + onmspointermove: (ev: MSPointerEvent) => any; + onmspointerout: (ev: MSPointerEvent) => any; + onmspointerover: (ev: MSPointerEvent) => any; + onmspointerup: (ev: MSPointerEvent) => any; + ontouchcancel: (ev: TouchEvent) => any; + ontouchend: (ev: TouchEvent) => any; + ontouchmove: (ev: TouchEvent) => any; + ontouchstart: (ev: TouchEvent) => any; + onwebkitfullscreenchange: (ev: Event) => any; + onwebkitfullscreenerror: (ev: Event) => any; + scrollHeight: number; + scrollLeft: number; + scrollTop: number; + scrollWidth: number; + tagName: string; + id: string; + className: string; + innerHTML: string; + getAttribute(name?: string): string; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + getElementsByTagName(name: "a"): NodeListOf; + getElementsByTagName(name: "abbr"): NodeListOf; + getElementsByTagName(name: "acronym"): NodeListOf; + getElementsByTagName(name: "address"): NodeListOf; + getElementsByTagName(name: "applet"): NodeListOf; + getElementsByTagName(name: "area"): NodeListOf; + getElementsByTagName(name: "article"): NodeListOf; + getElementsByTagName(name: "aside"): NodeListOf; + getElementsByTagName(name: "audio"): NodeListOf; + getElementsByTagName(name: "b"): NodeListOf; + getElementsByTagName(name: "base"): NodeListOf; + getElementsByTagName(name: "basefont"): NodeListOf; + getElementsByTagName(name: "bdo"): NodeListOf; + getElementsByTagName(name: "big"): NodeListOf; + getElementsByTagName(name: "blockquote"): NodeListOf; + getElementsByTagName(name: "body"): NodeListOf; + getElementsByTagName(name: "br"): NodeListOf; + getElementsByTagName(name: "button"): NodeListOf; + getElementsByTagName(name: "canvas"): NodeListOf; + getElementsByTagName(name: "caption"): NodeListOf; + getElementsByTagName(name: "center"): NodeListOf; + getElementsByTagName(name: "circle"): NodeListOf; + getElementsByTagName(name: "cite"): NodeListOf; + getElementsByTagName(name: "clippath"): NodeListOf; + getElementsByTagName(name: "code"): NodeListOf; + getElementsByTagName(name: "col"): NodeListOf; + getElementsByTagName(name: "colgroup"): NodeListOf; + getElementsByTagName(name: "datalist"): NodeListOf; + getElementsByTagName(name: "dd"): NodeListOf; + getElementsByTagName(name: "defs"): NodeListOf; + getElementsByTagName(name: "del"): NodeListOf; + getElementsByTagName(name: "desc"): NodeListOf; + getElementsByTagName(name: "dfn"): NodeListOf; + getElementsByTagName(name: "dir"): NodeListOf; + getElementsByTagName(name: "div"): NodeListOf; + getElementsByTagName(name: "dl"): NodeListOf; + getElementsByTagName(name: "dt"): NodeListOf; + getElementsByTagName(name: "ellipse"): NodeListOf; + getElementsByTagName(name: "em"): NodeListOf; + getElementsByTagName(name: "embed"): NodeListOf; + getElementsByTagName(name: "feblend"): NodeListOf; + getElementsByTagName(name: "fecolormatrix"): NodeListOf; + getElementsByTagName(name: "fecomponenttransfer"): NodeListOf; + getElementsByTagName(name: "fecomposite"): NodeListOf; + getElementsByTagName(name: "feconvolvematrix"): NodeListOf; + getElementsByTagName(name: "fediffuselighting"): NodeListOf; + getElementsByTagName(name: "fedisplacementmap"): NodeListOf; + getElementsByTagName(name: "fedistantlight"): NodeListOf; + getElementsByTagName(name: "feflood"): NodeListOf; + getElementsByTagName(name: "fefunca"): NodeListOf; + getElementsByTagName(name: "fefuncb"): NodeListOf; + getElementsByTagName(name: "fefuncg"): NodeListOf; + getElementsByTagName(name: "fefuncr"): NodeListOf; + getElementsByTagName(name: "fegaussianblur"): NodeListOf; + getElementsByTagName(name: "feimage"): NodeListOf; + getElementsByTagName(name: "femerge"): NodeListOf; + getElementsByTagName(name: "femergenode"): NodeListOf; + getElementsByTagName(name: "femorphology"): NodeListOf; + getElementsByTagName(name: "feoffset"): NodeListOf; + getElementsByTagName(name: "fepointlight"): NodeListOf; + getElementsByTagName(name: "fespecularlighting"): NodeListOf; + getElementsByTagName(name: "fespotlight"): NodeListOf; + getElementsByTagName(name: "fetile"): NodeListOf; + getElementsByTagName(name: "feturbulence"): NodeListOf; + getElementsByTagName(name: "fieldset"): NodeListOf; + getElementsByTagName(name: "figcaption"): NodeListOf; + getElementsByTagName(name: "figure"): NodeListOf; + getElementsByTagName(name: "filter"): NodeListOf; + getElementsByTagName(name: "font"): NodeListOf; + getElementsByTagName(name: "footer"): NodeListOf; + getElementsByTagName(name: "foreignobject"): NodeListOf; + getElementsByTagName(name: "form"): NodeListOf; + getElementsByTagName(name: "frame"): NodeListOf; + getElementsByTagName(name: "frameset"): NodeListOf; + getElementsByTagName(name: "g"): NodeListOf; + getElementsByTagName(name: "h1"): NodeListOf; + getElementsByTagName(name: "h2"): NodeListOf; + getElementsByTagName(name: "h3"): NodeListOf; + getElementsByTagName(name: "h4"): NodeListOf; + getElementsByTagName(name: "h5"): NodeListOf; + getElementsByTagName(name: "h6"): NodeListOf; + getElementsByTagName(name: "head"): NodeListOf; + getElementsByTagName(name: "header"): NodeListOf; + getElementsByTagName(name: "hgroup"): NodeListOf; + getElementsByTagName(name: "hr"): NodeListOf; + getElementsByTagName(name: "html"): NodeListOf; + getElementsByTagName(name: "i"): NodeListOf; + getElementsByTagName(name: "iframe"): NodeListOf; + getElementsByTagName(name: "image"): NodeListOf; + getElementsByTagName(name: "img"): NodeListOf; + getElementsByTagName(name: "input"): NodeListOf; + getElementsByTagName(name: "ins"): NodeListOf; + getElementsByTagName(name: "isindex"): NodeListOf; + getElementsByTagName(name: "kbd"): NodeListOf; + getElementsByTagName(name: "keygen"): NodeListOf; + getElementsByTagName(name: "label"): NodeListOf; + getElementsByTagName(name: "legend"): NodeListOf; + getElementsByTagName(name: "li"): NodeListOf; + getElementsByTagName(name: "line"): NodeListOf; + getElementsByTagName(name: "lineargradient"): NodeListOf; + getElementsByTagName(name: "link"): NodeListOf; + getElementsByTagName(name: "listing"): NodeListOf; + getElementsByTagName(name: "map"): NodeListOf; + getElementsByTagName(name: "mark"): NodeListOf; + getElementsByTagName(name: "marker"): NodeListOf; + getElementsByTagName(name: "marquee"): NodeListOf; + getElementsByTagName(name: "mask"): NodeListOf; + getElementsByTagName(name: "menu"): NodeListOf; + getElementsByTagName(name: "meta"): NodeListOf; + getElementsByTagName(name: "metadata"): NodeListOf; + getElementsByTagName(name: "nav"): NodeListOf; + getElementsByTagName(name: "nextid"): NodeListOf; + getElementsByTagName(name: "nobr"): NodeListOf; + getElementsByTagName(name: "noframes"): NodeListOf; + getElementsByTagName(name: "noscript"): NodeListOf; + getElementsByTagName(name: "object"): NodeListOf; + getElementsByTagName(name: "ol"): NodeListOf; + getElementsByTagName(name: "optgroup"): NodeListOf; + getElementsByTagName(name: "option"): NodeListOf; + getElementsByTagName(name: "p"): NodeListOf; + getElementsByTagName(name: "param"): NodeListOf; + getElementsByTagName(name: "path"): NodeListOf; + getElementsByTagName(name: "pattern"): NodeListOf; + getElementsByTagName(name: "plaintext"): NodeListOf; + getElementsByTagName(name: "polygon"): NodeListOf; + getElementsByTagName(name: "polyline"): NodeListOf; + getElementsByTagName(name: "pre"): NodeListOf; + getElementsByTagName(name: "progress"): NodeListOf; + getElementsByTagName(name: "q"): NodeListOf; + getElementsByTagName(name: "radialgradient"): NodeListOf; + getElementsByTagName(name: "rect"): NodeListOf; + getElementsByTagName(name: "rt"): NodeListOf; + getElementsByTagName(name: "ruby"): NodeListOf; + getElementsByTagName(name: "s"): NodeListOf; + getElementsByTagName(name: "samp"): NodeListOf; + getElementsByTagName(name: "script"): NodeListOf; + getElementsByTagName(name: "section"): NodeListOf; + getElementsByTagName(name: "select"): NodeListOf; + getElementsByTagName(name: "small"): NodeListOf; + getElementsByTagName(name: "source"): NodeListOf; + getElementsByTagName(name: "span"): NodeListOf; + getElementsByTagName(name: "stop"): NodeListOf; + getElementsByTagName(name: "strike"): NodeListOf; + getElementsByTagName(name: "strong"): NodeListOf; + getElementsByTagName(name: "style"): NodeListOf; + getElementsByTagName(name: "sub"): NodeListOf; + getElementsByTagName(name: "sup"): NodeListOf; + getElementsByTagName(name: "svg"): NodeListOf; + getElementsByTagName(name: "switch"): NodeListOf; + getElementsByTagName(name: "symbol"): NodeListOf; + getElementsByTagName(name: "table"): NodeListOf; + getElementsByTagName(name: "tbody"): NodeListOf; + getElementsByTagName(name: "td"): NodeListOf; + getElementsByTagName(name: "text"): NodeListOf; + getElementsByTagName(name: "textpath"): NodeListOf; + getElementsByTagName(name: "textarea"): NodeListOf; + getElementsByTagName(name: "tfoot"): NodeListOf; + getElementsByTagName(name: "th"): NodeListOf; + getElementsByTagName(name: "thead"): NodeListOf; + getElementsByTagName(name: "title"): NodeListOf; + getElementsByTagName(name: "tr"): NodeListOf; + getElementsByTagName(name: "track"): NodeListOf; + getElementsByTagName(name: "tspan"): NodeListOf; + getElementsByTagName(name: "tt"): NodeListOf; + getElementsByTagName(name: "u"): NodeListOf; + getElementsByTagName(name: "ul"): NodeListOf; + getElementsByTagName(name: "use"): NodeListOf; + getElementsByTagName(name: "var"): NodeListOf; + getElementsByTagName(name: "video"): NodeListOf; + getElementsByTagName(name: "view"): NodeListOf; + getElementsByTagName(name: "wbr"): NodeListOf; + getElementsByTagName(name: "x-ms-webview"): NodeListOf; + getElementsByTagName(name: "xmp"): NodeListOf; + getElementsByTagName(name: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf; + hasAttribute(name: string): boolean; + hasAttributeNS(namespaceURI: string, localName: string): boolean; + msGetRegionContent(): MSRangeCollection; + msGetUntransformedBounds(): ClientRect; + msMatchesSelector(selectors: string): boolean; + msReleasePointerCapture(pointerId: number): void; + msSetPointerCapture(pointerId: number): void; + msZoomTo(args: MsZoomToOptions): void; + releasePointerCapture(pointerId: number): void; + removeAttribute(name?: string): void; + removeAttributeNS(namespaceURI: string, localName: string): void; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): void; + requestPointerLock(): void; + setAttribute(name: string, value: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): void; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): void; + webkitRequestFullscreen(): void; + getElementsByClassName(classNames: string): NodeListOf; + matches(selector: string): boolean; + getElementsByTagName(tagname: "picture"): NodeListOf; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Element: { + prototype: Element; + new(): Element; +} + +interface ErrorEvent extends Event { + colno: number; + error: any; + filename: string; + lineno: number; + message: string; + initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void; +} + +declare var ErrorEvent: { + prototype: ErrorEvent; + new(): ErrorEvent; +} + +interface Event { + bubbles: boolean; + cancelBubble: boolean; + cancelable: boolean; + currentTarget: EventTarget; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + returnValue: boolean; + srcElement: Element; + target: EventTarget; + timeStamp: number; + type: string; + initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void; + preventDefault(): void; + stopImmediatePropagation(): void; + stopPropagation(): void; + AT_TARGET: number; + BUBBLING_PHASE: number; + CAPTURING_PHASE: number; +} + +declare var Event: { + prototype: Event; + new(type: string, eventInitDict?: EventInit): Event; + AT_TARGET: number; + BUBBLING_PHASE: number; + CAPTURING_PHASE: number; +} + +interface EventTarget { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var EventTarget: { + prototype: EventTarget; + new(): EventTarget; +} + +interface External { +} + +declare var External: { + prototype: External; + new(): External; +} + +interface File extends Blob { + lastModifiedDate: any; + name: string; +} + +declare var File: { + prototype: File; + new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File; +} + +interface FileList { + length: number; + item(index: number): File; + [index: number]: File; +} + +declare var FileList: { + prototype: FileList; + new(): FileList; +} + +interface FileReader extends EventTarget, MSBaseReader { + error: DOMError; + readAsArrayBuffer(blob: Blob): void; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var FileReader: { + prototype: FileReader; + new(): FileReader; +} + +interface FocusEvent extends UIEvent { + relatedTarget: EventTarget; + initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void; +} + +declare var FocusEvent: { + prototype: FocusEvent; + new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; +} + +interface FormData { + append(name: any, value: any, blobName?: string): void; +} + +declare var FormData: { + prototype: FormData; + new (form?: HTMLFormElement): FormData; +} + +interface GainNode extends AudioNode { + gain: AudioParam; +} + +declare var GainNode: { + prototype: GainNode; + new(): GainNode; +} + +interface Gamepad { + axes: number[]; + buttons: GamepadButton[]; + connected: boolean; + id: string; + index: number; + mapping: string; + timestamp: number; +} + +declare var Gamepad: { + prototype: Gamepad; + new(): Gamepad; +} + +interface GamepadButton { + pressed: boolean; + value: number; +} + +declare var GamepadButton: { + prototype: GamepadButton; + new(): GamepadButton; +} + +interface GamepadEvent extends Event { + gamepad: Gamepad; +} + +declare var GamepadEvent: { + prototype: GamepadEvent; + new(): GamepadEvent; +} + +interface Geolocation { + clearWatch(watchId: number): void; + getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; + watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; +} + +declare var Geolocation: { + prototype: Geolocation; + new(): Geolocation; +} + +interface HTMLAllCollection extends HTMLCollection { + namedItem(name: string): Element; +} + +declare var HTMLAllCollection: { + prototype: HTMLAllCollection; + new(): HTMLAllCollection; +} + +interface HTMLAnchorElement extends HTMLElement { + Methods: string; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + /** + * Contains the anchor portion of the URL including the hash sign (#). + */ + hash: string; + /** + * Contains the hostname and port values of the URL. + */ + host: string; + /** + * Contains the hostname of a URL. + */ + hostname: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + mimeType: string; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + nameProp: string; + /** + * Contains the pathname of the URL. + */ + pathname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Contains the protocol of the URL. + */ + protocol: string; + protocolLong: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + type: string; + urn: string; + /** + * Returns a string representation of an object. + */ + toString(): string; +} + +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new(): HTMLAnchorElement; +} + +interface HTMLAppletElement extends HTMLElement { + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + BaseHref: string; + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + border: string; + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Address of a pointer to the document this page or frame contains. If there is no document, then null will be returned. + */ + contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + /** + * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. + */ + declare: boolean; + form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Sets or retrieves the shape of the object. + */ + name: string; + object: string; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + vspace: number; + width: number; +} + +declare var HTMLAppletElement: { + prototype: HTMLAppletElement; + new(): HTMLAppletElement; +} + +interface HTMLAreaElement extends HTMLElement { + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Sets or retrieves the coordinates of the object. + */ + coords: string; + /** + * Sets or retrieves the subsection of the href property that follows the number sign (#). + */ + hash: string; + /** + * Sets or retrieves the hostname and port number of the location or URL. + */ + host: string; + /** + * Sets or retrieves the host name part of the location or URL. + */ + hostname: string; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or gets whether clicks in this region cause action. + */ + noHref: boolean; + /** + * Sets or retrieves the file name or path specified by the object. + */ + pathname: string; + /** + * Sets or retrieves the port number associated with a URL. + */ + port: string; + /** + * Sets or retrieves the protocol portion of a URL. + */ + protocol: string; + rel: string; + /** + * Sets or retrieves the substring of the href property that follows the question mark. + */ + search: string; + /** + * Sets or retrieves the shape of the object. + */ + shape: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns a string representation of an object. + */ + toString(): string; +} + +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new(): HTMLAreaElement; +} + +interface HTMLAreasCollection extends HTMLCollection { + /** + * Adds an element to the areas, controlRange, or options collection. + */ + add(element: HTMLElement, before?: HTMLElement | number): void; + /** + * Removes an element from the collection. + */ + remove(index?: number): void; +} + +declare var HTMLAreasCollection: { + prototype: HTMLAreasCollection; + new(): HTMLAreasCollection; +} + +interface HTMLAudioElement extends HTMLMediaElement { +} + +declare var HTMLAudioElement: { + prototype: HTMLAudioElement; + new(): HTMLAudioElement; +} + +interface HTMLBRElement extends HTMLElement { + /** + * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document. + */ + clear: string; +} + +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +} + +interface HTMLBaseElement extends HTMLElement { + /** + * Gets or sets the baseline URL on which relative links are based. + */ + href: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; +} + +declare var HTMLBaseElement: { + prototype: HTMLBaseElement; + new(): HTMLBaseElement; +} + +interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + /** + * Sets or retrieves the font size of the object. + */ + size: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBaseFontElement: { + prototype: HTMLBaseFontElement; + new(): HTMLBaseFontElement; +} + +interface HTMLBlockElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + clear: string; + /** + * Sets or retrieves the width of the object. + */ + width: number; +} + +declare var HTMLBlockElement: { + prototype: HTMLBlockElement; + new(): HTMLBlockElement; +} + +interface HTMLBodyElement extends HTMLElement { + aLink: any; + background: string; + bgColor: any; + bgProperties: string; + link: any; + noWrap: boolean; + onafterprint: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + onblur: (ev: FocusEvent) => any; + onerror: (ev: Event) => any; + onfocus: (ev: FocusEvent) => any; + onhashchange: (ev: HashChangeEvent) => any; + onload: (ev: Event) => any; + onmessage: (ev: MessageEvent) => any; + onoffline: (ev: Event) => any; + ononline: (ev: Event) => any; + onorientationchange: (ev: Event) => any; + onpagehide: (ev: PageTransitionEvent) => any; + onpageshow: (ev: PageTransitionEvent) => any; + onpopstate: (ev: PopStateEvent) => any; + onresize: (ev: UIEvent) => any; + onstorage: (ev: StorageEvent) => any; + onunload: (ev: Event) => any; + text: any; + vLink: any; + createTextRange(): TextRange; + addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: HashChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "orientationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLBodyElement: { + prototype: HTMLBodyElement; + new(): HTMLBodyElement; +} + +interface HTMLButtonElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + status: any; + /** + * Gets the classification and default behavior of the button. + */ + type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Sets or retrieves the default or selected value of the control. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Creates a TextRange object for the element. + */ + createTextRange(): TextRange; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +declare var HTMLButtonElement: { + prototype: HTMLButtonElement; + new(): HTMLButtonElement; +} + +interface HTMLCanvasElement extends HTMLElement { + /** + * Gets or sets the height of a canvas element on a document. + */ + height: number; + /** + * Gets or sets the width of a canvas element on a document. + */ + width: number; + /** + * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. + * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); + */ + getContext(contextId: "2d"): CanvasRenderingContext2D; + getContext(contextId: "experimental-webgl"): WebGLRenderingContext; + getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext; + /** + * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. + */ + msToBlob(): Blob; + /** + * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element. + * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. + */ + toDataURL(type?: string, ...args: any[]): string; + toBlob(): Blob; +} + +declare var HTMLCanvasElement: { + prototype: HTMLCanvasElement; + new(): HTMLCanvasElement; +} + +interface HTMLCollection { + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Retrieves an object from various collections. + */ + item(nameOrIndex?: any, optionalIndex?: any): Element; + /** + * Retrieves a select object or an object from an options collection. + */ + namedItem(name: string): Element; + [index: number]: Element; +} + +declare var HTMLCollection: { + prototype: HTMLCollection; + new(): HTMLCollection; +} + +interface HTMLDDElement extends HTMLElement { + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; +} + +declare var HTMLDDElement: { + prototype: HTMLDDElement; + new(): HTMLDDElement; +} + +interface HTMLDListElement extends HTMLElement { + compact: boolean; +} + +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +} + +interface HTMLDTElement extends HTMLElement { + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; +} + +declare var HTMLDTElement: { + prototype: HTMLDTElement; + new(): HTMLDTElement; +} + +interface HTMLDataListElement extends HTMLElement { + options: HTMLCollection; +} + +declare var HTMLDataListElement: { + prototype: HTMLDataListElement; + new(): HTMLDataListElement; +} + +interface HTMLDirectoryElement extends HTMLElement { + compact: boolean; +} + +declare var HTMLDirectoryElement: { + prototype: HTMLDirectoryElement; + new(): HTMLDirectoryElement; +} + +interface HTMLDivElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; +} + +declare var HTMLDivElement: { + prototype: HTMLDivElement; + new(): HTMLDivElement; +} + +interface HTMLDocument extends Document { +} + +declare var HTMLDocument: { + prototype: HTMLDocument; + new(): HTMLDocument; +} + +interface HTMLElement extends Element { + accessKey: string; + children: HTMLCollection; + contentEditable: string; + dataset: DOMStringMap; + dir: string; + draggable: boolean; + hidden: boolean; + hideFocus: boolean; + innerHTML: string; + innerText: string; + isContentEditable: boolean; + lang: string; + offsetHeight: number; + offsetLeft: number; + offsetParent: Element; + offsetTop: number; + offsetWidth: number; + onabort: (ev: Event) => any; + onactivate: (ev: UIEvent) => any; + onbeforeactivate: (ev: UIEvent) => any; + onbeforecopy: (ev: DragEvent) => any; + onbeforecut: (ev: DragEvent) => any; + onbeforedeactivate: (ev: UIEvent) => any; + onbeforepaste: (ev: DragEvent) => any; + onblur: (ev: FocusEvent) => any; + oncanplay: (ev: Event) => any; + oncanplaythrough: (ev: Event) => any; + onchange: (ev: Event) => any; + onclick: (ev: MouseEvent) => any; + oncontextmenu: (ev: PointerEvent) => any; + oncopy: (ev: DragEvent) => any; + oncuechange: (ev: Event) => any; + oncut: (ev: DragEvent) => any; + ondblclick: (ev: MouseEvent) => any; + ondeactivate: (ev: UIEvent) => any; + ondrag: (ev: DragEvent) => any; + ondragend: (ev: DragEvent) => any; + ondragenter: (ev: DragEvent) => any; + ondragleave: (ev: DragEvent) => any; + ondragover: (ev: DragEvent) => any; + ondragstart: (ev: DragEvent) => any; + ondrop: (ev: DragEvent) => any; + ondurationchange: (ev: Event) => any; + onemptied: (ev: Event) => any; + onended: (ev: Event) => any; + onerror: (ev: Event) => any; + onfocus: (ev: FocusEvent) => any; + oninput: (ev: Event) => any; + onkeydown: (ev: KeyboardEvent) => any; + onkeypress: (ev: KeyboardEvent) => any; + onkeyup: (ev: KeyboardEvent) => any; + onload: (ev: Event) => any; + onloadeddata: (ev: Event) => any; + onloadedmetadata: (ev: Event) => any; + onloadstart: (ev: Event) => any; + onmousedown: (ev: MouseEvent) => any; + onmouseenter: (ev: MouseEvent) => any; + onmouseleave: (ev: MouseEvent) => any; + onmousemove: (ev: MouseEvent) => any; + onmouseout: (ev: MouseEvent) => any; + onmouseover: (ev: MouseEvent) => any; + onmouseup: (ev: MouseEvent) => any; + onmousewheel: (ev: MouseWheelEvent) => any; + onmscontentzoom: (ev: UIEvent) => any; + onmsmanipulationstatechanged: (ev: MSManipulationEvent) => any; + onpaste: (ev: DragEvent) => any; + onpause: (ev: Event) => any; + onplay: (ev: Event) => any; + onplaying: (ev: Event) => any; + onprogress: (ev: ProgressEvent) => any; + onratechange: (ev: Event) => any; + onreset: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + onseeked: (ev: Event) => any; + onseeking: (ev: Event) => any; + onselect: (ev: UIEvent) => any; + onselectstart: (ev: Event) => any; + onstalled: (ev: Event) => any; + onsubmit: (ev: Event) => any; + onsuspend: (ev: Event) => any; + ontimeupdate: (ev: Event) => any; + onvolumechange: (ev: Event) => any; + onwaiting: (ev: Event) => any; + outerHTML: string; + outerText: string; + spellcheck: boolean; + style: CSSStyleDeclaration; + tabIndex: number; + title: string; + blur(): void; + click(): void; + dragDrop(): boolean; + focus(): void; + insertAdjacentElement(position: string, insertedElement: Element): Element; + insertAdjacentHTML(where: string, html: string): void; + insertAdjacentText(where: string, text: string): void; + msGetInputContext(): MSInputMethodContext; + scrollIntoView(top?: boolean): void; + setActive(): void; + addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLElement: { + prototype: HTMLElement; + new(): HTMLElement; +} + +interface HTMLEmbedElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves the height of the object. + */ + height: string; + hidden: any; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the palette used for the embedded document. + */ + palette: string; + /** + * Retrieves the URL of the plug-in used to view an embedded document. + */ + pluginspage: string; + readyState: string; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the height and width units of the embed object. + */ + units: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLEmbedElement: { + prototype: HTMLEmbedElement; + new(): HTMLEmbedElement; +} + +interface HTMLFieldSetElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; +} + +declare var HTMLFieldSetElement: { + prototype: HTMLFieldSetElement; + new(): HTMLFieldSetElement; +} + +interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves the current typeface family. + */ + face: string; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFontElement: { + prototype: HTMLFontElement; + new(): HTMLFontElement; +} + +interface HTMLFormElement extends HTMLElement { + /** + * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form. + */ + acceptCharset: string; + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Retrieves a collection, in source order, of all controls in a given form. + */ + elements: HTMLCollection; + /** + * Sets or retrieves the MIME encoding for the form. + */ + encoding: string; + /** + * Sets or retrieves the encoding type for the form. + */ + enctype: string; + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves how to send the form data to the server. + */ + method: string; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Designates a form that is not validated when submitted. + */ + noValidate: boolean; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a form object or an object from an elements collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a form object or an object from an elements collection. + */ + namedItem(name: string): any; + /** + * Fires when the user resets a form. + */ + reset(): void; + /** + * Fires when a FORM is about to be submitted. + */ + submit(): void; + [name: string]: any; +} + +declare var HTMLFormElement: { + prototype: HTMLFormElement; + new(): HTMLFormElement; +} + +interface HTMLFrameElement extends HTMLElement, GetSVGDocument { + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Retrieves the document object of the page or frame. + */ + contentDocument: Document; + /** + * Retrieves the object of the specified. + */ + contentWindow: Window; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves the height of the object. + */ + height: string | number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Raised when the object has been completely received from the server. + */ + onload: (ev: Event) => any; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied. + */ + security: any; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the width of the object. + */ + width: string | number; + addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFrameElement: { + prototype: HTMLFrameElement; + new(): HTMLFrameElement; +} + +interface HTMLFrameSetElement extends HTMLElement { + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Sets or retrieves the frame widths of the object. + */ + cols: string; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + name: string; + onafterprint: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + /** + * Fires when the object loses the input focus. + */ + onblur: (ev: FocusEvent) => any; + onerror: (ev: Event) => any; + /** + * Fires when the object receives focus. + */ + onfocus: (ev: FocusEvent) => any; + onhashchange: (ev: HashChangeEvent) => any; + onload: (ev: Event) => any; + onmessage: (ev: MessageEvent) => any; + onoffline: (ev: Event) => any; + ononline: (ev: Event) => any; + onorientationchange: (ev: Event) => any; + onpagehide: (ev: PageTransitionEvent) => any; + onpageshow: (ev: PageTransitionEvent) => any; + onresize: (ev: UIEvent) => any; + onstorage: (ev: StorageEvent) => any; + onunload: (ev: Event) => any; + /** + * Sets or retrieves the frame heights of the object. + */ + rows: string; + addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: HashChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "orientationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLFrameSetElement: { + prototype: HTMLFrameSetElement; + new(): HTMLFrameSetElement; +} + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves whether the horizontal rule is drawn with 3-D shading. + */ + noShade: boolean; + /** + * Sets or retrieves the width of the object. + */ + width: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +} + +interface HTMLHeadElement extends HTMLElement { + profile: string; +} + +declare var HTMLHeadElement: { + prototype: HTMLHeadElement; + new(): HTMLHeadElement; +} + +interface HTMLHeadingElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + clear: string; +} + +declare var HTMLHeadingElement: { + prototype: HTMLHeadingElement; + new(): HTMLHeadingElement; +} + +interface HTMLHtmlElement extends HTMLElement { + /** + * Sets or retrieves the DTD version that governs the current document. + */ + version: string; +} + +declare var HTMLHtmlElement: { + prototype: HTMLHtmlElement; + new(): HTMLHtmlElement; +} + +interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + allowFullscreen: boolean; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves the document object of the page or frame. + */ + contentDocument: Document; + /** + * Retrieves the object of the specified. + */ + contentWindow: Window; + /** + * Sets or retrieves whether to display a border for the frame. + */ + frameBorder: string; + /** + * Sets or retrieves the amount of additional space between the frames. + */ + frameSpacing: any; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the horizontal margin for the object. + */ + hspace: number; + /** + * Sets or retrieves a URI to a long description of the object. + */ + longDesc: string; + /** + * Sets or retrieves the top and bottom margin heights before displaying the text in a frame. + */ + marginHeight: string; + /** + * Sets or retrieves the left and right margin widths before displaying the text in a frame. + */ + marginWidth: string; + /** + * Sets or retrieves the frame name. + */ + name: string; + /** + * Sets or retrieves whether the user can resize the frame. + */ + noResize: boolean; + /** + * Raised when the object has been completely received from the server. + */ + onload: (ev: Event) => any; + sandbox: DOMSettableTokenList; + /** + * Sets or retrieves whether the frame can be scrolled. + */ + scrolling: string; + /** + * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied. + */ + security: any; + /** + * Sets or retrieves a URL to be loaded by the object. + */ + src: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLIFrameElement: { + prototype: HTMLIFrameElement; + new(): HTMLIFrameElement; +} + +interface HTMLImageElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies the properties of a border drawn around an object. + */ + border: string; + /** + * Retrieves whether the object is fully loaded. + */ + complete: boolean; + crossOrigin: string; + currentSrc: string; + /** + * Sets or retrieves the height of the object. + */ + height: number; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + /** + * Sets or retrieves whether the image is a server-side image map. + */ + isMap: boolean; + /** + * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object. + */ + longDesc: string; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * The original height of the image resource before sizing. + */ + naturalHeight: number; + /** + * The original width of the image resource before sizing. + */ + naturalWidth: number; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + srcset: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: number; + x: number; + y: number; + msGetAsCastingSource(): any; +} + +declare var HTMLImageElement: { + prototype: HTMLImageElement; + new(): HTMLImageElement; + create(): HTMLImageElement; +} + +interface HTMLInputElement extends HTMLElement { + /** + * Sets or retrieves a comma-separated list of content types. + */ + accept: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Specifies whether autocomplete is applied to an editable text field. + */ + autocomplete: string; + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the state of the check box or radio button. + */ + checked: boolean; + /** + * Retrieves whether the object is fully loaded. + */ + complete: boolean; + /** + * Sets or retrieves the state of the check box or radio button. + */ + defaultChecked: boolean; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + disabled: boolean; + /** + * Returns a FileList object on a file type input object. + */ + files: FileList; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Overrides the action attribute (where the data on a form is sent) on the parent form element. + */ + formAction: string; + /** + * Used to override the encoding (formEnctype attribute) specified on the form element. + */ + formEnctype: string; + /** + * Overrides the submit method attribute previously specified on a form element. + */ + formMethod: string; + /** + * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a "save draft"-type submit option. + */ + formNoValidate: string; + /** + * Overrides the target attribute on a form element. + */ + formTarget: string; + /** + * Sets or retrieves the height of the object. + */ + height: string; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + hspace: number; + indeterminate: boolean; + /** + * Specifies the ID of a pre-defined datalist of options for an input element. + */ + list: HTMLElement; + /** + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + */ + max: string; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + */ + min: string; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a string containing a regular expression that the user's input must match. + */ + pattern: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + size: number; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + status: boolean; + /** + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + */ + step: string; + /** + * Returns the content type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Returns the value of the data at the cursor's current position. + */ + value: string; + valueAsDate: Date; + /** + * Returns the input field value as a number. + */ + valueAsNumber: number; + /** + * Sets or retrieves the vertical margin for the object. + */ + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Creates a TextRange object for the element. + */ + createTextRange(): TextRange; + /** + * Makes the selection equal to the current object. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start: number, end: number): void; + /** + * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. + * @param n Value to decrement the value by. + */ + stepDown(n?: number): void; + /** + * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value. + * @param n Value to increment the value by. + */ + stepUp(n?: number): void; +} + +declare var HTMLInputElement: { + prototype: HTMLInputElement; + new(): HTMLInputElement; +} + +interface HTMLIsIndexElement extends HTMLElement { + /** + * Sets or retrieves the URL to which the form content is sent for processing. + */ + action: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + prompt: string; +} + +declare var HTMLIsIndexElement: { + prototype: HTMLIsIndexElement; + new(): HTMLIsIndexElement; +} + +interface HTMLLIElement extends HTMLElement { + type: string; + /** + * Sets or retrieves the value of a list item. + */ + value: number; +} + +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +} + +interface HTMLLabelElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the object to which the given label object is assigned. + */ + htmlFor: string; +} + +declare var HTMLLabelElement: { + prototype: HTMLLabelElement; + new(): HTMLLabelElement; +} + +interface HTMLLegendElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + align: string; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; +} + +declare var HTMLLegendElement: { + prototype: HTMLLegendElement; + new(): HTMLLegendElement; +} + +interface HTMLLinkElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + disabled: boolean; + /** + * Sets or retrieves a destination URL or an anchor point. + */ + href: string; + /** + * Sets or retrieves the language code of the object. + */ + hreflang: string; + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rel: string; + /** + * Sets or retrieves the relationship between the object and the destination of the link. + */ + rev: string; + /** + * Sets or retrieves the window or frame at which to target content. + */ + target: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLLinkElement: { + prototype: HTMLLinkElement; + new(): HTMLLinkElement; +} + +interface HTMLMapElement extends HTMLElement { + /** + * Retrieves a collection of the area objects defined for the given map object. + */ + areas: HTMLAreasCollection; + /** + * Sets or retrieves the name of the object. + */ + name: string; +} + +declare var HTMLMapElement: { + prototype: HTMLMapElement; + new(): HTMLMapElement; +} + +interface HTMLMarqueeElement extends HTMLElement { + behavior: string; + bgColor: any; + direction: string; + height: string; + hspace: number; + loop: number; + onbounce: (ev: Event) => any; + onfinish: (ev: Event) => any; + onstart: (ev: Event) => any; + scrollAmount: number; + scrollDelay: number; + trueSpeed: boolean; + vspace: number; + width: string; + start(): void; + stop(): void; + addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "bounce", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "finish", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "start", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMarqueeElement: { + prototype: HTMLMarqueeElement; + new(): HTMLMarqueeElement; +} + +interface HTMLMediaElement extends HTMLElement { + /** + * Returns an AudioTrackList object with the audio tracks for a given video element. + */ + audioTracks: AudioTrackList; + /** + * Gets or sets a value that indicates whether to start playing the media automatically. + */ + autoplay: boolean; + /** + * Gets a collection of buffered time ranges. + */ + buffered: TimeRanges; + /** + * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player). + */ + controls: boolean; + /** + * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement. + */ + currentSrc: string; + /** + * Gets or sets the current playback position, in seconds. + */ + currentTime: number; + defaultMuted: boolean; + /** + * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource. + */ + defaultPlaybackRate: number; + /** + * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming. + */ + duration: number; + /** + * Gets information about whether the playback has ended or not. + */ + ended: boolean; + /** + * Returns an object representing the current error state of the audio or video element. + */ + error: MediaError; + /** + * Gets or sets a flag to specify whether playback should restart after it completes. + */ + loop: boolean; + /** + * Specifies the purpose of the audio or video media, such as background audio or alerts. + */ + msAudioCategory: string; + /** + * Specifies the output device id that the audio will be sent to. + */ + msAudioDeviceType: string; + msGraphicsTrustStatus: MSGraphicsTrust; + /** + * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element. + */ + msKeys: MSMediaKeys; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; + /** + * Specifies whether or not to enable low-latency playback on the media element. + */ + msRealTime: boolean; + /** + * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted. + */ + muted: boolean; + /** + * Gets the current network activity for the element. + */ + networkState: number; + onmsneedkey: (ev: MSMediaKeyNeededEvent) => any; + /** + * Gets a flag that specifies whether playback is paused. + */ + paused: boolean; + /** + * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource. + */ + playbackRate: number; + /** + * Gets TimeRanges for the current media resource that has been played. + */ + played: TimeRanges; + /** + * Gets or sets the current playback position, in seconds. + */ + preload: string; + readyState: number; + /** + * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked. + */ + seekable: TimeRanges; + /** + * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + */ + seeking: boolean; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + textTracks: TextTrackList; + videoTracks: VideoTrackList; + /** + * Gets or sets the volume level for audio portions of the media element. + */ + volume: number; + addTextTrack(kind: string, label?: string, language?: string): TextTrack; + /** + * Returns a string that specifies whether the client can play a given media resource type. + */ + canPlayType(type: string): string; + /** + * Fires immediately after the client loads the object. + */ + load(): void; + /** + * Clears all effects from the media pipeline. + */ + msClearEffects(): void; + msGetAsCastingSource(): any; + /** + * Inserts the specified audio effect into media pipeline. + */ + msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetMediaKeys(mediaKeys: MSMediaKeys): void; + /** + * Specifies the media protection manager for a given media pipeline. + */ + msSetMediaProtectionManager(mediaProtectionManager?: any): void; + /** + * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not. + */ + pause(): void; + /** + * Loads and starts playback of a media resource. + */ + play(): void; + HAVE_CURRENT_DATA: number; + HAVE_ENOUGH_DATA: number; + HAVE_FUTURE_DATA: number; + HAVE_METADATA: number; + HAVE_NOTHING: number; + NETWORK_EMPTY: number; + NETWORK_IDLE: number; + NETWORK_LOADING: number; + NETWORK_NO_SOURCE: number; + addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLMediaElement: { + prototype: HTMLMediaElement; + new(): HTMLMediaElement; + HAVE_CURRENT_DATA: number; + HAVE_ENOUGH_DATA: number; + HAVE_FUTURE_DATA: number; + HAVE_METADATA: number; + HAVE_NOTHING: number; + NETWORK_EMPTY: number; + NETWORK_IDLE: number; + NETWORK_LOADING: number; + NETWORK_NO_SOURCE: number; +} + +interface HTMLMenuElement extends HTMLElement { + compact: boolean; + type: string; +} + +declare var HTMLMenuElement: { + prototype: HTMLMenuElement; + new(): HTMLMenuElement; +} + +interface HTMLMetaElement extends HTMLElement { + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Gets or sets meta-information to associate with httpEquiv or name. + */ + content: string; + /** + * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header. + */ + httpEquiv: string; + /** + * Sets or retrieves the value specified in the content attribute of the meta object. + */ + name: string; + /** + * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object. + */ + scheme: string; + /** + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + */ + url: string; +} + +declare var HTMLMetaElement: { + prototype: HTMLMetaElement; + new(): HTMLMetaElement; +} + +interface HTMLModElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; +} + +declare var HTMLModElement: { + prototype: HTMLModElement; + new(): HTMLModElement; +} + +interface HTMLNextIdElement extends HTMLElement { + n: string; +} + +declare var HTMLNextIdElement: { + prototype: HTMLNextIdElement; + new(): HTMLNextIdElement; +} + +interface HTMLOListElement extends HTMLElement { + compact: boolean; + /** + * The starting number. + */ + start: number; + type: string; +} + +declare var HTMLOListElement: { + prototype: HTMLOListElement; + new(): HTMLOListElement; +} + +interface HTMLObjectElement extends HTMLElement, GetSVGDocument { + /** + * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element. + */ + BaseHref: string; + align: string; + /** + * Sets or retrieves a text alternative to the graphic. + */ + alt: string; + /** + * Gets or sets the optional alternative HTML script to execute if the object fails to load. + */ + altHtml: string; + /** + * Sets or retrieves a character string that can be used to implement your own archive functionality for the object. + */ + archive: string; + border: string; + /** + * Sets or retrieves the URL of the file containing the compiled Java class. + */ + code: string; + /** + * Sets or retrieves the URL of the component. + */ + codeBase: string; + /** + * Sets or retrieves the Internet media type for the code associated with the object. + */ + codeType: string; + /** + * Retrieves the document object of the page or frame. + */ + contentDocument: Document; + /** + * Sets or retrieves the URL that references the data of the object. + */ + data: string; + declare: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the height of the object. + */ + height: string; + hspace: number; + /** + * Gets or sets whether the DLNA PlayTo device is available. + */ + msPlayToDisabled: boolean; + /** + * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server. + */ + msPlayToPreferredSourceUri: string; + /** + * Gets or sets the primary DLNA PlayTo device. + */ + msPlayToPrimary: boolean; + /** + * Gets the source associated with the media element for use by the PlayToManager. + */ + msPlayToSource: any; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Retrieves the contained object. + */ + object: any; + readyState: number; + /** + * Sets or retrieves a message to be displayed while an object is loading. + */ + standby: string; + /** + * Sets or retrieves the MIME type of the object. + */ + type: string; + /** + * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map. + */ + useMap: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + vspace: number; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +} + +interface HTMLOptGroupElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; +} + +declare var HTMLOptGroupElement: { + prototype: HTMLOptGroupElement; + new(): HTMLOptGroupElement; +} + +interface HTMLOptionElement extends HTMLElement { + /** + * Sets or retrieves the status of an option. + */ + defaultSelected: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the ordinal position of an option in a list box. + */ + index: number; + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + */ + label: string; + /** + * Sets or retrieves whether the option in the list box is the default item. + */ + selected: boolean; + /** + * Sets or retrieves the text string specified by the option tag. + */ + text: string; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; +} + +declare var HTMLOptionElement: { + prototype: HTMLOptionElement; + new(): HTMLOptionElement; + create(): HTMLOptionElement; +} + +interface HTMLParagraphElement extends HTMLElement { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + clear: string; +} + +declare var HTMLParagraphElement: { + prototype: HTMLParagraphElement; + new(): HTMLParagraphElement; +} + +interface HTMLParamElement extends HTMLElement { + /** + * Sets or retrieves the name of an input parameter for an element. + */ + name: string; + /** + * Sets or retrieves the content type of the resource designated by the value attribute. + */ + type: string; + /** + * Sets or retrieves the value of an input parameter for an element. + */ + value: string; + /** + * Sets or retrieves the data type of the value attribute. + */ + valueType: string; +} + +declare var HTMLParamElement: { + prototype: HTMLParamElement; + new(): HTMLParamElement; +} + +interface HTMLPhraseElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; +} + +declare var HTMLPhraseElement: { + prototype: HTMLPhraseElement; + new(): HTMLPhraseElement; +} + +interface HTMLPreElement extends HTMLElement { + /** + * Indicates a citation by rendering text in italic type. + */ + cite: string; + clear: string; + /** + * Sets or gets a value that you can use to implement your own width functionality for the object. + */ + width: number; +} + +declare var HTMLPreElement: { + prototype: HTMLPreElement; + new(): HTMLPreElement; +} + +interface HTMLProgressElement extends HTMLElement { + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Defines the maximum, or "done" value for a progress element. + */ + max: number; + /** + * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar). + */ + position: number; + /** + * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value. + */ + value: number; +} + +declare var HTMLProgressElement: { + prototype: HTMLProgressElement; + new(): HTMLProgressElement; +} + +interface HTMLQuoteElement extends HTMLElement { + /** + * Sets or retrieves reference information about the object. + */ + cite: string; + /** + * Sets or retrieves the date and time of a modification to the object. + */ + dateTime: string; +} + +declare var HTMLQuoteElement: { + prototype: HTMLQuoteElement; + new(): HTMLQuoteElement; +} + +interface HTMLScriptElement extends HTMLElement { + async: boolean; + /** + * Sets or retrieves the character set used to encode the object. + */ + charset: string; + /** + * Sets or retrieves the status of the script. + */ + defer: boolean; + /** + * Sets or retrieves the event for which the script is written. + */ + event: string; + /** + * Sets or retrieves the object that is bound to the event script. + */ + htmlFor: string; + /** + * Retrieves the URL to an external file that contains the source code or data. + */ + src: string; + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; + /** + * Sets or retrieves the MIME type for the associated scripting engine. + */ + type: string; +} + +declare var HTMLScriptElement: { + prototype: HTMLScriptElement; + new(): HTMLScriptElement; +} + +interface HTMLSelectElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the number of objects in a collection. + */ + length: number; + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + */ + multiple: boolean; + /** + * Sets or retrieves the name of the object. + */ + name: string; + options: HTMLCollection; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the index of the selected option in a select object. + */ + selectedIndex: number; + /** + * Sets or retrieves the number of rows in the list box. + */ + size: number; + /** + * Retrieves the type of select control based on the value of the MULTIPLE attribute. + */ + type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + selectedOptions: HTMLCollection; + /** + * Adds an element to the areas, controlRange, or options collection. + * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + */ + add(element: HTMLElement, before?: HTMLElement | number): void; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Retrieves a select object or an object from an options collection. + * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made. + * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned. + */ + item(name?: any, index?: any): any; + /** + * Retrieves a select object or an object from an options collection. + * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made. + */ + namedItem(name: string): any; + /** + * Removes an element from the collection. + * @param index Number that specifies the zero-based index of the element to remove from the collection. + */ + remove(index?: number): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + [name: string]: any; +} + +declare var HTMLSelectElement: { + prototype: HTMLSelectElement; + new(): HTMLSelectElement; +} + +interface HTMLSourceElement extends HTMLElement { + /** + * Gets or sets the intended media type of the media source. + */ + media: string; + msKeySystem: string; + /** + * The address or URL of the a media resource that is to be considered. + */ + src: string; + /** + * Gets or sets the MIME type of a media resource. + */ + type: string; +} + +declare var HTMLSourceElement: { + prototype: HTMLSourceElement; + new(): HTMLSourceElement; +} + +interface HTMLSpanElement extends HTMLElement { +} + +declare var HTMLSpanElement: { + prototype: HTMLSpanElement; + new(): HTMLSpanElement; +} + +interface HTMLStyleElement extends HTMLElement, LinkStyle { + /** + * Sets or retrieves the media type. + */ + media: string; + /** + * Retrieves the CSS language in which the style sheet is written. + */ + type: string; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLStyleElement: { + prototype: HTMLStyleElement; + new(): HTMLStyleElement; +} + +interface HTMLTableCaptionElement extends HTMLElement { + /** + * Sets or retrieves the alignment of the caption or legend. + */ + align: string; + /** + * Sets or retrieves whether the caption appears at the top or bottom of the table. + */ + vAlign: string; +} + +declare var HTMLTableCaptionElement: { + prototype: HTMLTableCaptionElement; + new(): HTMLTableCaptionElement; +} + +interface HTMLTableCellElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves abbreviated text for the object. + */ + abbr: string; + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + /** + * Sets or retrieves a comma-delimited list of conceptual categories associated with the object. + */ + axis: string; + bgColor: any; + /** + * Retrieves the position of the object in the cells collection of a row. + */ + cellIndex: number; + /** + * Sets or retrieves the number columns in the table that the object should span. + */ + colSpan: number; + /** + * Sets or retrieves a list of header cells that provide information for the object. + */ + headers: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves whether the browser automatically performs wordwrap. + */ + noWrap: boolean; + /** + * Sets or retrieves how many rows in a table the cell should span. + */ + rowSpan: number; + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; + /** + * Sets or retrieves the width of the object. + */ + width: string; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableCellElement: { + prototype: HTMLTableCellElement; + new(): HTMLTableCellElement; +} + +interface HTMLTableColElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves the alignment of the object relative to the display or table. + */ + align: string; + /** + * Sets or retrieves the number of columns in the group. + */ + span: number; + /** + * Sets or retrieves the width of the object. + */ + width: any; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableColElement: { + prototype: HTMLTableColElement; + new(): HTMLTableColElement; +} + +interface HTMLTableDataCellElement extends HTMLTableCellElement { +} + +declare var HTMLTableDataCellElement: { + prototype: HTMLTableDataCellElement; + new(): HTMLTableDataCellElement; +} + +interface HTMLTableElement extends HTMLElement { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + bgColor: any; + /** + * Sets or retrieves the width of the border to draw around the object. + */ + border: string; + /** + * Sets or retrieves the border color of the object. + */ + borderColor: any; + /** + * Retrieves the caption object of a table. + */ + caption: HTMLTableCaptionElement; + /** + * Sets or retrieves the amount of space between the border of the cell and the content of the cell. + */ + cellPadding: string; + /** + * Sets or retrieves the amount of space between cells in a table. + */ + cellSpacing: string; + /** + * Sets or retrieves the number of columns in the table. + */ + cols: number; + /** + * Sets or retrieves the way the border frame around the table is displayed. + */ + frame: string; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollection; + /** + * Sets or retrieves which dividing lines (inner borders) are displayed. + */ + rules: string; + /** + * Sets or retrieves a description and/or structure of the object. + */ + summary: string; + /** + * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order. + */ + tBodies: HTMLCollection; + /** + * Retrieves the tFoot object of the table. + */ + tFoot: HTMLTableSectionElement; + /** + * Retrieves the tHead object of the table. + */ + tHead: HTMLTableSectionElement; + /** + * Sets or retrieves the width of the object. + */ + width: string; + /** + * Creates an empty caption element in the table. + */ + createCaption(): HTMLTableCaptionElement; + /** + * Creates an empty tBody element in the table. + */ + createTBody(): HTMLTableSectionElement; + /** + * Creates an empty tFoot element in the table. + */ + createTFoot(): HTMLTableSectionElement; + /** + * Returns the tHead element object if successful, or null otherwise. + */ + createTHead(): HTMLTableSectionElement; + /** + * Deletes the caption element and its contents from the table. + */ + deleteCaption(): void; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Deletes the tFoot element and its contents from the table. + */ + deleteTFoot(): void; + /** + * Deletes the tHead element and its contents from the table. + */ + deleteTHead(): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; +} + +declare var HTMLTableElement: { + prototype: HTMLTableElement; + new(): HTMLTableElement; +} + +interface HTMLTableHeaderCellElement extends HTMLTableCellElement { + /** + * Sets or retrieves the group of cells in a table to which the object's information applies. + */ + scope: string; +} + +declare var HTMLTableHeaderCellElement: { + prototype: HTMLTableHeaderCellElement; + new(): HTMLTableHeaderCellElement; +} + +interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves how the object is aligned with adjacent text. + */ + align: string; + bgColor: any; + /** + * Retrieves a collection of all cells in the table row. + */ + cells: HTMLCollection; + /** + * Sets or retrieves the height of the object. + */ + height: any; + /** + * Retrieves the position of the object in the rows collection for the table. + */ + rowIndex: number; + /** + * Retrieves the position of the object in the collection. + */ + sectionRowIndex: number; + /** + * Removes the specified cell from the table row, as well as from the cells collection. + * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted. + */ + deleteCell(index?: number): void; + /** + * Creates a new cell in the table row, and adds the cell to the cells collection. + * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection. + */ + insertCell(index?: number): HTMLTableCellElement; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableRowElement: { + prototype: HTMLTableRowElement; + new(): HTMLTableRowElement; +} + +interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { + /** + * Sets or retrieves a value that indicates the table alignment. + */ + align: string; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: HTMLCollection; + /** + * Removes the specified row (tr) from the element and from the rows collection. + * @param index Number that specifies the zero-based position in the rows collection of the row to remove. + */ + deleteRow(index?: number): void; + /** + * Creates a new row (tr) in the table, and adds the row to the rows collection. + * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection. + */ + insertRow(index?: number): HTMLTableRowElement; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLTableSectionElement: { + prototype: HTMLTableSectionElement; + new(): HTMLTableSectionElement; +} + +interface HTMLTextAreaElement extends HTMLElement { + /** + * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing. + */ + autofocus: boolean; + /** + * Sets or retrieves the width of the object. + */ + cols: number; + /** + * Sets or retrieves the initial contents of the object. + */ + defaultValue: string; + disabled: boolean; + /** + * Retrieves a reference to the form that the object is embedded in. + */ + form: HTMLFormElement; + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + */ + maxLength: number; + /** + * Sets or retrieves the name of the object. + */ + name: string; + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + */ + placeholder: string; + /** + * Sets or retrieves the value indicated whether the content of the object is read-only. + */ + readOnly: boolean; + /** + * When present, marks an element that can't be submitted without a value. + */ + required: boolean; + /** + * Sets or retrieves the number of horizontal rows contained in the object. + */ + rows: number; + /** + * Gets or sets the end position or offset of a text selection. + */ + selectionEnd: number; + /** + * Gets or sets the starting position or offset of a text selection. + */ + selectionStart: number; + /** + * Sets or retrieves the value indicating whether the control is selected. + */ + status: any; + /** + * Retrieves the type of control. + */ + type: string; + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + */ + validationMessage: string; + /** + * Returns a ValidityState object that represents the validity states of an element. + */ + validity: ValidityState; + /** + * Retrieves or sets the text in the entry field of the textArea element. + */ + value: string; + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + */ + willValidate: boolean; + /** + * Sets or retrieves how to handle wordwrapping in the object. + */ + wrap: string; + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + */ + checkValidity(): boolean; + /** + * Creates a TextRange object for the element. + */ + createTextRange(): TextRange; + /** + * Highlights the input area of a form element. + */ + select(): void; + /** + * Sets a custom error message that is displayed when a form is submitted. + * @param error Sets a custom error message that is displayed when a form is submitted. + */ + setCustomValidity(error: string): void; + /** + * Sets the start and end positions of a selection in a text field. + * @param start The offset into the text field for the start of the selection. + * @param end The offset into the text field for the end of the selection. + */ + setSelectionRange(start: number, end: number): void; +} + +declare var HTMLTextAreaElement: { + prototype: HTMLTextAreaElement; + new(): HTMLTextAreaElement; +} + +interface HTMLTitleElement extends HTMLElement { + /** + * Retrieves or sets the text of the object as a string. + */ + text: string; +} + +declare var HTMLTitleElement: { + prototype: HTMLTitleElement; + new(): HTMLTitleElement; +} + +interface HTMLTrackElement extends HTMLElement { + default: boolean; + kind: string; + label: string; + readyState: number; + src: string; + srclang: string; + track: TextTrack; + ERROR: number; + LOADED: number; + LOADING: number; + NONE: number; +} + +declare var HTMLTrackElement: { + prototype: HTMLTrackElement; + new(): HTMLTrackElement; + ERROR: number; + LOADED: number; + LOADING: number; + NONE: number; +} + +interface HTMLUListElement extends HTMLElement { + compact: boolean; + type: string; +} + +declare var HTMLUListElement: { + prototype: HTMLUListElement; + new(): HTMLUListElement; +} + +interface HTMLUnknownElement extends HTMLElement { +} + +declare var HTMLUnknownElement: { + prototype: HTMLUnknownElement; + new(): HTMLUnknownElement; +} + +interface HTMLVideoElement extends HTMLMediaElement { + /** + * Gets or sets the height of the video element. + */ + height: number; + msHorizontalMirror: boolean; + msIsLayoutOptimalForPlayback: boolean; + msIsStereo3D: boolean; + msStereo3DPackingMode: string; + msStereo3DRenderMode: string; + msZoom: boolean; + onMSVideoFormatChanged: (ev: Event) => any; + onMSVideoFrameStepCompleted: (ev: Event) => any; + onMSVideoOptimalLayoutChanged: (ev: Event) => any; + /** + * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available. + */ + poster: string; + /** + * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known. + */ + videoHeight: number; + /** + * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known. + */ + videoWidth: number; + webkitDisplayingFullscreen: boolean; + webkitSupportsFullscreen: boolean; + /** + * Gets or sets the width of the video element. + */ + width: number; + getVideoPlaybackQuality(): VideoPlaybackQuality; + msFrameStep(forward: boolean): void; + msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void; + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + webkitEnterFullScreen(): void; + webkitEnterFullscreen(): void; + webkitExitFullScreen(): void; + webkitExitFullscreen(): void; + addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoFormatChanged", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoFrameStepCompleted", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "MSVideoOptimalLayoutChanged", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "msneedkey", listener: (ev: MSMediaKeyNeededEvent) => any, useCapture?: boolean): void; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var HTMLVideoElement: { + prototype: HTMLVideoElement; + new(): HTMLVideoElement; +} + +interface HashChangeEvent extends Event { + newURL: string; + oldURL: string; +} + +declare var HashChangeEvent: { + prototype: HashChangeEvent; + new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent; +} + +interface History { + length: number; + state: any; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): void; + pushState(statedata: any, title?: string, url?: string): void; + replaceState(statedata: any, title?: string, url?: string): void; +} + +declare var History: { + prototype: History; + new(): History; +} + +interface IDBCursor { + direction: string; + key: any; + primaryKey: any; + source: IDBObjectStore | IDBIndex; + advance(count: number): void; + continue(key?: any): void; + delete(): IDBRequest; + update(value: any): IDBRequest; + NEXT: string; + NEXT_NO_DUPLICATE: string; + PREV: string; + PREV_NO_DUPLICATE: string; +} + +declare var IDBCursor: { + prototype: IDBCursor; + new(): IDBCursor; + NEXT: string; + NEXT_NO_DUPLICATE: string; + PREV: string; + PREV_NO_DUPLICATE: string; +} + +interface IDBCursorWithValue extends IDBCursor { + value: any; +} + +declare var IDBCursorWithValue: { + prototype: IDBCursorWithValue; + new(): IDBCursorWithValue; +} + +interface IDBDatabase extends EventTarget { + name: string; + objectStoreNames: DOMStringList; + onabort: (ev: Event) => any; + onerror: (ev: Event) => any; + version: number; + close(): void; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; + deleteObjectStore(name: string): void; + transaction(storeNames: string | string[], mode?: string): IDBTransaction; + addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBDatabase: { + prototype: IDBDatabase; + new(): IDBDatabase; +} + +interface IDBFactory { + cmp(first: any, second: any): number; + deleteDatabase(name: string): IDBOpenDBRequest; + open(name: string, version?: number): IDBOpenDBRequest; +} + +declare var IDBFactory: { + prototype: IDBFactory; + new(): IDBFactory; +} + +interface IDBIndex { + keyPath: string | string[]; + name: string; + objectStore: IDBObjectStore; + unique: boolean; + multiEntry: boolean; + count(key?: any): IDBRequest; + get(key: any): IDBRequest; + getKey(key: any): IDBRequest; + openCursor(range?: IDBKeyRange, direction?: string): IDBRequest; + openKeyCursor(range?: IDBKeyRange, direction?: string): IDBRequest; +} + +declare var IDBIndex: { + prototype: IDBIndex; + new(): IDBIndex; +} + +interface IDBKeyRange { + lower: any; + lowerOpen: boolean; + upper: any; + upperOpen: boolean; +} + +declare var IDBKeyRange: { + prototype: IDBKeyRange; + new(): IDBKeyRange; + bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange; + lowerBound(bound: any, open?: boolean): IDBKeyRange; + only(value: any): IDBKeyRange; + upperBound(bound: any, open?: boolean): IDBKeyRange; +} + +interface IDBObjectStore { + indexNames: DOMStringList; + keyPath: string | string[]; + name: string; + transaction: IDBTransaction; + autoIncrement: boolean; + add(value: any, key?: any): IDBRequest; + clear(): IDBRequest; + count(key?: any): IDBRequest; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; + delete(key: any): IDBRequest; + deleteIndex(indexName: string): void; + get(key: any): IDBRequest; + index(name: string): IDBIndex; + openCursor(range?: any, direction?: string): IDBRequest; + put(value: any, key?: any): IDBRequest; +} + +declare var IDBObjectStore: { + prototype: IDBObjectStore; + new(): IDBObjectStore; +} + +interface IDBOpenDBRequest extends IDBRequest { + onblocked: (ev: Event) => any; + onupgradeneeded: (ev: IDBVersionChangeEvent) => any; + addEventListener(type: "blocked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "upgradeneeded", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBOpenDBRequest: { + prototype: IDBOpenDBRequest; + new(): IDBOpenDBRequest; +} + +interface IDBRequest extends EventTarget { + error: DOMError; + onerror: (ev: Event) => any; + onsuccess: (ev: Event) => any; + readyState: string; + result: any; + source: IDBObjectStore | IDBIndex | IDBCursor; + transaction: IDBTransaction; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBRequest: { + prototype: IDBRequest; + new(): IDBRequest; +} + +interface IDBTransaction extends EventTarget { + db: IDBDatabase; + error: DOMError; + mode: string; + onabort: (ev: Event) => any; + oncomplete: (ev: Event) => any; + onerror: (ev: Event) => any; + abort(): void; + objectStore(name: string): IDBObjectStore; + READ_ONLY: string; + READ_WRITE: string; + VERSION_CHANGE: string; + addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var IDBTransaction: { + prototype: IDBTransaction; + new(): IDBTransaction; + READ_ONLY: string; + READ_WRITE: string; + VERSION_CHANGE: string; +} + +interface IDBVersionChangeEvent extends Event { + newVersion: number; + oldVersion: number; +} + +declare var IDBVersionChangeEvent: { + prototype: IDBVersionChangeEvent; + new(): IDBVersionChangeEvent; +} + +interface ImageData { + data: Uint8ClampedArray; + height: number; + width: number; +} + +declare var ImageData: { + prototype: ImageData; + new(width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height: number): ImageData; +} + +interface KeyboardEvent extends UIEvent { + altKey: boolean; + char: string; + charCode: number; + ctrlKey: boolean; + key: string; + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + repeat: boolean; + shiftKey: boolean; + which: number; + getModifierState(keyArg: string): boolean; + initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void; + DOM_KEY_LOCATION_JOYSTICK: number; + DOM_KEY_LOCATION_LEFT: number; + DOM_KEY_LOCATION_MOBILE: number; + DOM_KEY_LOCATION_NUMPAD: number; + DOM_KEY_LOCATION_RIGHT: number; + DOM_KEY_LOCATION_STANDARD: number; +} + +declare var KeyboardEvent: { + prototype: KeyboardEvent; + new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent; + DOM_KEY_LOCATION_JOYSTICK: number; + DOM_KEY_LOCATION_LEFT: number; + DOM_KEY_LOCATION_MOBILE: number; + DOM_KEY_LOCATION_NUMPAD: number; + DOM_KEY_LOCATION_RIGHT: number; + DOM_KEY_LOCATION_STANDARD: number; +} + +interface Location { + hash: string; + host: string; + hostname: string; + href: string; + origin: string; + pathname: string; + port: string; + protocol: string; + search: string; + assign(url: string): void; + reload(forcedReload?: boolean): void; + replace(url: string): void; + toString(): string; +} + +declare var Location: { + prototype: Location; + new(): Location; +} + +interface LongRunningScriptDetectedEvent extends Event { + executionTime: number; + stopPageScriptExecution: boolean; +} + +declare var LongRunningScriptDetectedEvent: { + prototype: LongRunningScriptDetectedEvent; + new(): LongRunningScriptDetectedEvent; +} + +interface MSApp { + clearTemporaryWebDataAsync(): MSAppAsyncOperation; + createBlobFromRandomAccessStream(type: string, seeker: any): Blob; + createDataPackage(object: any): any; + createDataPackageFromSelection(): any; + createFileFromStorageFile(storageFile: any): File; + createStreamFromInputStream(type: string, inputStream: any): MSStream; + execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void; + execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any; + getCurrentPriority(): string; + getHtmlPrintDocumentSourceAsync(htmlDoc: any): any; + getViewId(view: any): any; + isTaskScheduledAtPriorityOrHigher(priority: string): boolean; + pageHandlesAllApplicationActivations(enabled: boolean): void; + suppressSubdownloadCredentialPrompts(suppress: boolean): void; + terminateApp(exceptionObject: any): void; + CURRENT: string; + HIGH: string; + IDLE: string; + NORMAL: string; +} +declare var MSApp: MSApp; + +interface MSAppAsyncOperation extends EventTarget { + error: DOMError; + oncomplete: (ev: Event) => any; + onerror: (ev: Event) => any; + readyState: number; + result: any; + start(): void; + COMPLETED: number; + ERROR: number; + STARTED: number; + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSAppAsyncOperation: { + prototype: MSAppAsyncOperation; + new(): MSAppAsyncOperation; + COMPLETED: number; + ERROR: number; + STARTED: number; +} + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} + +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new(): MSBlobBuilder; +} + +interface MSCSSMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + m11: number; + m12: number; + m13: number; + m14: number; + m21: number; + m22: number; + m23: number; + m24: number; + m31: number; + m32: number; + m33: number; + m34: number; + m41: number; + m42: number; + m43: number; + m44: number; + inverse(): MSCSSMatrix; + multiply(secondMatrix: MSCSSMatrix): MSCSSMatrix; + rotate(angleX: number, angleY?: number, angleZ?: number): MSCSSMatrix; + rotateAxisAngle(x: number, y: number, z: number, angle: number): MSCSSMatrix; + scale(scaleX: number, scaleY?: number, scaleZ?: number): MSCSSMatrix; + setMatrixValue(value: string): void; + skewX(angle: number): MSCSSMatrix; + skewY(angle: number): MSCSSMatrix; + toString(): string; + translate(x: number, y: number, z?: number): MSCSSMatrix; +} + +declare var MSCSSMatrix: { + prototype: MSCSSMatrix; + new(text?: string): MSCSSMatrix; +} + +interface MSGesture { + target: Element; + addPointer(pointerId: number): void; + stop(): void; +} + +declare var MSGesture: { + prototype: MSGesture; + new(): MSGesture; +} + +interface MSGestureEvent extends UIEvent { + clientX: number; + clientY: number; + expansion: number; + gestureObject: any; + hwTimestamp: number; + offsetX: number; + offsetY: number; + rotation: number; + scale: number; + screenX: number; + screenY: number; + translationX: number; + translationY: number; + velocityAngular: number; + velocityExpansion: number; + velocityX: number; + velocityY: number; + initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; + MSGESTURE_FLAG_BEGIN: number; + MSGESTURE_FLAG_CANCEL: number; + MSGESTURE_FLAG_END: number; + MSGESTURE_FLAG_INERTIA: number; + MSGESTURE_FLAG_NONE: number; +} + +declare var MSGestureEvent: { + prototype: MSGestureEvent; + new(): MSGestureEvent; + MSGESTURE_FLAG_BEGIN: number; + MSGESTURE_FLAG_CANCEL: number; + MSGESTURE_FLAG_END: number; + MSGESTURE_FLAG_INERTIA: number; + MSGESTURE_FLAG_NONE: number; +} + +interface MSGraphicsTrust { + constrictionActive: boolean; + status: string; +} + +declare var MSGraphicsTrust: { + prototype: MSGraphicsTrust; + new(): MSGraphicsTrust; +} + +interface MSHTMLWebViewElement extends HTMLElement { + canGoBack: boolean; + canGoForward: boolean; + containsFullScreenElement: boolean; + documentTitle: string; + height: number; + settings: MSWebViewSettings; + src: string; + width: number; + addWebAllowedObject(name: string, applicationObject: any): void; + buildLocalStreamUri(contentIdentifier: string, relativePath: string): string; + capturePreviewToBlobAsync(): MSWebViewAsyncOperation; + captureSelectedContentToDataPackageAsync(): MSWebViewAsyncOperation; + getDeferredPermissionRequestById(id: number): DeferredPermissionRequest; + getDeferredPermissionRequests(): DeferredPermissionRequest[]; + goBack(): void; + goForward(): void; + invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation; + navigate(uri: string): void; + navigateToLocalStreamUri(source: string, streamResolver: any): void; + navigateToString(contents: string): void; + navigateWithHttpRequestMessage(requestMessage: any): void; + refresh(): void; + stop(): void; +} + +declare var MSHTMLWebViewElement: { + prototype: MSHTMLWebViewElement; + new(): MSHTMLWebViewElement; +} + +interface MSInputMethodContext extends EventTarget { + compositionEndOffset: number; + compositionStartOffset: number; + oncandidatewindowhide: (ev: Event) => any; + oncandidatewindowshow: (ev: Event) => any; + oncandidatewindowupdate: (ev: Event) => any; + target: HTMLElement; + getCandidateWindowClientRect(): ClientRect; + getCompositionAlternatives(): string[]; + hasComposition(): boolean; + isCandidateWindowVisible(): boolean; + addEventListener(type: "MSCandidateWindowHide", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "MSCandidateWindowShow", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "MSCandidateWindowUpdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSInputMethodContext: { + prototype: MSInputMethodContext; + new(): MSInputMethodContext; +} + +interface MSManipulationEvent extends UIEvent { + currentState: number; + inertiaDestinationX: number; + inertiaDestinationY: number; + lastState: number; + initMSManipulationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, lastState: number, currentState: number): void; + MS_MANIPULATION_STATE_ACTIVE: number; + MS_MANIPULATION_STATE_CANCELLED: number; + MS_MANIPULATION_STATE_COMMITTED: number; + MS_MANIPULATION_STATE_DRAGGING: number; + MS_MANIPULATION_STATE_INERTIA: number; + MS_MANIPULATION_STATE_PRESELECT: number; + MS_MANIPULATION_STATE_SELECTING: number; + MS_MANIPULATION_STATE_STOPPED: number; +} + +declare var MSManipulationEvent: { + prototype: MSManipulationEvent; + new(): MSManipulationEvent; + MS_MANIPULATION_STATE_ACTIVE: number; + MS_MANIPULATION_STATE_CANCELLED: number; + MS_MANIPULATION_STATE_COMMITTED: number; + MS_MANIPULATION_STATE_DRAGGING: number; + MS_MANIPULATION_STATE_INERTIA: number; + MS_MANIPULATION_STATE_PRESELECT: number; + MS_MANIPULATION_STATE_SELECTING: number; + MS_MANIPULATION_STATE_STOPPED: number; +} + +interface MSMediaKeyError { + code: number; + systemCode: number; + MS_MEDIA_KEYERR_CLIENT: number; + MS_MEDIA_KEYERR_DOMAIN: number; + MS_MEDIA_KEYERR_HARDWARECHANGE: number; + MS_MEDIA_KEYERR_OUTPUT: number; + MS_MEDIA_KEYERR_SERVICE: number; + MS_MEDIA_KEYERR_UNKNOWN: number; +} + +declare var MSMediaKeyError: { + prototype: MSMediaKeyError; + new(): MSMediaKeyError; + MS_MEDIA_KEYERR_CLIENT: number; + MS_MEDIA_KEYERR_DOMAIN: number; + MS_MEDIA_KEYERR_HARDWARECHANGE: number; + MS_MEDIA_KEYERR_OUTPUT: number; + MS_MEDIA_KEYERR_SERVICE: number; + MS_MEDIA_KEYERR_UNKNOWN: number; +} + +interface MSMediaKeyMessageEvent extends Event { + destinationURL: string; + message: Uint8Array; +} + +declare var MSMediaKeyMessageEvent: { + prototype: MSMediaKeyMessageEvent; + new(): MSMediaKeyMessageEvent; +} + +interface MSMediaKeyNeededEvent extends Event { + initData: Uint8Array; +} + +declare var MSMediaKeyNeededEvent: { + prototype: MSMediaKeyNeededEvent; + new(): MSMediaKeyNeededEvent; +} + +interface MSMediaKeySession extends EventTarget { + error: MSMediaKeyError; + keySystem: string; + sessionId: string; + close(): void; + update(key: Uint8Array): void; +} + +declare var MSMediaKeySession: { + prototype: MSMediaKeySession; + new(): MSMediaKeySession; +} + +interface MSMediaKeys { + keySystem: string; + createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array): MSMediaKeySession; +} + +declare var MSMediaKeys: { + prototype: MSMediaKeys; + new(keySystem: string): MSMediaKeys; + isTypeSupported(keySystem: string, type?: string): boolean; +} + +interface MSMimeTypesCollection { + length: number; +} + +declare var MSMimeTypesCollection: { + prototype: MSMimeTypesCollection; + new(): MSMimeTypesCollection; +} + +interface MSPluginsCollection { + length: number; + refresh(reload?: boolean): void; +} + +declare var MSPluginsCollection: { + prototype: MSPluginsCollection; + new(): MSPluginsCollection; +} + +interface MSPointerEvent extends MouseEvent { + currentPoint: any; + height: number; + hwTimestamp: number; + intermediatePoints: any; + isPrimary: boolean; + pointerId: number; + pointerType: any; + pressure: number; + rotation: number; + tiltX: number; + tiltY: number; + width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var MSPointerEvent: { + prototype: MSPointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; +} + +interface MSRangeCollection { + length: number; + item(index: number): Range; + [index: number]: Range; +} + +declare var MSRangeCollection: { + prototype: MSRangeCollection; + new(): MSRangeCollection; +} + +interface MSSiteModeEvent extends Event { + actionURL: string; + buttonID: number; +} + +declare var MSSiteModeEvent: { + prototype: MSSiteModeEvent; + new(): MSSiteModeEvent; +} + +interface MSStream { + type: string; + msClose(): void; + msDetachStream(): any; +} + +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +} + +interface MSStreamReader extends EventTarget, MSBaseReader { + error: DOMError; + readAsArrayBuffer(stream: MSStream, size?: number): void; + readAsBinaryString(stream: MSStream, size?: number): void; + readAsBlob(stream: MSStream, size?: number): void; + readAsDataURL(stream: MSStream, size?: number): void; + readAsText(stream: MSStream, encoding?: string, size?: number): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSStreamReader: { + prototype: MSStreamReader; + new(): MSStreamReader; +} + +interface MSWebViewAsyncOperation extends EventTarget { + error: DOMError; + oncomplete: (ev: Event) => any; + onerror: (ev: Event) => any; + readyState: number; + result: any; + target: MSHTMLWebViewElement; + type: number; + start(): void; + COMPLETED: number; + ERROR: number; + STARTED: number; + TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + TYPE_INVOKE_SCRIPT: number; + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MSWebViewAsyncOperation: { + prototype: MSWebViewAsyncOperation; + new(): MSWebViewAsyncOperation; + COMPLETED: number; + ERROR: number; + STARTED: number; + TYPE_CAPTURE_PREVIEW_TO_RANDOM_ACCESS_STREAM: number; + TYPE_CREATE_DATA_PACKAGE_FROM_SELECTION: number; + TYPE_INVOKE_SCRIPT: number; +} + +interface MSWebViewSettings { + isIndexedDBEnabled: boolean; + isJavaScriptEnabled: boolean; +} + +declare var MSWebViewSettings: { + prototype: MSWebViewSettings; + new(): MSWebViewSettings; +} + +interface MediaElementAudioSourceNode extends AudioNode { +} + +declare var MediaElementAudioSourceNode: { + prototype: MediaElementAudioSourceNode; + new(): MediaElementAudioSourceNode; +} + +interface MediaError { + code: number; + msExtendedCode: number; + MEDIA_ERR_ABORTED: number; + MEDIA_ERR_DECODE: number; + MEDIA_ERR_NETWORK: number; + MEDIA_ERR_SRC_NOT_SUPPORTED: number; + MS_MEDIA_ERR_ENCRYPTED: number; +} + +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + MEDIA_ERR_ABORTED: number; + MEDIA_ERR_DECODE: number; + MEDIA_ERR_NETWORK: number; + MEDIA_ERR_SRC_NOT_SUPPORTED: number; + MS_MEDIA_ERR_ENCRYPTED: number; +} + +interface MediaList { + length: number; + mediaText: string; + appendMedium(newMedium: string): void; + deleteMedium(oldMedium: string): void; + item(index: number): string; + toString(): string; + [index: number]: string; +} + +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +} + +interface MediaQueryList { + matches: boolean; + media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} + +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +} + +interface MediaSource extends EventTarget { + activeSourceBuffers: SourceBufferList; + duration: number; + readyState: string; + sourceBuffers: SourceBufferList; + addSourceBuffer(type: string): SourceBuffer; + endOfStream(error?: number): void; + removeSourceBuffer(sourceBuffer: SourceBuffer): void; +} + +declare var MediaSource: { + prototype: MediaSource; + new(): MediaSource; + isTypeSupported(type: string): boolean; +} + +interface MessageChannel { + port1: MessagePort; + port2: MessagePort; +} + +declare var MessageChannel: { + prototype: MessageChannel; + new(): MessageChannel; +} + +interface MessageEvent extends Event { + data: any; + origin: string; + ports: any; + source: Window; + initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} + +declare var MessageEvent: { + prototype: MessageEvent; + new(type: string, eventInitDict?: MessageEventInit): MessageEvent; +} + +interface MessagePort extends EventTarget { + onmessage: (ev: MessageEvent) => any; + close(): void; + postMessage(message?: any, ports?: any): void; + start(): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +} + +interface MimeType { + description: string; + enabledPlugin: Plugin; + suffixes: string; + type: string; +} + +declare var MimeType: { + prototype: MimeType; + new(): MimeType; +} + +interface MimeTypeArray { + length: number; + item(index: number): Plugin; + namedItem(type: string): Plugin; + [index: number]: Plugin; +} + +declare var MimeTypeArray: { + prototype: MimeTypeArray; + new(): MimeTypeArray; +} + +interface MouseEvent extends UIEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + fromElement: Element; + layerX: number; + layerY: number; + metaKey: boolean; + movementX: number; + movementY: number; + offsetX: number; + offsetY: number; + pageX: number; + pageY: number; + relatedTarget: EventTarget; + screenX: number; + screenY: number; + shiftKey: boolean; + toElement: Element; + which: number; + x: number; + y: number; + getModifierState(keyArg: string): boolean; + initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void; +} + +declare var MouseEvent: { + prototype: MouseEvent; + new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent; +} + +interface MouseWheelEvent extends MouseEvent { + wheelDelta: number; + wheelDeltaX: number; + wheelDeltaY: number; + initMouseWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, wheelDeltaArg: number): void; +} + +declare var MouseWheelEvent: { + prototype: MouseWheelEvent; + new(): MouseWheelEvent; +} + +interface MutationEvent extends Event { + attrChange: number; + attrName: string; + newValue: string; + prevValue: string; + relatedNode: Node; + initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; + ADDITION: number; + MODIFICATION: number; + REMOVAL: number; +} + +declare var MutationEvent: { + prototype: MutationEvent; + new(): MutationEvent; + ADDITION: number; + MODIFICATION: number; + REMOVAL: number; +} + +interface MutationObserver { + disconnect(): void; + observe(target: Node, options: MutationObserverInit): void; + takeRecords(): MutationRecord[]; +} + +declare var MutationObserver: { + prototype: MutationObserver; + new(callback: MutationCallback): MutationObserver; +} + +interface MutationRecord { + addedNodes: NodeList; + attributeName: string; + attributeNamespace: string; + nextSibling: Node; + oldValue: string; + previousSibling: Node; + removedNodes: NodeList; + target: Node; + type: string; +} + +declare var MutationRecord: { + prototype: MutationRecord; + new(): MutationRecord; +} + +interface NamedNodeMap { + length: number; + getNamedItem(name: string): Attr; + getNamedItemNS(namespaceURI: string, localName: string): Attr; + item(index: number): Attr; + removeNamedItem(name: string): Attr; + removeNamedItemNS(namespaceURI: string, localName: string): Attr; + setNamedItem(arg: Attr): Attr; + setNamedItemNS(arg: Attr): Attr; + [index: number]: Attr; +} + +declare var NamedNodeMap: { + prototype: NamedNodeMap; + new(): NamedNodeMap; +} + +interface NavigationCompletedEvent extends NavigationEvent { + isSuccess: boolean; + webErrorStatus: number; +} + +declare var NavigationCompletedEvent: { + prototype: NavigationCompletedEvent; + new(): NavigationCompletedEvent; +} + +interface NavigationEvent extends Event { + uri: string; +} + +declare var NavigationEvent: { + prototype: NavigationEvent; + new(): NavigationEvent; +} + +interface NavigationEventWithReferrer extends NavigationEvent { + referer: string; +} + +declare var NavigationEventWithReferrer: { + prototype: NavigationEventWithReferrer; + new(): NavigationEventWithReferrer; +} + +interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver { + appCodeName: string; + appMinorVersion: string; + browserLanguage: string; + connectionSpeed: number; + cookieEnabled: boolean; + cpuClass: string; + language: string; + maxTouchPoints: number; + mimeTypes: MSMimeTypesCollection; + msManipulationViewsEnabled: boolean; + msMaxTouchPoints: number; + msPointerEnabled: boolean; + plugins: MSPluginsCollection; + pointerEnabled: boolean; + systemLanguage: string; + userLanguage: string; + webdriver: boolean; + getGamepads(): Gamepad[]; + javaEnabled(): boolean; + msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; + vibrate(pattern: number | number[]): boolean; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Navigator: { + prototype: Navigator; + new(): Navigator; +} + +interface Node extends EventTarget { + attributes: NamedNodeMap; + baseURI: string; + childNodes: NodeList; + firstChild: Node; + lastChild: Node; + localName: string; + namespaceURI: string; + nextSibling: Node; + nodeName: string; + nodeType: number; + nodeValue: string; + ownerDocument: Document; + parentElement: HTMLElement; + parentNode: Node; + prefix: string; + previousSibling: Node; + textContent: string; + appendChild(newChild: Node): Node; + cloneNode(deep?: boolean): Node; + compareDocumentPosition(other: Node): number; + hasAttributes(): boolean; + hasChildNodes(): boolean; + insertBefore(newChild: Node, refChild?: Node): Node; + isDefaultNamespace(namespaceURI: string): boolean; + isEqualNode(arg: Node): boolean; + isSameNode(other: Node): boolean; + lookupNamespaceURI(prefix: string): string; + lookupPrefix(namespaceURI: string): string; + normalize(): void; + removeChild(oldChild: Node): Node; + replaceChild(newChild: Node, oldChild: Node): Node; + contains(node: Node): boolean; + ATTRIBUTE_NODE: number; + CDATA_SECTION_NODE: number; + COMMENT_NODE: number; + DOCUMENT_FRAGMENT_NODE: number; + DOCUMENT_NODE: number; + DOCUMENT_POSITION_CONTAINED_BY: number; + DOCUMENT_POSITION_CONTAINS: number; + DOCUMENT_POSITION_DISCONNECTED: number; + DOCUMENT_POSITION_FOLLOWING: number; + DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + DOCUMENT_POSITION_PRECEDING: number; + DOCUMENT_TYPE_NODE: number; + ELEMENT_NODE: number; + ENTITY_NODE: number; + ENTITY_REFERENCE_NODE: number; + NOTATION_NODE: number; + PROCESSING_INSTRUCTION_NODE: number; + TEXT_NODE: number; +} + +declare var Node: { + prototype: Node; + new(): Node; + ATTRIBUTE_NODE: number; + CDATA_SECTION_NODE: number; + COMMENT_NODE: number; + DOCUMENT_FRAGMENT_NODE: number; + DOCUMENT_NODE: number; + DOCUMENT_POSITION_CONTAINED_BY: number; + DOCUMENT_POSITION_CONTAINS: number; + DOCUMENT_POSITION_DISCONNECTED: number; + DOCUMENT_POSITION_FOLLOWING: number; + DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + DOCUMENT_POSITION_PRECEDING: number; + DOCUMENT_TYPE_NODE: number; + ELEMENT_NODE: number; + ENTITY_NODE: number; + ENTITY_REFERENCE_NODE: number; + NOTATION_NODE: number; + PROCESSING_INSTRUCTION_NODE: number; + TEXT_NODE: number; +} + +interface NodeFilter { + acceptNode(n: Node): number; +} + +declare var NodeFilter: { + FILTER_ACCEPT: number; + FILTER_REJECT: number; + FILTER_SKIP: number; + SHOW_ALL: number; + SHOW_ATTRIBUTE: number; + SHOW_CDATA_SECTION: number; + SHOW_COMMENT: number; + SHOW_DOCUMENT: number; + SHOW_DOCUMENT_FRAGMENT: number; + SHOW_DOCUMENT_TYPE: number; + SHOW_ELEMENT: number; + SHOW_ENTITY: number; + SHOW_ENTITY_REFERENCE: number; + SHOW_NOTATION: number; + SHOW_PROCESSING_INSTRUCTION: number; + SHOW_TEXT: number; +} + +interface NodeIterator { + expandEntityReferences: boolean; + filter: NodeFilter; + root: Node; + whatToShow: number; + detach(): void; + nextNode(): Node; + previousNode(): Node; +} + +declare var NodeIterator: { + prototype: NodeIterator; + new(): NodeIterator; +} + +interface NodeList { + length: number; + item(index: number): Node; + [index: number]: Node; +} + +declare var NodeList: { + prototype: NodeList; + new(): NodeList; +} + +interface OES_element_index_uint { +} + +declare var OES_element_index_uint: { + prototype: OES_element_index_uint; + new(): OES_element_index_uint; +} + +interface OES_standard_derivatives { + FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +declare var OES_standard_derivatives: { + prototype: OES_standard_derivatives; + new(): OES_standard_derivatives; + FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number; +} + +interface OES_texture_float { +} + +declare var OES_texture_float: { + prototype: OES_texture_float; + new(): OES_texture_float; +} + +interface OES_texture_float_linear { +} + +declare var OES_texture_float_linear: { + prototype: OES_texture_float_linear; + new(): OES_texture_float_linear; +} + +interface OfflineAudioCompletionEvent extends Event { + renderedBuffer: AudioBuffer; +} + +declare var OfflineAudioCompletionEvent: { + prototype: OfflineAudioCompletionEvent; + new(): OfflineAudioCompletionEvent; +} + +interface OfflineAudioContext extends AudioContext { + oncomplete: (ev: Event) => any; + startRendering(): void; + addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var OfflineAudioContext: { + prototype: OfflineAudioContext; + new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; +} + +interface OscillatorNode extends AudioNode { + detune: AudioParam; + frequency: AudioParam; + onended: (ev: Event) => any; + type: string; + setPeriodicWave(periodicWave: PeriodicWave): void; + start(when?: number): void; + stop(when?: number): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var OscillatorNode: { + prototype: OscillatorNode; + new(): OscillatorNode; +} + +interface PageTransitionEvent extends Event { + persisted: boolean; +} + +declare var PageTransitionEvent: { + prototype: PageTransitionEvent; + new(): PageTransitionEvent; +} + +interface PannerNode extends AudioNode { + coneInnerAngle: number; + coneOuterAngle: number; + coneOuterGain: number; + distanceModel: string; + maxDistance: number; + panningModel: string; + refDistance: number; + rolloffFactor: number; + setOrientation(x: number, y: number, z: number): void; + setPosition(x: number, y: number, z: number): void; + setVelocity(x: number, y: number, z: number): void; +} + +declare var PannerNode: { + prototype: PannerNode; + new(): PannerNode; +} + +interface PerfWidgetExternal { + activeNetworkRequestCount: number; + averageFrameTime: number; + averagePaintTime: number; + extraInformationEnabled: boolean; + independentRenderingEnabled: boolean; + irDisablingContentString: string; + irStatusAvailable: boolean; + maxCpuSpeed: number; + paintRequestsPerSecond: number; + performanceCounter: number; + performanceCounterFrequency: number; + addEventListener(eventType: string, callback: Function): void; + getMemoryUsage(): number; + getProcessCpuUsage(): number; + getRecentCpuUsage(last: number): any; + getRecentFrames(last: number): any; + getRecentMemoryUsage(last: number): any; + getRecentPaintRequests(last: number): any; + removeEventListener(eventType: string, callback: Function): void; + repositionWindow(x: number, y: number): void; + resizeWindow(width: number, height: number): void; +} + +declare var PerfWidgetExternal: { + prototype: PerfWidgetExternal; + new(): PerfWidgetExternal; +} + +interface Performance { + navigation: PerformanceNavigation; + timing: PerformanceTiming; + clearMarks(markName?: string): void; + clearMeasures(measureName?: string): void; + clearResourceTimings(): void; + getEntries(): any; + getEntriesByName(name: string, entryType?: string): any; + getEntriesByType(entryType: string): any; + getMarks(markName?: string): any; + getMeasures(measureName?: string): any; + mark(markName: string): void; + measure(measureName: string, startMarkName?: string, endMarkName?: string): void; + now(): number; + setResourceTimingBufferSize(maxSize: number): void; + toJSON(): any; +} + +declare var Performance: { + prototype: Performance; + new(): Performance; +} + +interface PerformanceEntry { + duration: number; + entryType: string; + name: string; + startTime: number; +} + +declare var PerformanceEntry: { + prototype: PerformanceEntry; + new(): PerformanceEntry; +} + +interface PerformanceMark extends PerformanceEntry { +} + +declare var PerformanceMark: { + prototype: PerformanceMark; + new(): PerformanceMark; +} + +interface PerformanceMeasure extends PerformanceEntry { +} + +declare var PerformanceMeasure: { + prototype: PerformanceMeasure; + new(): PerformanceMeasure; +} + +interface PerformanceNavigation { + redirectCount: number; + type: number; + toJSON(): any; + TYPE_BACK_FORWARD: number; + TYPE_NAVIGATE: number; + TYPE_RELOAD: number; + TYPE_RESERVED: number; +} + +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + TYPE_BACK_FORWARD: number; + TYPE_NAVIGATE: number; + TYPE_RELOAD: number; + TYPE_RESERVED: number; +} + +interface PerformanceNavigationTiming extends PerformanceEntry { + connectEnd: number; + connectStart: number; + domComplete: number; + domContentLoadedEventEnd: number; + domContentLoadedEventStart: number; + domInteractive: number; + domLoading: number; + domainLookupEnd: number; + domainLookupStart: number; + fetchStart: number; + loadEventEnd: number; + loadEventStart: number; + navigationStart: number; + redirectCount: number; + redirectEnd: number; + redirectStart: number; + requestStart: number; + responseEnd: number; + responseStart: number; + type: string; + unloadEventEnd: number; + unloadEventStart: number; +} + +declare var PerformanceNavigationTiming: { + prototype: PerformanceNavigationTiming; + new(): PerformanceNavigationTiming; +} + +interface PerformanceResourceTiming extends PerformanceEntry { + connectEnd: number; + connectStart: number; + domainLookupEnd: number; + domainLookupStart: number; + fetchStart: number; + initiatorType: string; + redirectEnd: number; + redirectStart: number; + requestStart: number; + responseEnd: number; + responseStart: number; +} + +declare var PerformanceResourceTiming: { + prototype: PerformanceResourceTiming; + new(): PerformanceResourceTiming; +} + +interface PerformanceTiming { + connectEnd: number; + connectStart: number; + domComplete: number; + domContentLoadedEventEnd: number; + domContentLoadedEventStart: number; + domInteractive: number; + domLoading: number; + domainLookupEnd: number; + domainLookupStart: number; + fetchStart: number; + loadEventEnd: number; + loadEventStart: number; + msFirstPaint: number; + navigationStart: number; + redirectEnd: number; + redirectStart: number; + requestStart: number; + responseEnd: number; + responseStart: number; + unloadEventEnd: number; + unloadEventStart: number; + toJSON(): any; +} + +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +} + +interface PeriodicWave { +} + +declare var PeriodicWave: { + prototype: PeriodicWave; + new(): PeriodicWave; +} + +interface PermissionRequest extends DeferredPermissionRequest { + state: string; + defer(): void; +} + +declare var PermissionRequest: { + prototype: PermissionRequest; + new(): PermissionRequest; +} + +interface PermissionRequestedEvent extends Event { + permissionRequest: PermissionRequest; +} + +declare var PermissionRequestedEvent: { + prototype: PermissionRequestedEvent; + new(): PermissionRequestedEvent; +} + +interface Plugin { + description: string; + filename: string; + length: number; + name: string; + version: string; + item(index: number): MimeType; + namedItem(type: string): MimeType; + [index: number]: MimeType; +} + +declare var Plugin: { + prototype: Plugin; + new(): Plugin; +} + +interface PluginArray { + length: number; + item(index: number): Plugin; + namedItem(name: string): Plugin; + refresh(reload?: boolean): void; + [index: number]: Plugin; +} + +declare var PluginArray: { + prototype: PluginArray; + new(): PluginArray; +} + +interface PointerEvent extends MouseEvent { + currentPoint: any; + height: number; + hwTimestamp: number; + intermediatePoints: any; + isPrimary: boolean; + pointerId: number; + pointerType: any; + pressure: number; + rotation: number; + tiltX: number; + tiltY: number; + width: number; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; +} + +declare var PointerEvent: { + prototype: PointerEvent; + new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; +} + +interface PopStateEvent extends Event { + state: any; + initPopStateEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, stateArg: any): void; +} + +declare var PopStateEvent: { + prototype: PopStateEvent; + new(): PopStateEvent; +} + +interface Position { + coords: Coordinates; + timestamp: number; +} + +declare var Position: { + prototype: Position; + new(): Position; +} + +interface PositionError { + code: number; + message: string; + toString(): string; + PERMISSION_DENIED: number; + POSITION_UNAVAILABLE: number; + TIMEOUT: number; +} + +declare var PositionError: { + prototype: PositionError; + new(): PositionError; + PERMISSION_DENIED: number; + POSITION_UNAVAILABLE: number; + TIMEOUT: number; +} + +interface ProcessingInstruction extends CharacterData { + target: string; +} + +declare var ProcessingInstruction: { + prototype: ProcessingInstruction; + new(): ProcessingInstruction; +} + +interface ProgressEvent extends Event { + lengthComputable: boolean; + loaded: number; + total: number; + initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void; +} + +declare var ProgressEvent: { + prototype: ProgressEvent; + new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; +} + +interface Range { + collapsed: boolean; + commonAncestorContainer: Node; + endContainer: Node; + endOffset: number; + startContainer: Node; + startOffset: number; + cloneContents(): DocumentFragment; + cloneRange(): Range; + collapse(toStart: boolean): void; + compareBoundaryPoints(how: number, sourceRange: Range): number; + createContextualFragment(fragment: string): DocumentFragment; + deleteContents(): void; + detach(): void; + expand(Unit: string): boolean; + extractContents(): DocumentFragment; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + insertNode(newNode: Node): void; + selectNode(refNode: Node): void; + selectNodeContents(refNode: Node): void; + setEnd(refNode: Node, offset: number): void; + setEndAfter(refNode: Node): void; + setEndBefore(refNode: Node): void; + setStart(refNode: Node, offset: number): void; + setStartAfter(refNode: Node): void; + setStartBefore(refNode: Node): void; + surroundContents(newParent: Node): void; + toString(): string; + END_TO_END: number; + END_TO_START: number; + START_TO_END: number; + START_TO_START: number; +} + +declare var Range: { + prototype: Range; + new(): Range; + END_TO_END: number; + END_TO_START: number; + START_TO_END: number; + START_TO_START: number; +} + +interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + target: SVGAnimatedString; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGAElement: { + prototype: SVGAElement; + new(): SVGAElement; +} + +interface SVGAngle { + unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + SVG_ANGLETYPE_DEG: number; + SVG_ANGLETYPE_GRAD: number; + SVG_ANGLETYPE_RAD: number; + SVG_ANGLETYPE_UNKNOWN: number; + SVG_ANGLETYPE_UNSPECIFIED: number; +} + +declare var SVGAngle: { + prototype: SVGAngle; + new(): SVGAngle; + SVG_ANGLETYPE_DEG: number; + SVG_ANGLETYPE_GRAD: number; + SVG_ANGLETYPE_RAD: number; + SVG_ANGLETYPE_UNKNOWN: number; + SVG_ANGLETYPE_UNSPECIFIED: number; +} + +interface SVGAnimatedAngle { + animVal: SVGAngle; + baseVal: SVGAngle; +} + +declare var SVGAnimatedAngle: { + prototype: SVGAnimatedAngle; + new(): SVGAnimatedAngle; +} + +interface SVGAnimatedBoolean { + animVal: boolean; + baseVal: boolean; +} + +declare var SVGAnimatedBoolean: { + prototype: SVGAnimatedBoolean; + new(): SVGAnimatedBoolean; +} + +interface SVGAnimatedEnumeration { + animVal: number; + baseVal: number; +} + +declare var SVGAnimatedEnumeration: { + prototype: SVGAnimatedEnumeration; + new(): SVGAnimatedEnumeration; +} + +interface SVGAnimatedInteger { + animVal: number; + baseVal: number; +} + +declare var SVGAnimatedInteger: { + prototype: SVGAnimatedInteger; + new(): SVGAnimatedInteger; +} + +interface SVGAnimatedLength { + animVal: SVGLength; + baseVal: SVGLength; +} + +declare var SVGAnimatedLength: { + prototype: SVGAnimatedLength; + new(): SVGAnimatedLength; +} + +interface SVGAnimatedLengthList { + animVal: SVGLengthList; + baseVal: SVGLengthList; +} + +declare var SVGAnimatedLengthList: { + prototype: SVGAnimatedLengthList; + new(): SVGAnimatedLengthList; +} + +interface SVGAnimatedNumber { + animVal: number; + baseVal: number; +} + +declare var SVGAnimatedNumber: { + prototype: SVGAnimatedNumber; + new(): SVGAnimatedNumber; +} + +interface SVGAnimatedNumberList { + animVal: SVGNumberList; + baseVal: SVGNumberList; +} + +declare var SVGAnimatedNumberList: { + prototype: SVGAnimatedNumberList; + new(): SVGAnimatedNumberList; +} + +interface SVGAnimatedPreserveAspectRatio { + animVal: SVGPreserveAspectRatio; + baseVal: SVGPreserveAspectRatio; +} + +declare var SVGAnimatedPreserveAspectRatio: { + prototype: SVGAnimatedPreserveAspectRatio; + new(): SVGAnimatedPreserveAspectRatio; +} + +interface SVGAnimatedRect { + animVal: SVGRect; + baseVal: SVGRect; +} + +declare var SVGAnimatedRect: { + prototype: SVGAnimatedRect; + new(): SVGAnimatedRect; +} + +interface SVGAnimatedString { + animVal: string; + baseVal: string; +} + +declare var SVGAnimatedString: { + prototype: SVGAnimatedString; + new(): SVGAnimatedString; +} + +interface SVGAnimatedTransformList { + animVal: SVGTransformList; + baseVal: SVGTransformList; +} + +declare var SVGAnimatedTransformList: { + prototype: SVGAnimatedTransformList; + new(): SVGAnimatedTransformList; +} + +interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + cx: SVGAnimatedLength; + cy: SVGAnimatedLength; + r: SVGAnimatedLength; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGCircleElement: { + prototype: SVGCircleElement; + new(): SVGCircleElement; +} + +interface SVGClipPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { + clipPathUnits: SVGAnimatedEnumeration; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGClipPathElement: { + prototype: SVGClipPathElement; + new(): SVGClipPathElement; +} + +interface SVGComponentTransferFunctionElement extends SVGElement { + amplitude: SVGAnimatedNumber; + exponent: SVGAnimatedNumber; + intercept: SVGAnimatedNumber; + offset: SVGAnimatedNumber; + slope: SVGAnimatedNumber; + tableValues: SVGAnimatedNumberList; + type: SVGAnimatedEnumeration; + SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; +} + +declare var SVGComponentTransferFunctionElement: { + prototype: SVGComponentTransferFunctionElement; + new(): SVGComponentTransferFunctionElement; + SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; + SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; +} + +interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGDefsElement: { + prototype: SVGDefsElement; + new(): SVGDefsElement; +} + +interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGDescElement: { + prototype: SVGDescElement; + new(): SVGDescElement; +} + +interface SVGElement extends Element { + id: string; + onclick: (ev: MouseEvent) => any; + ondblclick: (ev: MouseEvent) => any; + onfocusin: (ev: FocusEvent) => any; + onfocusout: (ev: FocusEvent) => any; + onload: (ev: Event) => any; + onmousedown: (ev: MouseEvent) => any; + onmousemove: (ev: MouseEvent) => any; + onmouseout: (ev: MouseEvent) => any; + onmouseover: (ev: MouseEvent) => any; + onmouseup: (ev: MouseEvent) => any; + ownerSVGElement: SVGSVGElement; + viewportElement: SVGElement; + xmlbase: string; + className: any; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGElement: { + prototype: SVGElement; + new(): SVGElement; +} + +interface SVGElementInstance extends EventTarget { + childNodes: SVGElementInstanceList; + correspondingElement: SVGElement; + correspondingUseElement: SVGUseElement; + firstChild: SVGElementInstance; + lastChild: SVGElementInstance; + nextSibling: SVGElementInstance; + parentNode: SVGElementInstance; + previousSibling: SVGElementInstance; +} + +declare var SVGElementInstance: { + prototype: SVGElementInstance; + new(): SVGElementInstance; +} + +interface SVGElementInstanceList { + length: number; + item(index: number): SVGElementInstance; +} + +declare var SVGElementInstanceList: { + prototype: SVGElementInstanceList; + new(): SVGElementInstanceList; +} + +interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + cx: SVGAnimatedLength; + cy: SVGAnimatedLength; + rx: SVGAnimatedLength; + ry: SVGAnimatedLength; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGEllipseElement: { + prototype: SVGEllipseElement; + new(): SVGEllipseElement; +} + +interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + in2: SVGAnimatedString; + mode: SVGAnimatedEnumeration; + SVG_FEBLEND_MODE_COLOR: number; + SVG_FEBLEND_MODE_COLOR_BURN: number; + SVG_FEBLEND_MODE_COLOR_DODGE: number; + SVG_FEBLEND_MODE_DARKEN: number; + SVG_FEBLEND_MODE_DIFFERENCE: number; + SVG_FEBLEND_MODE_EXCLUSION: number; + SVG_FEBLEND_MODE_HARD_LIGHT: number; + SVG_FEBLEND_MODE_HUE: number; + SVG_FEBLEND_MODE_LIGHTEN: number; + SVG_FEBLEND_MODE_LUMINOSITY: number; + SVG_FEBLEND_MODE_MULTIPLY: number; + SVG_FEBLEND_MODE_NORMAL: number; + SVG_FEBLEND_MODE_OVERLAY: number; + SVG_FEBLEND_MODE_SATURATION: number; + SVG_FEBLEND_MODE_SCREEN: number; + SVG_FEBLEND_MODE_SOFT_LIGHT: number; + SVG_FEBLEND_MODE_UNKNOWN: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEBlendElement: { + prototype: SVGFEBlendElement; + new(): SVGFEBlendElement; + SVG_FEBLEND_MODE_COLOR: number; + SVG_FEBLEND_MODE_COLOR_BURN: number; + SVG_FEBLEND_MODE_COLOR_DODGE: number; + SVG_FEBLEND_MODE_DARKEN: number; + SVG_FEBLEND_MODE_DIFFERENCE: number; + SVG_FEBLEND_MODE_EXCLUSION: number; + SVG_FEBLEND_MODE_HARD_LIGHT: number; + SVG_FEBLEND_MODE_HUE: number; + SVG_FEBLEND_MODE_LIGHTEN: number; + SVG_FEBLEND_MODE_LUMINOSITY: number; + SVG_FEBLEND_MODE_MULTIPLY: number; + SVG_FEBLEND_MODE_NORMAL: number; + SVG_FEBLEND_MODE_OVERLAY: number; + SVG_FEBLEND_MODE_SATURATION: number; + SVG_FEBLEND_MODE_SCREEN: number; + SVG_FEBLEND_MODE_SOFT_LIGHT: number; + SVG_FEBLEND_MODE_UNKNOWN: number; +} + +interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + type: SVGAnimatedEnumeration; + values: SVGAnimatedNumberList; + SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + SVG_FECOLORMATRIX_TYPE_MATRIX: number; + SVG_FECOLORMATRIX_TYPE_SATURATE: number; + SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEColorMatrixElement: { + prototype: SVGFEColorMatrixElement; + new(): SVGFEColorMatrixElement; + SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; + SVG_FECOLORMATRIX_TYPE_MATRIX: number; + SVG_FECOLORMATRIX_TYPE_SATURATE: number; + SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; +} + +interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEComponentTransferElement: { + prototype: SVGFEComponentTransferElement; + new(): SVGFEComponentTransferElement; +} + +interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + in2: SVGAnimatedString; + k1: SVGAnimatedNumber; + k2: SVGAnimatedNumber; + k3: SVGAnimatedNumber; + k4: SVGAnimatedNumber; + operator: SVGAnimatedEnumeration; + SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + SVG_FECOMPOSITE_OPERATOR_ATOP: number; + SVG_FECOMPOSITE_OPERATOR_IN: number; + SVG_FECOMPOSITE_OPERATOR_OUT: number; + SVG_FECOMPOSITE_OPERATOR_OVER: number; + SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + SVG_FECOMPOSITE_OPERATOR_XOR: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFECompositeElement: { + prototype: SVGFECompositeElement; + new(): SVGFECompositeElement; + SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + SVG_FECOMPOSITE_OPERATOR_ATOP: number; + SVG_FECOMPOSITE_OPERATOR_IN: number; + SVG_FECOMPOSITE_OPERATOR_OUT: number; + SVG_FECOMPOSITE_OPERATOR_OVER: number; + SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + SVG_FECOMPOSITE_OPERATOR_XOR: number; +} + +interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + bias: SVGAnimatedNumber; + divisor: SVGAnimatedNumber; + edgeMode: SVGAnimatedEnumeration; + in1: SVGAnimatedString; + kernelMatrix: SVGAnimatedNumberList; + kernelUnitLengthX: SVGAnimatedNumber; + kernelUnitLengthY: SVGAnimatedNumber; + orderX: SVGAnimatedInteger; + orderY: SVGAnimatedInteger; + preserveAlpha: SVGAnimatedBoolean; + targetX: SVGAnimatedInteger; + targetY: SVGAnimatedInteger; + SVG_EDGEMODE_DUPLICATE: number; + SVG_EDGEMODE_NONE: number; + SVG_EDGEMODE_UNKNOWN: number; + SVG_EDGEMODE_WRAP: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEConvolveMatrixElement: { + prototype: SVGFEConvolveMatrixElement; + new(): SVGFEConvolveMatrixElement; + SVG_EDGEMODE_DUPLICATE: number; + SVG_EDGEMODE_NONE: number; + SVG_EDGEMODE_UNKNOWN: number; + SVG_EDGEMODE_WRAP: number; +} + +interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + diffuseConstant: SVGAnimatedNumber; + in1: SVGAnimatedString; + kernelUnitLengthX: SVGAnimatedNumber; + kernelUnitLengthY: SVGAnimatedNumber; + surfaceScale: SVGAnimatedNumber; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDiffuseLightingElement: { + prototype: SVGFEDiffuseLightingElement; + new(): SVGFEDiffuseLightingElement; +} + +interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + in2: SVGAnimatedString; + scale: SVGAnimatedNumber; + xChannelSelector: SVGAnimatedEnumeration; + yChannelSelector: SVGAnimatedEnumeration; + SVG_CHANNEL_A: number; + SVG_CHANNEL_B: number; + SVG_CHANNEL_G: number; + SVG_CHANNEL_R: number; + SVG_CHANNEL_UNKNOWN: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEDisplacementMapElement: { + prototype: SVGFEDisplacementMapElement; + new(): SVGFEDisplacementMapElement; + SVG_CHANNEL_A: number; + SVG_CHANNEL_B: number; + SVG_CHANNEL_G: number; + SVG_CHANNEL_R: number; + SVG_CHANNEL_UNKNOWN: number; +} + +interface SVGFEDistantLightElement extends SVGElement { + azimuth: SVGAnimatedNumber; + elevation: SVGAnimatedNumber; +} + +declare var SVGFEDistantLightElement: { + prototype: SVGFEDistantLightElement; + new(): SVGFEDistantLightElement; +} + +interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEFloodElement: { + prototype: SVGFEFloodElement; + new(): SVGFEFloodElement; +} + +interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncAElement: { + prototype: SVGFEFuncAElement; + new(): SVGFEFuncAElement; +} + +interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncBElement: { + prototype: SVGFEFuncBElement; + new(): SVGFEFuncBElement; +} + +interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncGElement: { + prototype: SVGFEFuncGElement; + new(): SVGFEFuncGElement; +} + +interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { +} + +declare var SVGFEFuncRElement: { + prototype: SVGFEFuncRElement; + new(): SVGFEFuncRElement; +} + +interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + stdDeviationX: SVGAnimatedNumber; + stdDeviationY: SVGAnimatedNumber; + setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEGaussianBlurElement: { + prototype: SVGFEGaussianBlurElement; + new(): SVGFEGaussianBlurElement; +} + +interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEImageElement: { + prototype: SVGFEImageElement; + new(): SVGFEImageElement; +} + +interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMergeElement: { + prototype: SVGFEMergeElement; + new(): SVGFEMergeElement; +} + +interface SVGFEMergeNodeElement extends SVGElement { + in1: SVGAnimatedString; +} + +declare var SVGFEMergeNodeElement: { + prototype: SVGFEMergeNodeElement; + new(): SVGFEMergeNodeElement; +} + +interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + operator: SVGAnimatedEnumeration; + radiusX: SVGAnimatedNumber; + radiusY: SVGAnimatedNumber; + SVG_MORPHOLOGY_OPERATOR_DILATE: number; + SVG_MORPHOLOGY_OPERATOR_ERODE: number; + SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEMorphologyElement: { + prototype: SVGFEMorphologyElement; + new(): SVGFEMorphologyElement; + SVG_MORPHOLOGY_OPERATOR_DILATE: number; + SVG_MORPHOLOGY_OPERATOR_ERODE: number; + SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; +} + +interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + dx: SVGAnimatedNumber; + dy: SVGAnimatedNumber; + in1: SVGAnimatedString; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFEOffsetElement: { + prototype: SVGFEOffsetElement; + new(): SVGFEOffsetElement; +} + +interface SVGFEPointLightElement extends SVGElement { + x: SVGAnimatedNumber; + y: SVGAnimatedNumber; + z: SVGAnimatedNumber; +} + +declare var SVGFEPointLightElement: { + prototype: SVGFEPointLightElement; + new(): SVGFEPointLightElement; +} + +interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + kernelUnitLengthX: SVGAnimatedNumber; + kernelUnitLengthY: SVGAnimatedNumber; + specularConstant: SVGAnimatedNumber; + specularExponent: SVGAnimatedNumber; + surfaceScale: SVGAnimatedNumber; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFESpecularLightingElement: { + prototype: SVGFESpecularLightingElement; + new(): SVGFESpecularLightingElement; +} + +interface SVGFESpotLightElement extends SVGElement { + limitingConeAngle: SVGAnimatedNumber; + pointsAtX: SVGAnimatedNumber; + pointsAtY: SVGAnimatedNumber; + pointsAtZ: SVGAnimatedNumber; + specularExponent: SVGAnimatedNumber; + x: SVGAnimatedNumber; + y: SVGAnimatedNumber; + z: SVGAnimatedNumber; +} + +declare var SVGFESpotLightElement: { + prototype: SVGFESpotLightElement; + new(): SVGFESpotLightElement; +} + +interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFETileElement: { + prototype: SVGFETileElement; + new(): SVGFETileElement; +} + +interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + baseFrequencyX: SVGAnimatedNumber; + baseFrequencyY: SVGAnimatedNumber; + numOctaves: SVGAnimatedInteger; + seed: SVGAnimatedNumber; + stitchTiles: SVGAnimatedEnumeration; + type: SVGAnimatedEnumeration; + SVG_STITCHTYPE_NOSTITCH: number; + SVG_STITCHTYPE_STITCH: number; + SVG_STITCHTYPE_UNKNOWN: number; + SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + SVG_TURBULENCE_TYPE_TURBULENCE: number; + SVG_TURBULENCE_TYPE_UNKNOWN: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFETurbulenceElement: { + prototype: SVGFETurbulenceElement; + new(): SVGFETurbulenceElement; + SVG_STITCHTYPE_NOSTITCH: number; + SVG_STITCHTYPE_STITCH: number; + SVG_STITCHTYPE_UNKNOWN: number; + SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + SVG_TURBULENCE_TYPE_TURBULENCE: number; + SVG_TURBULENCE_TYPE_UNKNOWN: number; +} + +interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference, SVGExternalResourcesRequired { + filterResX: SVGAnimatedInteger; + filterResY: SVGAnimatedInteger; + filterUnits: SVGAnimatedEnumeration; + height: SVGAnimatedLength; + primitiveUnits: SVGAnimatedEnumeration; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + y: SVGAnimatedLength; + setFilterRes(filterResX: number, filterResY: number): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGFilterElement: { + prototype: SVGFilterElement; + new(): SVGFilterElement; +} + +interface SVGForeignObjectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + height: SVGAnimatedLength; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + y: SVGAnimatedLength; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGForeignObjectElement: { + prototype: SVGForeignObjectElement; + new(): SVGForeignObjectElement; +} + +interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGGElement: { + prototype: SVGGElement; + new(): SVGGElement; +} + +interface SVGGradientElement extends SVGElement, SVGStylable, SVGExternalResourcesRequired, SVGURIReference, SVGUnitTypes { + gradientTransform: SVGAnimatedTransformList; + gradientUnits: SVGAnimatedEnumeration; + spreadMethod: SVGAnimatedEnumeration; + SVG_SPREADMETHOD_PAD: number; + SVG_SPREADMETHOD_REFLECT: number; + SVG_SPREADMETHOD_REPEAT: number; + SVG_SPREADMETHOD_UNKNOWN: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGGradientElement: { + prototype: SVGGradientElement; + new(): SVGGradientElement; + SVG_SPREADMETHOD_PAD: number; + SVG_SPREADMETHOD_REFLECT: number; + SVG_SPREADMETHOD_REPEAT: number; + SVG_SPREADMETHOD_UNKNOWN: number; +} + +interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + height: SVGAnimatedLength; + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + y: SVGAnimatedLength; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGImageElement: { + prototype: SVGImageElement; + new(): SVGImageElement; +} + +interface SVGLength { + unitType: number; + value: number; + valueAsString: string; + valueInSpecifiedUnits: number; + convertToSpecifiedUnits(unitType: number): void; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + SVG_LENGTHTYPE_CM: number; + SVG_LENGTHTYPE_EMS: number; + SVG_LENGTHTYPE_EXS: number; + SVG_LENGTHTYPE_IN: number; + SVG_LENGTHTYPE_MM: number; + SVG_LENGTHTYPE_NUMBER: number; + SVG_LENGTHTYPE_PC: number; + SVG_LENGTHTYPE_PERCENTAGE: number; + SVG_LENGTHTYPE_PT: number; + SVG_LENGTHTYPE_PX: number; + SVG_LENGTHTYPE_UNKNOWN: number; +} + +declare var SVGLength: { + prototype: SVGLength; + new(): SVGLength; + SVG_LENGTHTYPE_CM: number; + SVG_LENGTHTYPE_EMS: number; + SVG_LENGTHTYPE_EXS: number; + SVG_LENGTHTYPE_IN: number; + SVG_LENGTHTYPE_MM: number; + SVG_LENGTHTYPE_NUMBER: number; + SVG_LENGTHTYPE_PC: number; + SVG_LENGTHTYPE_PERCENTAGE: number; + SVG_LENGTHTYPE_PT: number; + SVG_LENGTHTYPE_PX: number; + SVG_LENGTHTYPE_UNKNOWN: number; +} + +interface SVGLengthList { + numberOfItems: number; + appendItem(newItem: SVGLength): SVGLength; + clear(): void; + getItem(index: number): SVGLength; + initialize(newItem: SVGLength): SVGLength; + insertItemBefore(newItem: SVGLength, index: number): SVGLength; + removeItem(index: number): SVGLength; + replaceItem(newItem: SVGLength, index: number): SVGLength; +} + +declare var SVGLengthList: { + prototype: SVGLengthList; + new(): SVGLengthList; +} + +interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + x1: SVGAnimatedLength; + x2: SVGAnimatedLength; + y1: SVGAnimatedLength; + y2: SVGAnimatedLength; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +} + +interface SVGLinearGradientElement extends SVGGradientElement { + x1: SVGAnimatedLength; + x2: SVGAnimatedLength; + y1: SVGAnimatedLength; + y2: SVGAnimatedLength; +} + +declare var SVGLinearGradientElement: { + prototype: SVGLinearGradientElement; + new(): SVGLinearGradientElement; +} + +interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { + markerHeight: SVGAnimatedLength; + markerUnits: SVGAnimatedEnumeration; + markerWidth: SVGAnimatedLength; + orientAngle: SVGAnimatedAngle; + orientType: SVGAnimatedEnumeration; + refX: SVGAnimatedLength; + refY: SVGAnimatedLength; + setOrientToAngle(angle: SVGAngle): void; + setOrientToAuto(): void; + SVG_MARKERUNITS_STROKEWIDTH: number; + SVG_MARKERUNITS_UNKNOWN: number; + SVG_MARKERUNITS_USERSPACEONUSE: number; + SVG_MARKER_ORIENT_ANGLE: number; + SVG_MARKER_ORIENT_AUTO: number; + SVG_MARKER_ORIENT_UNKNOWN: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMarkerElement: { + prototype: SVGMarkerElement; + new(): SVGMarkerElement; + SVG_MARKERUNITS_STROKEWIDTH: number; + SVG_MARKERUNITS_UNKNOWN: number; + SVG_MARKERUNITS_USERSPACEONUSE: number; + SVG_MARKER_ORIENT_ANGLE: number; + SVG_MARKER_ORIENT_AUTO: number; + SVG_MARKER_ORIENT_UNKNOWN: number; +} + +interface SVGMaskElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGUnitTypes { + height: SVGAnimatedLength; + maskContentUnits: SVGAnimatedEnumeration; + maskUnits: SVGAnimatedEnumeration; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + y: SVGAnimatedLength; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGMaskElement: { + prototype: SVGMaskElement; + new(): SVGMaskElement; +} + +interface SVGMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + flipX(): SVGMatrix; + flipY(): SVGMatrix; + inverse(): SVGMatrix; + multiply(secondMatrix: SVGMatrix): SVGMatrix; + rotate(angle: number): SVGMatrix; + rotateFromVector(x: number, y: number): SVGMatrix; + scale(scaleFactor: number): SVGMatrix; + scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; + skewX(angle: number): SVGMatrix; + skewY(angle: number): SVGMatrix; + translate(x: number, y: number): SVGMatrix; +} + +declare var SVGMatrix: { + prototype: SVGMatrix; + new(): SVGMatrix; +} + +interface SVGMetadataElement extends SVGElement { +} + +declare var SVGMetadataElement: { + prototype: SVGMetadataElement; + new(): SVGMetadataElement; +} + +interface SVGNumber { + value: number; +} + +declare var SVGNumber: { + prototype: SVGNumber; + new(): SVGNumber; +} + +interface SVGNumberList { + numberOfItems: number; + appendItem(newItem: SVGNumber): SVGNumber; + clear(): void; + getItem(index: number): SVGNumber; + initialize(newItem: SVGNumber): SVGNumber; + insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; + removeItem(index: number): SVGNumber; + replaceItem(newItem: SVGNumber, index: number): SVGNumber; +} + +declare var SVGNumberList: { + prototype: SVGNumberList; + new(): SVGNumberList; +} + +interface SVGPathElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPathData { + createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; + createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; + createSVGPathSegClosePath(): SVGPathSegClosePath; + createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + getPathSegAtLength(distance: number): number; + getPointAtLength(distance: number): SVGPoint; + getTotalLength(): number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPathElement: { + prototype: SVGPathElement; + new(): SVGPathElement; +} + +interface SVGPathSeg { + pathSegType: number; + pathSegTypeAsLetter: string; + PATHSEG_ARC_ABS: number; + PATHSEG_ARC_REL: number; + PATHSEG_CLOSEPATH: number; + PATHSEG_CURVETO_CUBIC_ABS: number; + PATHSEG_CURVETO_CUBIC_REL: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + PATHSEG_CURVETO_QUADRATIC_ABS: number; + PATHSEG_CURVETO_QUADRATIC_REL: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + PATHSEG_LINETO_ABS: number; + PATHSEG_LINETO_HORIZONTAL_ABS: number; + PATHSEG_LINETO_HORIZONTAL_REL: number; + PATHSEG_LINETO_REL: number; + PATHSEG_LINETO_VERTICAL_ABS: number; + PATHSEG_LINETO_VERTICAL_REL: number; + PATHSEG_MOVETO_ABS: number; + PATHSEG_MOVETO_REL: number; + PATHSEG_UNKNOWN: number; +} + +declare var SVGPathSeg: { + prototype: SVGPathSeg; + new(): SVGPathSeg; + PATHSEG_ARC_ABS: number; + PATHSEG_ARC_REL: number; + PATHSEG_CLOSEPATH: number; + PATHSEG_CURVETO_CUBIC_ABS: number; + PATHSEG_CURVETO_CUBIC_REL: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + PATHSEG_CURVETO_QUADRATIC_ABS: number; + PATHSEG_CURVETO_QUADRATIC_REL: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; + PATHSEG_LINETO_ABS: number; + PATHSEG_LINETO_HORIZONTAL_ABS: number; + PATHSEG_LINETO_HORIZONTAL_REL: number; + PATHSEG_LINETO_REL: number; + PATHSEG_LINETO_VERTICAL_ABS: number; + PATHSEG_LINETO_VERTICAL_REL: number; + PATHSEG_MOVETO_ABS: number; + PATHSEG_MOVETO_REL: number; + PATHSEG_UNKNOWN: number; +} + +interface SVGPathSegArcAbs extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcAbs: { + prototype: SVGPathSegArcAbs; + new(): SVGPathSegArcAbs; +} + +interface SVGPathSegArcRel extends SVGPathSeg { + angle: number; + largeArcFlag: boolean; + r1: number; + r2: number; + sweepFlag: boolean; + x: number; + y: number; +} + +declare var SVGPathSegArcRel: { + prototype: SVGPathSegArcRel; + new(): SVGPathSegArcRel; +} + +interface SVGPathSegClosePath extends SVGPathSeg { +} + +declare var SVGPathSegClosePath: { + prototype: SVGPathSegClosePath; + new(): SVGPathSegClosePath; +} + +interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicAbs: { + prototype: SVGPathSegCurvetoCubicAbs; + new(): SVGPathSegCurvetoCubicAbs; +} + +interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { + x: number; + x1: number; + x2: number; + y: number; + y1: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicRel: { + prototype: SVGPathSegCurvetoCubicRel; + new(): SVGPathSegCurvetoCubicRel; +} + +interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothAbs: { + prototype: SVGPathSegCurvetoCubicSmoothAbs; + new(): SVGPathSegCurvetoCubicSmoothAbs; +} + +interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { + x: number; + x2: number; + y: number; + y2: number; +} + +declare var SVGPathSegCurvetoCubicSmoothRel: { + prototype: SVGPathSegCurvetoCubicSmoothRel; + new(): SVGPathSegCurvetoCubicSmoothRel; +} + +interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticAbs: { + prototype: SVGPathSegCurvetoQuadraticAbs; + new(): SVGPathSegCurvetoQuadraticAbs; +} + +interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { + x: number; + x1: number; + y: number; + y1: number; +} + +declare var SVGPathSegCurvetoQuadraticRel: { + prototype: SVGPathSegCurvetoQuadraticRel; + new(): SVGPathSegCurvetoQuadraticRel; +} + +interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothAbs: { + prototype: SVGPathSegCurvetoQuadraticSmoothAbs; + new(): SVGPathSegCurvetoQuadraticSmoothAbs; +} + +interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegCurvetoQuadraticSmoothRel: { + prototype: SVGPathSegCurvetoQuadraticSmoothRel; + new(): SVGPathSegCurvetoQuadraticSmoothRel; +} + +interface SVGPathSegLinetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoAbs: { + prototype: SVGPathSegLinetoAbs; + new(): SVGPathSegLinetoAbs; +} + +interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalAbs: { + prototype: SVGPathSegLinetoHorizontalAbs; + new(): SVGPathSegLinetoHorizontalAbs; +} + +interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { + x: number; +} + +declare var SVGPathSegLinetoHorizontalRel: { + prototype: SVGPathSegLinetoHorizontalRel; + new(): SVGPathSegLinetoHorizontalRel; +} + +interface SVGPathSegLinetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegLinetoRel: { + prototype: SVGPathSegLinetoRel; + new(): SVGPathSegLinetoRel; +} + +interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalAbs: { + prototype: SVGPathSegLinetoVerticalAbs; + new(): SVGPathSegLinetoVerticalAbs; +} + +interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { + y: number; +} + +declare var SVGPathSegLinetoVerticalRel: { + prototype: SVGPathSegLinetoVerticalRel; + new(): SVGPathSegLinetoVerticalRel; +} + +interface SVGPathSegList { + numberOfItems: number; + appendItem(newItem: SVGPathSeg): SVGPathSeg; + clear(): void; + getItem(index: number): SVGPathSeg; + initialize(newItem: SVGPathSeg): SVGPathSeg; + insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; + removeItem(index: number): SVGPathSeg; + replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; +} + +declare var SVGPathSegList: { + prototype: SVGPathSegList; + new(): SVGPathSegList; +} + +interface SVGPathSegMovetoAbs extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoAbs: { + prototype: SVGPathSegMovetoAbs; + new(): SVGPathSegMovetoAbs; +} + +interface SVGPathSegMovetoRel extends SVGPathSeg { + x: number; + y: number; +} + +declare var SVGPathSegMovetoRel: { + prototype: SVGPathSegMovetoRel; + new(): SVGPathSegMovetoRel; +} + +interface SVGPatternElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGURIReference, SVGUnitTypes { + height: SVGAnimatedLength; + patternContentUnits: SVGAnimatedEnumeration; + patternTransform: SVGAnimatedTransformList; + patternUnits: SVGAnimatedEnumeration; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + y: SVGAnimatedLength; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPatternElement: { + prototype: SVGPatternElement; + new(): SVGPatternElement; +} + +interface SVGPoint { + x: number; + y: number; + matrixTransform(matrix: SVGMatrix): SVGPoint; +} + +declare var SVGPoint: { + prototype: SVGPoint; + new(): SVGPoint; +} + +interface SVGPointList { + numberOfItems: number; + appendItem(newItem: SVGPoint): SVGPoint; + clear(): void; + getItem(index: number): SVGPoint; + initialize(newItem: SVGPoint): SVGPoint; + insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; + removeItem(index: number): SVGPoint; + replaceItem(newItem: SVGPoint, index: number): SVGPoint; +} + +declare var SVGPointList: { + prototype: SVGPointList; + new(): SVGPointList; +} + +interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPolygonElement: { + prototype: SVGPolygonElement; + new(): SVGPolygonElement; +} + +interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGAnimatedPoints { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGPolylineElement: { + prototype: SVGPolylineElement; + new(): SVGPolylineElement; +} + +interface SVGPreserveAspectRatio { + align: number; + meetOrSlice: number; + SVG_MEETORSLICE_MEET: number; + SVG_MEETORSLICE_SLICE: number; + SVG_MEETORSLICE_UNKNOWN: number; + SVG_PRESERVEASPECTRATIO_NONE: number; + SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + SVG_PRESERVEASPECTRATIO_XMINYMID: number; + SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +} + +declare var SVGPreserveAspectRatio: { + prototype: SVGPreserveAspectRatio; + new(): SVGPreserveAspectRatio; + SVG_MEETORSLICE_MEET: number; + SVG_MEETORSLICE_SLICE: number; + SVG_MEETORSLICE_UNKNOWN: number; + SVG_PRESERVEASPECTRATIO_NONE: number; + SVG_PRESERVEASPECTRATIO_UNKNOWN: number; + SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + SVG_PRESERVEASPECTRATIO_XMINYMID: number; + SVG_PRESERVEASPECTRATIO_XMINYMIN: number; +} + +interface SVGRadialGradientElement extends SVGGradientElement { + cx: SVGAnimatedLength; + cy: SVGAnimatedLength; + fx: SVGAnimatedLength; + fy: SVGAnimatedLength; + r: SVGAnimatedLength; +} + +declare var SVGRadialGradientElement: { + prototype: SVGRadialGradientElement; + new(): SVGRadialGradientElement; +} + +interface SVGRect { + height: number; + width: number; + x: number; + y: number; +} + +declare var SVGRect: { + prototype: SVGRect; + new(): SVGRect; +} + +interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + height: SVGAnimatedLength; + rx: SVGAnimatedLength; + ry: SVGAnimatedLength; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + y: SVGAnimatedLength; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGRectElement: { + prototype: SVGRectElement; + new(): SVGRectElement; +} + +interface SVGSVGElement extends SVGElement, DocumentEvent, SVGLocatable, SVGTests, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { + contentScriptType: string; + contentStyleType: string; + currentScale: number; + currentTranslate: SVGPoint; + height: SVGAnimatedLength; + onabort: (ev: Event) => any; + onerror: (ev: Event) => any; + onresize: (ev: UIEvent) => any; + onscroll: (ev: UIEvent) => any; + onunload: (ev: Event) => any; + onzoom: (ev: SVGZoomEvent) => any; + pixelUnitToMillimeterX: number; + pixelUnitToMillimeterY: number; + screenPixelToMillimeterX: number; + screenPixelToMillimeterY: number; + viewport: SVGRect; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + y: SVGAnimatedLength; + checkEnclosure(element: SVGElement, rect: SVGRect): boolean; + checkIntersection(element: SVGElement, rect: SVGRect): boolean; + createSVGAngle(): SVGAngle; + createSVGLength(): SVGLength; + createSVGMatrix(): SVGMatrix; + createSVGNumber(): SVGNumber; + createSVGPoint(): SVGPoint; + createSVGRect(): SVGRect; + createSVGTransform(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + deselectAll(): void; + forceRedraw(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getCurrentTime(): number; + getElementById(elementId: string): Element; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeList; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeList; + pauseAnimations(): void; + setCurrentTime(seconds: number): void; + suspendRedraw(maxWaitMilliseconds: number): number; + unpauseAnimations(): void; + unsuspendRedraw(suspendHandleID: number): void; + unsuspendRedrawAll(): void; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "SVGAbort", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "SVGError", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "SVGUnload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "SVGZoom", listener: (ev: SVGZoomEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusin", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "focusout", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSVGElement: { + prototype: SVGSVGElement; + new(): SVGSVGElement; +} + +interface SVGScriptElement extends SVGElement, SVGExternalResourcesRequired, SVGURIReference { + type: string; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +} + +interface SVGStopElement extends SVGElement, SVGStylable { + offset: SVGAnimatedNumber; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +} + +interface SVGStringList { + numberOfItems: number; + appendItem(newItem: string): string; + clear(): void; + getItem(index: number): string; + initialize(newItem: string): string; + insertItemBefore(newItem: string, index: number): string; + removeItem(index: number): string; + replaceItem(newItem: string, index: number): string; +} + +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +} + +interface SVGStyleElement extends SVGElement, SVGLangSpace { + media: string; + title: string; + type: string; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +} + +interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSwitchElement: { + prototype: SVGSwitchElement; + new(): SVGSwitchElement; +} + +interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGExternalResourcesRequired, SVGFitToViewBox { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGSymbolElement: { + prototype: SVGSymbolElement; + new(): SVGSymbolElement; +} + +interface SVGTSpanElement extends SVGTextPositioningElement { +} + +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +} + +interface SVGTextContentElement extends SVGElement, SVGStylable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired { + lengthAdjust: SVGAnimatedEnumeration; + textLength: SVGAnimatedLength; + getCharNumAtPosition(point: SVGPoint): number; + getComputedTextLength(): number; + getEndPositionOfChar(charnum: number): SVGPoint; + getExtentOfChar(charnum: number): SVGRect; + getNumberOfChars(): number; + getRotationOfChar(charnum: number): number; + getStartPositionOfChar(charnum: number): SVGPoint; + getSubStringLength(charnum: number, nchars: number): number; + selectSubString(charnum: number, nchars: number): void; + LENGTHADJUST_SPACING: number; + LENGTHADJUST_SPACINGANDGLYPHS: number; + LENGTHADJUST_UNKNOWN: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGTextContentElement: { + prototype: SVGTextContentElement; + new(): SVGTextContentElement; + LENGTHADJUST_SPACING: number; + LENGTHADJUST_SPACINGANDGLYPHS: number; + LENGTHADJUST_UNKNOWN: number; +} + +interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGTextElement: { + prototype: SVGTextElement; + new(): SVGTextElement; +} + +interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { + method: SVGAnimatedEnumeration; + spacing: SVGAnimatedEnumeration; + startOffset: SVGAnimatedLength; + TEXTPATH_METHODTYPE_ALIGN: number; + TEXTPATH_METHODTYPE_STRETCH: number; + TEXTPATH_METHODTYPE_UNKNOWN: number; + TEXTPATH_SPACINGTYPE_AUTO: number; + TEXTPATH_SPACINGTYPE_EXACT: number; + TEXTPATH_SPACINGTYPE_UNKNOWN: number; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGTextPathElement: { + prototype: SVGTextPathElement; + new(): SVGTextPathElement; + TEXTPATH_METHODTYPE_ALIGN: number; + TEXTPATH_METHODTYPE_STRETCH: number; + TEXTPATH_METHODTYPE_UNKNOWN: number; + TEXTPATH_SPACINGTYPE_AUTO: number; + TEXTPATH_SPACINGTYPE_EXACT: number; + TEXTPATH_SPACINGTYPE_UNKNOWN: number; +} + +interface SVGTextPositioningElement extends SVGTextContentElement { + dx: SVGAnimatedLengthList; + dy: SVGAnimatedLengthList; + rotate: SVGAnimatedNumberList; + x: SVGAnimatedLengthList; + y: SVGAnimatedLengthList; +} + +declare var SVGTextPositioningElement: { + prototype: SVGTextPositioningElement; + new(): SVGTextPositioningElement; +} + +interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGTitleElement: { + prototype: SVGTitleElement; + new(): SVGTitleElement; +} + +interface SVGTransform { + angle: number; + matrix: SVGMatrix; + type: number; + setMatrix(matrix: SVGMatrix): void; + setRotate(angle: number, cx: number, cy: number): void; + setScale(sx: number, sy: number): void; + setSkewX(angle: number): void; + setSkewY(angle: number): void; + setTranslate(tx: number, ty: number): void; + SVG_TRANSFORM_MATRIX: number; + SVG_TRANSFORM_ROTATE: number; + SVG_TRANSFORM_SCALE: number; + SVG_TRANSFORM_SKEWX: number; + SVG_TRANSFORM_SKEWY: number; + SVG_TRANSFORM_TRANSLATE: number; + SVG_TRANSFORM_UNKNOWN: number; +} + +declare var SVGTransform: { + prototype: SVGTransform; + new(): SVGTransform; + SVG_TRANSFORM_MATRIX: number; + SVG_TRANSFORM_ROTATE: number; + SVG_TRANSFORM_SCALE: number; + SVG_TRANSFORM_SKEWX: number; + SVG_TRANSFORM_SKEWY: number; + SVG_TRANSFORM_TRANSLATE: number; + SVG_TRANSFORM_UNKNOWN: number; +} + +interface SVGTransformList { + numberOfItems: number; + appendItem(newItem: SVGTransform): SVGTransform; + clear(): void; + consolidate(): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + getItem(index: number): SVGTransform; + initialize(newItem: SVGTransform): SVGTransform; + insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; + removeItem(index: number): SVGTransform; + replaceItem(newItem: SVGTransform, index: number): SVGTransform; +} + +declare var SVGTransformList: { + prototype: SVGTransformList; + new(): SVGTransformList; +} + +interface SVGUnitTypes { + SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + SVG_UNIT_TYPE_UNKNOWN: number; + SVG_UNIT_TYPE_USERSPACEONUSE: number; +} +declare var SVGUnitTypes: SVGUnitTypes; + +interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGTests, SVGLangSpace, SVGExternalResourcesRequired, SVGURIReference { + animatedInstanceRoot: SVGElementInstance; + height: SVGAnimatedLength; + instanceRoot: SVGElementInstance; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + y: SVGAnimatedLength; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGUseElement: { + prototype: SVGUseElement; + new(): SVGUseElement; +} + +interface SVGViewElement extends SVGElement, SVGExternalResourcesRequired, SVGFitToViewBox, SVGZoomAndPan { + viewTarget: SVGStringList; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var SVGViewElement: { + prototype: SVGViewElement; + new(): SVGViewElement; +} + +interface SVGZoomAndPan { + zoomAndPan: number; +} + +declare var SVGZoomAndPan: { + SVG_ZOOMANDPAN_DISABLE: number; + SVG_ZOOMANDPAN_MAGNIFY: number; + SVG_ZOOMANDPAN_UNKNOWN: number; +} + +interface SVGZoomEvent extends UIEvent { + newScale: number; + newTranslate: SVGPoint; + previousScale: number; + previousTranslate: SVGPoint; + zoomRectScreen: SVGRect; +} + +declare var SVGZoomEvent: { + prototype: SVGZoomEvent; + new(): SVGZoomEvent; +} + +interface Screen extends EventTarget { + availHeight: number; + availWidth: number; + bufferDepth: number; + colorDepth: number; + deviceXDPI: number; + deviceYDPI: number; + fontSmoothingEnabled: boolean; + height: number; + logicalXDPI: number; + logicalYDPI: number; + msOrientation: string; + onmsorientationchange: (ev: Event) => any; + pixelDepth: number; + systemXDPI: number; + systemYDPI: number; + width: number; + msLockOrientation(orientations: string | string[]): boolean; + msUnlockOrientation(): void; + addEventListener(type: "MSOrientationChange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Screen: { + prototype: Screen; + new(): Screen; +} + +interface ScriptNotifyEvent extends Event { + callingUri: string; + value: string; +} + +declare var ScriptNotifyEvent: { + prototype: ScriptNotifyEvent; + new(): ScriptNotifyEvent; +} + +interface ScriptProcessorNode extends AudioNode { + bufferSize: number; + onaudioprocess: (ev: AudioProcessingEvent) => any; + addEventListener(type: "audioprocess", listener: (ev: AudioProcessingEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var ScriptProcessorNode: { + prototype: ScriptProcessorNode; + new(): ScriptProcessorNode; +} + +interface Selection { + anchorNode: Node; + anchorOffset: number; + focusNode: Node; + focusOffset: number; + isCollapsed: boolean; + rangeCount: number; + type: string; + addRange(range: Range): void; + collapse(parentNode: Node, offset: number): void; + collapseToEnd(): void; + collapseToStart(): void; + containsNode(node: Node, partlyContained: boolean): boolean; + deleteFromDocument(): void; + empty(): void; + extend(newNode: Node, offset: number): void; + getRangeAt(index: number): Range; + removeAllRanges(): void; + removeRange(range: Range): void; + selectAllChildren(parentNode: Node): void; + setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void; + toString(): string; +} + +declare var Selection: { + prototype: Selection; + new(): Selection; +} + +interface SourceBuffer extends EventTarget { + appendWindowEnd: number; + appendWindowStart: number; + audioTracks: AudioTrackList; + buffered: TimeRanges; + mode: string; + timestampOffset: number; + updating: boolean; + videoTracks: VideoTrackList; + abort(): void; + appendBuffer(data: ArrayBuffer | ArrayBufferView): void; + appendStream(stream: MSStream, maxSize?: number): void; + remove(start: number, end: number): void; +} + +declare var SourceBuffer: { + prototype: SourceBuffer; + new(): SourceBuffer; +} + +interface SourceBufferList extends EventTarget { + length: number; + item(index: number): SourceBuffer; + [index: number]: SourceBuffer; +} + +declare var SourceBufferList: { + prototype: SourceBufferList; + new(): SourceBufferList; +} + +interface StereoPannerNode extends AudioNode { + pan: AudioParam; +} + +declare var StereoPannerNode: { + prototype: StereoPannerNode; + new(): StereoPannerNode; +} + +interface Storage { + length: number; + clear(): void; + getItem(key: string): any; + key(index: number): string; + removeItem(key: string): void; + setItem(key: string, data: string): void; + [key: string]: any; + [index: number]: string; +} + +declare var Storage: { + prototype: Storage; + new(): Storage; +} + +interface StorageEvent extends Event { + url: string; + key?: string; + oldValue?: string; + newValue?: string; + storageArea?: Storage; +} + +declare var StorageEvent: { + prototype: StorageEvent; + new (type: string, eventInitDict?: StorageEventInit): StorageEvent; +} + +interface StyleMedia { + type: string; + matchMedium(mediaquery: string): boolean; +} + +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +} + +interface StyleSheet { + disabled: boolean; + href: string; + media: MediaList; + ownerNode: Node; + parentStyleSheet: StyleSheet; + title: string; + type: string; +} + +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +} + +interface StyleSheetList { + length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; +} + +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +} + +interface StyleSheetPageList { + length: number; + item(index: number): CSSPageRule; + [index: number]: CSSPageRule; +} + +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +} + +interface SubtleCrypto { + decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any; + deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): any; + deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): any; + digest(algorithm: string | Algorithm, data: ArrayBufferView): any; + encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any; + exportKey(format: string, key: CryptoKey): any; + generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any; + importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any; + sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any; + unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any; + verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): any; +} + +declare var SubtleCrypto: { + prototype: SubtleCrypto; + new(): SubtleCrypto; +} + +interface Text extends CharacterData { + wholeText: string; + replaceWholeText(content: string): Text; + splitText(offset: number): Text; +} + +declare var Text: { + prototype: Text; + new(): Text; +} + +interface TextEvent extends UIEvent { + data: string; + inputMethod: number; + locale: string; + initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void; + DOM_INPUT_METHOD_DROP: number; + DOM_INPUT_METHOD_HANDWRITING: number; + DOM_INPUT_METHOD_IME: number; + DOM_INPUT_METHOD_KEYBOARD: number; + DOM_INPUT_METHOD_MULTIMODAL: number; + DOM_INPUT_METHOD_OPTION: number; + DOM_INPUT_METHOD_PASTE: number; + DOM_INPUT_METHOD_SCRIPT: number; + DOM_INPUT_METHOD_UNKNOWN: number; + DOM_INPUT_METHOD_VOICE: number; +} + +declare var TextEvent: { + prototype: TextEvent; + new(): TextEvent; + DOM_INPUT_METHOD_DROP: number; + DOM_INPUT_METHOD_HANDWRITING: number; + DOM_INPUT_METHOD_IME: number; + DOM_INPUT_METHOD_KEYBOARD: number; + DOM_INPUT_METHOD_MULTIMODAL: number; + DOM_INPUT_METHOD_OPTION: number; + DOM_INPUT_METHOD_PASTE: number; + DOM_INPUT_METHOD_SCRIPT: number; + DOM_INPUT_METHOD_UNKNOWN: number; + DOM_INPUT_METHOD_VOICE: number; +} + +interface TextMetrics { + width: number; +} + +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +} + +interface TextRange { + boundingHeight: number; + boundingLeft: number; + boundingTop: number; + boundingWidth: number; + htmlText: string; + offsetLeft: number; + offsetTop: number; + text: string; + collapse(start?: boolean): void; + compareEndPoints(how: string, sourceRange: TextRange): number; + duplicate(): TextRange; + execCommand(cmdID: string, showUI?: boolean, value?: any): boolean; + execCommandShowHelp(cmdID: string): boolean; + expand(Unit: string): boolean; + findText(string: string, count?: number, flags?: number): boolean; + getBookmark(): string; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + inRange(range: TextRange): boolean; + isEqual(range: TextRange): boolean; + move(unit: string, count?: number): number; + moveEnd(unit: string, count?: number): number; + moveStart(unit: string, count?: number): number; + moveToBookmark(bookmark: string): boolean; + moveToElementText(element: Element): void; + moveToPoint(x: number, y: number): void; + parentElement(): Element; + pasteHTML(html: string): void; + queryCommandEnabled(cmdID: string): boolean; + queryCommandIndeterm(cmdID: string): boolean; + queryCommandState(cmdID: string): boolean; + queryCommandSupported(cmdID: string): boolean; + queryCommandText(cmdID: string): string; + queryCommandValue(cmdID: string): any; + scrollIntoView(fStart?: boolean): void; + select(): void; + setEndPoint(how: string, SourceRange: TextRange): void; +} + +declare var TextRange: { + prototype: TextRange; + new(): TextRange; +} + +interface TextRangeCollection { + length: number; + item(index: number): TextRange; + [index: number]: TextRange; +} + +declare var TextRangeCollection: { + prototype: TextRangeCollection; + new(): TextRangeCollection; +} + +interface TextTrack extends EventTarget { + activeCues: TextTrackCueList; + cues: TextTrackCueList; + inBandMetadataTrackDispatchType: string; + kind: string; + label: string; + language: string; + mode: any; + oncuechange: (ev: Event) => any; + onerror: (ev: Event) => any; + onload: (ev: Event) => any; + readyState: number; + addCue(cue: TextTrackCue): void; + removeCue(cue: TextTrackCue): void; + DISABLED: number; + ERROR: number; + HIDDEN: number; + LOADED: number; + LOADING: number; + NONE: number; + SHOWING: number; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var TextTrack: { + prototype: TextTrack; + new(): TextTrack; + DISABLED: number; + ERROR: number; + HIDDEN: number; + LOADED: number; + LOADING: number; + NONE: number; + SHOWING: number; +} + +interface TextTrackCue extends EventTarget { + endTime: number; + id: string; + onenter: (ev: Event) => any; + onexit: (ev: Event) => any; + pauseOnExit: boolean; + startTime: number; + text: string; + track: TextTrack; + getCueAsHTML(): DocumentFragment; + addEventListener(type: "enter", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "exit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var TextTrackCue: { + prototype: TextTrackCue; + new(startTime: number, endTime: number, text: string): TextTrackCue; +} + +interface TextTrackCueList { + length: number; + getCueById(id: string): TextTrackCue; + item(index: number): TextTrackCue; + [index: number]: TextTrackCue; +} + +declare var TextTrackCueList: { + prototype: TextTrackCueList; + new(): TextTrackCueList; +} + +interface TextTrackList extends EventTarget { + length: number; + onaddtrack: (ev: TrackEvent) => any; + item(index: number): TextTrack; + addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: TextTrack; +} + +declare var TextTrackList: { + prototype: TextTrackList; + new(): TextTrackList; +} + +interface TimeRanges { + length: number; + end(index: number): number; + start(index: number): number; +} + +declare var TimeRanges: { + prototype: TimeRanges; + new(): TimeRanges; +} + +interface Touch { + clientX: number; + clientY: number; + identifier: number; + pageX: number; + pageY: number; + screenX: number; + screenY: number; + target: EventTarget; +} + +declare var Touch: { + prototype: Touch; + new(): Touch; +} + +interface TouchEvent extends UIEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + metaKey: boolean; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; +} + +declare var TouchEvent: { + prototype: TouchEvent; + new(): TouchEvent; +} + +interface TouchList { + length: number; + item(index: number): Touch; + [index: number]: Touch; +} + +declare var TouchList: { + prototype: TouchList; + new(): TouchList; +} + +interface TrackEvent extends Event { + track: any; +} + +declare var TrackEvent: { + prototype: TrackEvent; + new(): TrackEvent; +} + +interface TransitionEvent extends Event { + elapsedTime: number; + propertyName: string; + initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void; +} + +declare var TransitionEvent: { + prototype: TransitionEvent; + new(): TransitionEvent; +} + +interface TreeWalker { + currentNode: Node; + expandEntityReferences: boolean; + filter: NodeFilter; + root: Node; + whatToShow: number; + firstChild(): Node; + lastChild(): Node; + nextNode(): Node; + nextSibling(): Node; + parentNode(): Node; + previousNode(): Node; + previousSibling(): Node; +} + +declare var TreeWalker: { + prototype: TreeWalker; + new(): TreeWalker; +} + +interface UIEvent extends Event { + detail: number; + view: Window; + initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void; +} + +declare var UIEvent: { + prototype: UIEvent; + new(type: string, eventInitDict?: UIEventInit): UIEvent; +} + +interface URL { + createObjectURL(object: any, options?: ObjectURLOptions): string; + revokeObjectURL(url: string): void; +} +declare var URL: URL; + +interface UnviewableContentIdentifiedEvent extends NavigationEventWithReferrer { + mediaType: string; +} + +declare var UnviewableContentIdentifiedEvent: { + prototype: UnviewableContentIdentifiedEvent; + new(): UnviewableContentIdentifiedEvent; +} + +interface ValidityState { + badInput: boolean; + customError: boolean; + patternMismatch: boolean; + rangeOverflow: boolean; + rangeUnderflow: boolean; + stepMismatch: boolean; + tooLong: boolean; + typeMismatch: boolean; + valid: boolean; + valueMissing: boolean; +} + +declare var ValidityState: { + prototype: ValidityState; + new(): ValidityState; +} + +interface VideoPlaybackQuality { + corruptedVideoFrames: number; + creationTime: number; + droppedVideoFrames: number; + totalFrameDelay: number; + totalVideoFrames: number; +} + +declare var VideoPlaybackQuality: { + prototype: VideoPlaybackQuality; + new(): VideoPlaybackQuality; +} + +interface VideoTrack { + id: string; + kind: string; + label: string; + language: string; + selected: boolean; + sourceBuffer: SourceBuffer; +} + +declare var VideoTrack: { + prototype: VideoTrack; + new(): VideoTrack; +} + +interface VideoTrackList extends EventTarget { + length: number; + onaddtrack: (ev: TrackEvent) => any; + onchange: (ev: Event) => any; + onremovetrack: (ev: TrackEvent) => any; + selectedIndex: number; + getTrackById(id: string): VideoTrack; + item(index: number): VideoTrack; + addEventListener(type: "addtrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "removetrack", listener: (ev: TrackEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: VideoTrack; +} + +declare var VideoTrackList: { + prototype: VideoTrackList; + new(): VideoTrackList; +} + +interface WEBGL_compressed_texture_s3tc { + COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +declare var WEBGL_compressed_texture_s3tc: { + prototype: WEBGL_compressed_texture_s3tc; + new(): WEBGL_compressed_texture_s3tc; + COMPRESSED_RGBA_S3TC_DXT1_EXT: number; + COMPRESSED_RGBA_S3TC_DXT3_EXT: number; + COMPRESSED_RGBA_S3TC_DXT5_EXT: number; + COMPRESSED_RGB_S3TC_DXT1_EXT: number; +} + +interface WEBGL_debug_renderer_info { + UNMASKED_RENDERER_WEBGL: number; + UNMASKED_VENDOR_WEBGL: number; +} + +declare var WEBGL_debug_renderer_info: { + prototype: WEBGL_debug_renderer_info; + new(): WEBGL_debug_renderer_info; + UNMASKED_RENDERER_WEBGL: number; + UNMASKED_VENDOR_WEBGL: number; +} + +interface WEBGL_depth_texture { + UNSIGNED_INT_24_8_WEBGL: number; +} + +declare var WEBGL_depth_texture: { + prototype: WEBGL_depth_texture; + new(): WEBGL_depth_texture; + UNSIGNED_INT_24_8_WEBGL: number; +} + +interface WaveShaperNode extends AudioNode { + curve: Float32Array; + oversample: string; +} + +declare var WaveShaperNode: { + prototype: WaveShaperNode; + new(): WaveShaperNode; +} + +interface WebGLActiveInfo { + name: string; + size: number; + type: number; +} + +declare var WebGLActiveInfo: { + prototype: WebGLActiveInfo; + new(): WebGLActiveInfo; +} + +interface WebGLBuffer extends WebGLObject { +} + +declare var WebGLBuffer: { + prototype: WebGLBuffer; + new(): WebGLBuffer; +} + +interface WebGLContextEvent extends Event { + statusMessage: string; +} + +declare var WebGLContextEvent: { + prototype: WebGLContextEvent; + new(): WebGLContextEvent; +} + +interface WebGLFramebuffer extends WebGLObject { +} + +declare var WebGLFramebuffer: { + prototype: WebGLFramebuffer; + new(): WebGLFramebuffer; +} + +interface WebGLObject { +} + +declare var WebGLObject: { + prototype: WebGLObject; + new(): WebGLObject; +} + +interface WebGLProgram extends WebGLObject { +} + +declare var WebGLProgram: { + prototype: WebGLProgram; + new(): WebGLProgram; +} + +interface WebGLRenderbuffer extends WebGLObject { +} + +declare var WebGLRenderbuffer: { + prototype: WebGLRenderbuffer; + new(): WebGLRenderbuffer; +} + +interface WebGLRenderingContext { + canvas: HTMLCanvasElement; + drawingBufferHeight: number; + drawingBufferWidth: number; + activeTexture(texture: number): void; + attachShader(program: WebGLProgram, shader: WebGLShader): void; + bindAttribLocation(program: WebGLProgram, index: number, name: string): void; + bindBuffer(target: number, buffer: WebGLBuffer): void; + bindFramebuffer(target: number, framebuffer: WebGLFramebuffer): void; + bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer): void; + bindTexture(target: number, texture: WebGLTexture): void; + blendColor(red: number, green: number, blue: number, alpha: number): void; + blendEquation(mode: number): void; + blendEquationSeparate(modeRGB: number, modeAlpha: number): void; + blendFunc(sfactor: number, dfactor: number): void; + blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void; + bufferData(target: number, size: number | ArrayBufferView | ArrayBuffer, usage: number): void; + bufferSubData(target: number, offset: number, data: ArrayBufferView | ArrayBuffer): void; + checkFramebufferStatus(target: number): number; + clear(mask: number): void; + clearColor(red: number, green: number, blue: number, alpha: number): void; + clearDepth(depth: number): void; + clearStencil(s: number): void; + colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void; + compileShader(shader: WebGLShader): void; + compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: ArrayBufferView): void; + compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: ArrayBufferView): void; + copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void; + copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void; + createBuffer(): WebGLBuffer; + createFramebuffer(): WebGLFramebuffer; + createProgram(): WebGLProgram; + createRenderbuffer(): WebGLRenderbuffer; + createShader(type: number): WebGLShader; + createTexture(): WebGLTexture; + cullFace(mode: number): void; + deleteBuffer(buffer: WebGLBuffer): void; + deleteFramebuffer(framebuffer: WebGLFramebuffer): void; + deleteProgram(program: WebGLProgram): void; + deleteRenderbuffer(renderbuffer: WebGLRenderbuffer): void; + deleteShader(shader: WebGLShader): void; + deleteTexture(texture: WebGLTexture): void; + depthFunc(func: number): void; + depthMask(flag: boolean): void; + depthRange(zNear: number, zFar: number): void; + detachShader(program: WebGLProgram, shader: WebGLShader): void; + disable(cap: number): void; + disableVertexAttribArray(index: number): void; + drawArrays(mode: number, first: number, count: number): void; + drawElements(mode: number, count: number, type: number, offset: number): void; + enable(cap: number): void; + enableVertexAttribArray(index: number): void; + finish(): void; + flush(): void; + framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer): void; + framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture, level: number): void; + frontFace(mode: number): void; + generateMipmap(target: number): void; + getActiveAttrib(program: WebGLProgram, index: number): WebGLActiveInfo; + getActiveUniform(program: WebGLProgram, index: number): WebGLActiveInfo; + getAttachedShaders(program: WebGLProgram): WebGLShader[]; + getAttribLocation(program: WebGLProgram, name: string): number; + getBufferParameter(target: number, pname: number): any; + getContextAttributes(): WebGLContextAttributes; + getError(): number; + getExtension(name: string): any; + getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any; + getParameter(pname: number): any; + getProgramInfoLog(program: WebGLProgram): string; + getProgramParameter(program: WebGLProgram, pname: number): any; + getRenderbufferParameter(target: number, pname: number): any; + getShaderInfoLog(shader: WebGLShader): string; + getShaderParameter(shader: WebGLShader, pname: number): any; + getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat; + getShaderSource(shader: WebGLShader): string; + getSupportedExtensions(): string[]; + getTexParameter(target: number, pname: number): any; + getUniform(program: WebGLProgram, location: WebGLUniformLocation): any; + getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation; + getVertexAttrib(index: number, pname: number): any; + getVertexAttribOffset(index: number, pname: number): number; + hint(target: number, mode: number): void; + isBuffer(buffer: WebGLBuffer): boolean; + isContextLost(): boolean; + isEnabled(cap: number): boolean; + isFramebuffer(framebuffer: WebGLFramebuffer): boolean; + isProgram(program: WebGLProgram): boolean; + isRenderbuffer(renderbuffer: WebGLRenderbuffer): boolean; + isShader(shader: WebGLShader): boolean; + isTexture(texture: WebGLTexture): boolean; + lineWidth(width: number): void; + linkProgram(program: WebGLProgram): void; + pixelStorei(pname: number, param: number): void; + polygonOffset(factor: number, units: number): void; + readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; + renderbufferStorage(target: number, internalformat: number, width: number, height: number): void; + sampleCoverage(value: number, invert: boolean): void; + scissor(x: number, y: number, width: number, height: number): void; + shaderSource(shader: WebGLShader, source: string): void; + stencilFunc(func: number, ref: number, mask: number): void; + stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void; + stencilMask(mask: number): void; + 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: Float32Array): void; + uniform1i(location: WebGLUniformLocation, x: number): void; + uniform1iv(location: WebGLUniformLocation, v: Int32Array): void; + uniform2f(location: WebGLUniformLocation, x: number, y: number): void; + uniform2fv(location: WebGLUniformLocation, v: Float32Array): void; + uniform2i(location: WebGLUniformLocation, x: number, y: number): void; + uniform2iv(location: WebGLUniformLocation, v: Int32Array): void; + uniform3f(location: WebGLUniformLocation, x: number, y: number, z: number): void; + uniform3fv(location: WebGLUniformLocation, v: Float32Array): void; + uniform3i(location: WebGLUniformLocation, x: number, y: number, z: number): void; + uniform3iv(location: WebGLUniformLocation, v: Int32Array): void; + uniform4f(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; + uniform4fv(location: WebGLUniformLocation, v: Float32Array): void; + uniform4i(location: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; + uniform4iv(location: WebGLUniformLocation, v: Int32Array): void; + uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array): void; + useProgram(program: WebGLProgram): void; + validateProgram(program: WebGLProgram): void; + vertexAttrib1f(indx: number, x: number): void; + vertexAttrib1fv(indx: number, values: Float32Array): void; + vertexAttrib2f(indx: number, x: number, y: number): void; + vertexAttrib2fv(indx: number, values: Float32Array): void; + vertexAttrib3f(indx: number, x: number, y: number, z: number): void; + vertexAttrib3fv(indx: number, values: Float32Array): void; + vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void; + vertexAttrib4fv(indx: number, values: Float32Array): void; + vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void; + viewport(x: number, y: number, width: number, height: number): void; + ACTIVE_ATTRIBUTES: number; + ACTIVE_TEXTURE: number; + ACTIVE_UNIFORMS: number; + ALIASED_LINE_WIDTH_RANGE: number; + ALIASED_POINT_SIZE_RANGE: number; + ALPHA: number; + ALPHA_BITS: number; + ALWAYS: number; + ARRAY_BUFFER: number; + ARRAY_BUFFER_BINDING: number; + ATTACHED_SHADERS: number; + BACK: number; + BLEND: number; + BLEND_COLOR: number; + BLEND_DST_ALPHA: number; + BLEND_DST_RGB: number; + BLEND_EQUATION: number; + BLEND_EQUATION_ALPHA: number; + BLEND_EQUATION_RGB: number; + BLEND_SRC_ALPHA: number; + BLEND_SRC_RGB: number; + BLUE_BITS: number; + BOOL: number; + BOOL_VEC2: number; + BOOL_VEC3: number; + BOOL_VEC4: number; + BROWSER_DEFAULT_WEBGL: number; + BUFFER_SIZE: number; + BUFFER_USAGE: number; + BYTE: number; + CCW: number; + CLAMP_TO_EDGE: number; + COLOR_ATTACHMENT0: number; + COLOR_BUFFER_BIT: number; + COLOR_CLEAR_VALUE: number; + COLOR_WRITEMASK: number; + COMPILE_STATUS: number; + COMPRESSED_TEXTURE_FORMATS: number; + CONSTANT_ALPHA: number; + CONSTANT_COLOR: number; + CONTEXT_LOST_WEBGL: number; + CULL_FACE: number; + CULL_FACE_MODE: number; + CURRENT_PROGRAM: number; + CURRENT_VERTEX_ATTRIB: number; + CW: number; + DECR: number; + DECR_WRAP: number; + DELETE_STATUS: number; + DEPTH_ATTACHMENT: number; + DEPTH_BITS: number; + DEPTH_BUFFER_BIT: number; + DEPTH_CLEAR_VALUE: number; + DEPTH_COMPONENT: number; + DEPTH_COMPONENT16: number; + DEPTH_FUNC: number; + DEPTH_RANGE: number; + DEPTH_STENCIL: number; + DEPTH_STENCIL_ATTACHMENT: number; + DEPTH_TEST: number; + DEPTH_WRITEMASK: number; + DITHER: number; + DONT_CARE: number; + DST_ALPHA: number; + DST_COLOR: number; + DYNAMIC_DRAW: number; + ELEMENT_ARRAY_BUFFER: number; + ELEMENT_ARRAY_BUFFER_BINDING: number; + EQUAL: number; + FASTEST: number; + FLOAT: number; + FLOAT_MAT2: number; + FLOAT_MAT3: number; + FLOAT_MAT4: number; + FLOAT_VEC2: number; + FLOAT_VEC3: number; + FLOAT_VEC4: number; + FRAGMENT_SHADER: number; + FRAMEBUFFER: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + FRAMEBUFFER_BINDING: number; + FRAMEBUFFER_COMPLETE: number; + FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + FRAMEBUFFER_UNSUPPORTED: number; + FRONT: number; + FRONT_AND_BACK: number; + FRONT_FACE: number; + FUNC_ADD: number; + FUNC_REVERSE_SUBTRACT: number; + FUNC_SUBTRACT: number; + GENERATE_MIPMAP_HINT: number; + GEQUAL: number; + GREATER: number; + GREEN_BITS: number; + HIGH_FLOAT: number; + HIGH_INT: number; + IMPLEMENTATION_COLOR_READ_FORMAT: number; + IMPLEMENTATION_COLOR_READ_TYPE: number; + INCR: number; + INCR_WRAP: number; + INT: number; + INT_VEC2: number; + INT_VEC3: number; + INT_VEC4: number; + INVALID_ENUM: number; + INVALID_FRAMEBUFFER_OPERATION: number; + INVALID_OPERATION: number; + INVALID_VALUE: number; + INVERT: number; + KEEP: number; + LEQUAL: number; + LESS: number; + LINEAR: number; + LINEAR_MIPMAP_LINEAR: number; + LINEAR_MIPMAP_NEAREST: number; + LINES: number; + LINE_LOOP: number; + LINE_STRIP: number; + LINE_WIDTH: number; + LINK_STATUS: number; + LOW_FLOAT: number; + LOW_INT: number; + LUMINANCE: number; + LUMINANCE_ALPHA: number; + MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + MAX_CUBE_MAP_TEXTURE_SIZE: number; + MAX_FRAGMENT_UNIFORM_VECTORS: number; + MAX_RENDERBUFFER_SIZE: number; + MAX_TEXTURE_IMAGE_UNITS: number; + MAX_TEXTURE_SIZE: number; + MAX_VARYING_VECTORS: number; + MAX_VERTEX_ATTRIBS: number; + MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + MAX_VERTEX_UNIFORM_VECTORS: number; + MAX_VIEWPORT_DIMS: number; + MEDIUM_FLOAT: number; + MEDIUM_INT: number; + MIRRORED_REPEAT: number; + NEAREST: number; + NEAREST_MIPMAP_LINEAR: number; + NEAREST_MIPMAP_NEAREST: number; + NEVER: number; + NICEST: number; + NONE: number; + NOTEQUAL: number; + NO_ERROR: number; + ONE: number; + ONE_MINUS_CONSTANT_ALPHA: number; + ONE_MINUS_CONSTANT_COLOR: number; + ONE_MINUS_DST_ALPHA: number; + ONE_MINUS_DST_COLOR: number; + ONE_MINUS_SRC_ALPHA: number; + ONE_MINUS_SRC_COLOR: number; + OUT_OF_MEMORY: number; + PACK_ALIGNMENT: number; + POINTS: number; + POLYGON_OFFSET_FACTOR: number; + POLYGON_OFFSET_FILL: number; + POLYGON_OFFSET_UNITS: number; + RED_BITS: number; + RENDERBUFFER: number; + RENDERBUFFER_ALPHA_SIZE: number; + RENDERBUFFER_BINDING: number; + RENDERBUFFER_BLUE_SIZE: number; + RENDERBUFFER_DEPTH_SIZE: number; + RENDERBUFFER_GREEN_SIZE: number; + RENDERBUFFER_HEIGHT: number; + RENDERBUFFER_INTERNAL_FORMAT: number; + RENDERBUFFER_RED_SIZE: number; + RENDERBUFFER_STENCIL_SIZE: number; + RENDERBUFFER_WIDTH: number; + RENDERER: number; + REPEAT: number; + REPLACE: number; + RGB: number; + RGB565: number; + RGB5_A1: number; + RGBA: number; + RGBA4: number; + SAMPLER_2D: number; + SAMPLER_CUBE: number; + SAMPLES: number; + SAMPLE_ALPHA_TO_COVERAGE: number; + SAMPLE_BUFFERS: number; + SAMPLE_COVERAGE: number; + SAMPLE_COVERAGE_INVERT: number; + SAMPLE_COVERAGE_VALUE: number; + SCISSOR_BOX: number; + SCISSOR_TEST: number; + SHADER_TYPE: number; + SHADING_LANGUAGE_VERSION: number; + SHORT: number; + SRC_ALPHA: number; + SRC_ALPHA_SATURATE: number; + SRC_COLOR: number; + STATIC_DRAW: number; + STENCIL_ATTACHMENT: number; + STENCIL_BACK_FAIL: number; + STENCIL_BACK_FUNC: number; + STENCIL_BACK_PASS_DEPTH_FAIL: number; + STENCIL_BACK_PASS_DEPTH_PASS: number; + STENCIL_BACK_REF: number; + STENCIL_BACK_VALUE_MASK: number; + STENCIL_BACK_WRITEMASK: number; + STENCIL_BITS: number; + STENCIL_BUFFER_BIT: number; + STENCIL_CLEAR_VALUE: number; + STENCIL_FAIL: number; + STENCIL_FUNC: number; + STENCIL_INDEX: number; + STENCIL_INDEX8: number; + STENCIL_PASS_DEPTH_FAIL: number; + STENCIL_PASS_DEPTH_PASS: number; + STENCIL_REF: number; + STENCIL_TEST: number; + STENCIL_VALUE_MASK: number; + STENCIL_WRITEMASK: number; + STREAM_DRAW: number; + SUBPIXEL_BITS: number; + TEXTURE: number; + TEXTURE0: number; + TEXTURE1: number; + TEXTURE10: number; + TEXTURE11: number; + TEXTURE12: number; + TEXTURE13: number; + TEXTURE14: number; + TEXTURE15: number; + TEXTURE16: number; + TEXTURE17: number; + TEXTURE18: number; + TEXTURE19: number; + TEXTURE2: number; + TEXTURE20: number; + TEXTURE21: number; + TEXTURE22: number; + TEXTURE23: number; + TEXTURE24: number; + TEXTURE25: number; + TEXTURE26: number; + TEXTURE27: number; + TEXTURE28: number; + TEXTURE29: number; + TEXTURE3: number; + TEXTURE30: number; + TEXTURE31: number; + TEXTURE4: number; + TEXTURE5: number; + TEXTURE6: number; + TEXTURE7: number; + TEXTURE8: number; + TEXTURE9: number; + TEXTURE_2D: number; + TEXTURE_BINDING_2D: number; + TEXTURE_BINDING_CUBE_MAP: number; + TEXTURE_CUBE_MAP: number; + TEXTURE_CUBE_MAP_NEGATIVE_X: number; + TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + TEXTURE_CUBE_MAP_POSITIVE_X: number; + TEXTURE_CUBE_MAP_POSITIVE_Y: number; + TEXTURE_CUBE_MAP_POSITIVE_Z: number; + TEXTURE_MAG_FILTER: number; + TEXTURE_MIN_FILTER: number; + TEXTURE_WRAP_S: number; + TEXTURE_WRAP_T: number; + TRIANGLES: number; + TRIANGLE_FAN: number; + TRIANGLE_STRIP: number; + UNPACK_ALIGNMENT: number; + UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + UNPACK_FLIP_Y_WEBGL: number; + UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + UNSIGNED_BYTE: number; + UNSIGNED_INT: number; + UNSIGNED_SHORT: number; + UNSIGNED_SHORT_4_4_4_4: number; + UNSIGNED_SHORT_5_5_5_1: number; + UNSIGNED_SHORT_5_6_5: number; + VALIDATE_STATUS: number; + VENDOR: number; + VERSION: number; + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + VERTEX_ATTRIB_ARRAY_ENABLED: number; + VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + VERTEX_ATTRIB_ARRAY_POINTER: number; + VERTEX_ATTRIB_ARRAY_SIZE: number; + VERTEX_ATTRIB_ARRAY_STRIDE: number; + VERTEX_ATTRIB_ARRAY_TYPE: number; + VERTEX_SHADER: number; + VIEWPORT: number; + ZERO: number; +} + +declare var WebGLRenderingContext: { + prototype: WebGLRenderingContext; + new(): WebGLRenderingContext; + ACTIVE_ATTRIBUTES: number; + ACTIVE_TEXTURE: number; + ACTIVE_UNIFORMS: number; + ALIASED_LINE_WIDTH_RANGE: number; + ALIASED_POINT_SIZE_RANGE: number; + ALPHA: number; + ALPHA_BITS: number; + ALWAYS: number; + ARRAY_BUFFER: number; + ARRAY_BUFFER_BINDING: number; + ATTACHED_SHADERS: number; + BACK: number; + BLEND: number; + BLEND_COLOR: number; + BLEND_DST_ALPHA: number; + BLEND_DST_RGB: number; + BLEND_EQUATION: number; + BLEND_EQUATION_ALPHA: number; + BLEND_EQUATION_RGB: number; + BLEND_SRC_ALPHA: number; + BLEND_SRC_RGB: number; + BLUE_BITS: number; + BOOL: number; + BOOL_VEC2: number; + BOOL_VEC3: number; + BOOL_VEC4: number; + BROWSER_DEFAULT_WEBGL: number; + BUFFER_SIZE: number; + BUFFER_USAGE: number; + BYTE: number; + CCW: number; + CLAMP_TO_EDGE: number; + COLOR_ATTACHMENT0: number; + COLOR_BUFFER_BIT: number; + COLOR_CLEAR_VALUE: number; + COLOR_WRITEMASK: number; + COMPILE_STATUS: number; + COMPRESSED_TEXTURE_FORMATS: number; + CONSTANT_ALPHA: number; + CONSTANT_COLOR: number; + CONTEXT_LOST_WEBGL: number; + CULL_FACE: number; + CULL_FACE_MODE: number; + CURRENT_PROGRAM: number; + CURRENT_VERTEX_ATTRIB: number; + CW: number; + DECR: number; + DECR_WRAP: number; + DELETE_STATUS: number; + DEPTH_ATTACHMENT: number; + DEPTH_BITS: number; + DEPTH_BUFFER_BIT: number; + DEPTH_CLEAR_VALUE: number; + DEPTH_COMPONENT: number; + DEPTH_COMPONENT16: number; + DEPTH_FUNC: number; + DEPTH_RANGE: number; + DEPTH_STENCIL: number; + DEPTH_STENCIL_ATTACHMENT: number; + DEPTH_TEST: number; + DEPTH_WRITEMASK: number; + DITHER: number; + DONT_CARE: number; + DST_ALPHA: number; + DST_COLOR: number; + DYNAMIC_DRAW: number; + ELEMENT_ARRAY_BUFFER: number; + ELEMENT_ARRAY_BUFFER_BINDING: number; + EQUAL: number; + FASTEST: number; + FLOAT: number; + FLOAT_MAT2: number; + FLOAT_MAT3: number; + FLOAT_MAT4: number; + FLOAT_VEC2: number; + FLOAT_VEC3: number; + FLOAT_VEC4: number; + FRAGMENT_SHADER: number; + FRAMEBUFFER: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; + FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; + FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; + FRAMEBUFFER_BINDING: number; + FRAMEBUFFER_COMPLETE: number; + FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; + FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; + FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; + FRAMEBUFFER_UNSUPPORTED: number; + FRONT: number; + FRONT_AND_BACK: number; + FRONT_FACE: number; + FUNC_ADD: number; + FUNC_REVERSE_SUBTRACT: number; + FUNC_SUBTRACT: number; + GENERATE_MIPMAP_HINT: number; + GEQUAL: number; + GREATER: number; + GREEN_BITS: number; + HIGH_FLOAT: number; + HIGH_INT: number; + IMPLEMENTATION_COLOR_READ_FORMAT: number; + IMPLEMENTATION_COLOR_READ_TYPE: number; + INCR: number; + INCR_WRAP: number; + INT: number; + INT_VEC2: number; + INT_VEC3: number; + INT_VEC4: number; + INVALID_ENUM: number; + INVALID_FRAMEBUFFER_OPERATION: number; + INVALID_OPERATION: number; + INVALID_VALUE: number; + INVERT: number; + KEEP: number; + LEQUAL: number; + LESS: number; + LINEAR: number; + LINEAR_MIPMAP_LINEAR: number; + LINEAR_MIPMAP_NEAREST: number; + LINES: number; + LINE_LOOP: number; + LINE_STRIP: number; + LINE_WIDTH: number; + LINK_STATUS: number; + LOW_FLOAT: number; + LOW_INT: number; + LUMINANCE: number; + LUMINANCE_ALPHA: number; + MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; + MAX_CUBE_MAP_TEXTURE_SIZE: number; + MAX_FRAGMENT_UNIFORM_VECTORS: number; + MAX_RENDERBUFFER_SIZE: number; + MAX_TEXTURE_IMAGE_UNITS: number; + MAX_TEXTURE_SIZE: number; + MAX_VARYING_VECTORS: number; + MAX_VERTEX_ATTRIBS: number; + MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; + MAX_VERTEX_UNIFORM_VECTORS: number; + MAX_VIEWPORT_DIMS: number; + MEDIUM_FLOAT: number; + MEDIUM_INT: number; + MIRRORED_REPEAT: number; + NEAREST: number; + NEAREST_MIPMAP_LINEAR: number; + NEAREST_MIPMAP_NEAREST: number; + NEVER: number; + NICEST: number; + NONE: number; + NOTEQUAL: number; + NO_ERROR: number; + ONE: number; + ONE_MINUS_CONSTANT_ALPHA: number; + ONE_MINUS_CONSTANT_COLOR: number; + ONE_MINUS_DST_ALPHA: number; + ONE_MINUS_DST_COLOR: number; + ONE_MINUS_SRC_ALPHA: number; + ONE_MINUS_SRC_COLOR: number; + OUT_OF_MEMORY: number; + PACK_ALIGNMENT: number; + POINTS: number; + POLYGON_OFFSET_FACTOR: number; + POLYGON_OFFSET_FILL: number; + POLYGON_OFFSET_UNITS: number; + RED_BITS: number; + RENDERBUFFER: number; + RENDERBUFFER_ALPHA_SIZE: number; + RENDERBUFFER_BINDING: number; + RENDERBUFFER_BLUE_SIZE: number; + RENDERBUFFER_DEPTH_SIZE: number; + RENDERBUFFER_GREEN_SIZE: number; + RENDERBUFFER_HEIGHT: number; + RENDERBUFFER_INTERNAL_FORMAT: number; + RENDERBUFFER_RED_SIZE: number; + RENDERBUFFER_STENCIL_SIZE: number; + RENDERBUFFER_WIDTH: number; + RENDERER: number; + REPEAT: number; + REPLACE: number; + RGB: number; + RGB565: number; + RGB5_A1: number; + RGBA: number; + RGBA4: number; + SAMPLER_2D: number; + SAMPLER_CUBE: number; + SAMPLES: number; + SAMPLE_ALPHA_TO_COVERAGE: number; + SAMPLE_BUFFERS: number; + SAMPLE_COVERAGE: number; + SAMPLE_COVERAGE_INVERT: number; + SAMPLE_COVERAGE_VALUE: number; + SCISSOR_BOX: number; + SCISSOR_TEST: number; + SHADER_TYPE: number; + SHADING_LANGUAGE_VERSION: number; + SHORT: number; + SRC_ALPHA: number; + SRC_ALPHA_SATURATE: number; + SRC_COLOR: number; + STATIC_DRAW: number; + STENCIL_ATTACHMENT: number; + STENCIL_BACK_FAIL: number; + STENCIL_BACK_FUNC: number; + STENCIL_BACK_PASS_DEPTH_FAIL: number; + STENCIL_BACK_PASS_DEPTH_PASS: number; + STENCIL_BACK_REF: number; + STENCIL_BACK_VALUE_MASK: number; + STENCIL_BACK_WRITEMASK: number; + STENCIL_BITS: number; + STENCIL_BUFFER_BIT: number; + STENCIL_CLEAR_VALUE: number; + STENCIL_FAIL: number; + STENCIL_FUNC: number; + STENCIL_INDEX: number; + STENCIL_INDEX8: number; + STENCIL_PASS_DEPTH_FAIL: number; + STENCIL_PASS_DEPTH_PASS: number; + STENCIL_REF: number; + STENCIL_TEST: number; + STENCIL_VALUE_MASK: number; + STENCIL_WRITEMASK: number; + STREAM_DRAW: number; + SUBPIXEL_BITS: number; + TEXTURE: number; + TEXTURE0: number; + TEXTURE1: number; + TEXTURE10: number; + TEXTURE11: number; + TEXTURE12: number; + TEXTURE13: number; + TEXTURE14: number; + TEXTURE15: number; + TEXTURE16: number; + TEXTURE17: number; + TEXTURE18: number; + TEXTURE19: number; + TEXTURE2: number; + TEXTURE20: number; + TEXTURE21: number; + TEXTURE22: number; + TEXTURE23: number; + TEXTURE24: number; + TEXTURE25: number; + TEXTURE26: number; + TEXTURE27: number; + TEXTURE28: number; + TEXTURE29: number; + TEXTURE3: number; + TEXTURE30: number; + TEXTURE31: number; + TEXTURE4: number; + TEXTURE5: number; + TEXTURE6: number; + TEXTURE7: number; + TEXTURE8: number; + TEXTURE9: number; + TEXTURE_2D: number; + TEXTURE_BINDING_2D: number; + TEXTURE_BINDING_CUBE_MAP: number; + TEXTURE_CUBE_MAP: number; + TEXTURE_CUBE_MAP_NEGATIVE_X: number; + TEXTURE_CUBE_MAP_NEGATIVE_Y: number; + TEXTURE_CUBE_MAP_NEGATIVE_Z: number; + TEXTURE_CUBE_MAP_POSITIVE_X: number; + TEXTURE_CUBE_MAP_POSITIVE_Y: number; + TEXTURE_CUBE_MAP_POSITIVE_Z: number; + TEXTURE_MAG_FILTER: number; + TEXTURE_MIN_FILTER: number; + TEXTURE_WRAP_S: number; + TEXTURE_WRAP_T: number; + TRIANGLES: number; + TRIANGLE_FAN: number; + TRIANGLE_STRIP: number; + UNPACK_ALIGNMENT: number; + UNPACK_COLORSPACE_CONVERSION_WEBGL: number; + UNPACK_FLIP_Y_WEBGL: number; + UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; + UNSIGNED_BYTE: number; + UNSIGNED_INT: number; + UNSIGNED_SHORT: number; + UNSIGNED_SHORT_4_4_4_4: number; + UNSIGNED_SHORT_5_5_5_1: number; + UNSIGNED_SHORT_5_6_5: number; + VALIDATE_STATUS: number; + VENDOR: number; + VERSION: number; + VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; + VERTEX_ATTRIB_ARRAY_ENABLED: number; + VERTEX_ATTRIB_ARRAY_NORMALIZED: number; + VERTEX_ATTRIB_ARRAY_POINTER: number; + VERTEX_ATTRIB_ARRAY_SIZE: number; + VERTEX_ATTRIB_ARRAY_STRIDE: number; + VERTEX_ATTRIB_ARRAY_TYPE: number; + VERTEX_SHADER: number; + VIEWPORT: number; + ZERO: number; +} + +interface WebGLShader extends WebGLObject { +} + +declare var WebGLShader: { + prototype: WebGLShader; + new(): WebGLShader; +} + +interface WebGLShaderPrecisionFormat { + precision: number; + rangeMax: number; + rangeMin: number; +} + +declare var WebGLShaderPrecisionFormat: { + prototype: WebGLShaderPrecisionFormat; + new(): WebGLShaderPrecisionFormat; +} + +interface WebGLTexture extends WebGLObject { +} + +declare var WebGLTexture: { + prototype: WebGLTexture; + new(): WebGLTexture; +} + +interface WebGLUniformLocation { +} + +declare var WebGLUniformLocation: { + prototype: WebGLUniformLocation; + new(): WebGLUniformLocation; +} + +interface WebKitCSSMatrix { + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + m11: number; + m12: number; + m13: number; + m14: number; + m21: number; + m22: number; + m23: number; + m24: number; + m31: number; + m32: number; + m33: number; + m34: number; + m41: number; + m42: number; + m43: number; + m44: number; + inverse(): WebKitCSSMatrix; + multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix; + rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix; + rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix; + scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix; + setMatrixValue(value: string): void; + skewX(angle: number): WebKitCSSMatrix; + skewY(angle: number): WebKitCSSMatrix; + toString(): string; + translate(x: number, y: number, z?: number): WebKitCSSMatrix; +} + +declare var WebKitCSSMatrix: { + prototype: WebKitCSSMatrix; + new(text?: string): WebKitCSSMatrix; +} + +interface WebKitPoint { + x: number; + y: number; +} + +declare var WebKitPoint: { + prototype: WebKitPoint; + new(x?: number, y?: number): WebKitPoint; +} + +interface WebSocket extends EventTarget { + binaryType: string; + bufferedAmount: number; + extensions: string; + onclose: (ev: CloseEvent) => any; + onerror: (ev: Event) => any; + onmessage: (ev: MessageEvent) => any; + onopen: (ev: Event) => any; + protocol: string; + readyState: number; + url: string; + close(code?: number, reason?: string): void; + send(data: any): void; + CLOSED: number; + CLOSING: number; + CONNECTING: number; + OPEN: number; + addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var WebSocket: { + prototype: WebSocket; + new(url: string, protocols?: string | string[]): WebSocket; + CLOSED: number; + CLOSING: number; + CONNECTING: number; + OPEN: number; +} + +interface WheelEvent extends MouseEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + getCurrentPoint(element: Element): void; + initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; + DOM_DELTA_LINE: number; + DOM_DELTA_PAGE: number; + DOM_DELTA_PIXEL: number; +} + +declare var WheelEvent: { + prototype: WheelEvent; + new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent; + DOM_DELTA_LINE: number; + DOM_DELTA_PAGE: number; + DOM_DELTA_PIXEL: number; +} + +interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64 { + animationStartTime: number; + applicationCache: ApplicationCache; + clientInformation: Navigator; + closed: boolean; + crypto: Crypto; + defaultStatus: string; + devicePixelRatio: number; + doNotTrack: string; + document: Document; + event: Event; + external: External; + frameElement: Element; + frames: Window; + history: History; + innerHeight: number; + innerWidth: number; + length: number; + location: Location; + locationbar: BarProp; + menubar: BarProp; + msAnimationStartTime: number; + name: string; + navigator: Navigator; + offscreenBuffering: string | boolean; + onabort: (ev: Event) => any; + onafterprint: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + onblur: (ev: FocusEvent) => any; + oncanplay: (ev: Event) => any; + oncanplaythrough: (ev: Event) => any; + onchange: (ev: Event) => any; + onclick: (ev: MouseEvent) => any; + oncompassneedscalibration: (ev: Event) => any; + oncontextmenu: (ev: PointerEvent) => any; + ondblclick: (ev: MouseEvent) => any; + ondevicemotion: (ev: DeviceMotionEvent) => any; + ondeviceorientation: (ev: DeviceOrientationEvent) => any; + ondrag: (ev: DragEvent) => any; + ondragend: (ev: DragEvent) => any; + ondragenter: (ev: DragEvent) => any; + ondragleave: (ev: DragEvent) => any; + ondragover: (ev: DragEvent) => any; + ondragstart: (ev: DragEvent) => any; + ondrop: (ev: DragEvent) => any; + ondurationchange: (ev: Event) => any; + onemptied: (ev: Event) => any; + onended: (ev: Event) => any; + onerror: ErrorEventHandler; + onfocus: (ev: FocusEvent) => any; + onhashchange: (ev: HashChangeEvent) => any; + oninput: (ev: Event) => any; + onkeydown: (ev: KeyboardEvent) => any; + onkeypress: (ev: KeyboardEvent) => any; + onkeyup: (ev: KeyboardEvent) => any; + onload: (ev: Event) => any; + onloadeddata: (ev: Event) => any; + onloadedmetadata: (ev: Event) => any; + onloadstart: (ev: Event) => any; + onmessage: (ev: MessageEvent) => any; + onmousedown: (ev: MouseEvent) => any; + onmouseenter: (ev: MouseEvent) => any; + onmouseleave: (ev: MouseEvent) => any; + onmousemove: (ev: MouseEvent) => any; + onmouseout: (ev: MouseEvent) => any; + onmouseover: (ev: MouseEvent) => any; + onmouseup: (ev: MouseEvent) => any; + onmousewheel: (ev: MouseWheelEvent) => any; + onmsgesturechange: (ev: MSGestureEvent) => any; + onmsgesturedoubletap: (ev: MSGestureEvent) => any; + onmsgestureend: (ev: MSGestureEvent) => any; + onmsgesturehold: (ev: MSGestureEvent) => any; + onmsgesturestart: (ev: MSGestureEvent) => any; + onmsgesturetap: (ev: MSGestureEvent) => any; + onmsinertiastart: (ev: MSGestureEvent) => any; + onmspointercancel: (ev: MSPointerEvent) => any; + onmspointerdown: (ev: MSPointerEvent) => any; + onmspointerenter: (ev: MSPointerEvent) => any; + onmspointerleave: (ev: MSPointerEvent) => any; + onmspointermove: (ev: MSPointerEvent) => any; + onmspointerout: (ev: MSPointerEvent) => any; + onmspointerover: (ev: MSPointerEvent) => any; + onmspointerup: (ev: MSPointerEvent) => any; + onoffline: (ev: Event) => any; + ononline: (ev: Event) => any; + onorientationchange: (ev: Event) => any; + onpagehide: (ev: PageTransitionEvent) => any; + onpageshow: (ev: PageTransitionEvent) => any; + onpause: (ev: Event) => any; + onplay: (ev: Event) => any; + onplaying: (ev: Event) => any; + onpopstate: (ev: PopStateEvent) => any; + onprogress: (ev: ProgressEvent) => any; + onratechange: (ev: Event) => any; + onreadystatechange: (ev: ProgressEvent) => any; + onreset: (ev: Event) => any; + onresize: (ev: UIEvent) => any; + onscroll: (ev: UIEvent) => any; + onseeked: (ev: Event) => any; + onseeking: (ev: Event) => any; + onselect: (ev: UIEvent) => any; + onstalled: (ev: Event) => any; + onstorage: (ev: StorageEvent) => any; + onsubmit: (ev: Event) => any; + onsuspend: (ev: Event) => any; + ontimeupdate: (ev: Event) => any; + ontouchcancel: any; + ontouchend: any; + ontouchmove: any; + ontouchstart: any; + onunload: (ev: Event) => any; + onvolumechange: (ev: Event) => any; + onwaiting: (ev: Event) => any; + opener: Window; + orientation: string | number; + outerHeight: number; + outerWidth: number; + pageXOffset: number; + pageYOffset: number; + parent: Window; + performance: Performance; + personalbar: BarProp; + screen: Screen; + screenLeft: number; + screenTop: number; + screenX: number; + screenY: number; + scrollX: number; + scrollY: number; + scrollbars: BarProp; + self: Window; + status: string; + statusbar: BarProp; + styleMedia: StyleMedia; + toolbar: BarProp; + top: Window; + window: Window; + URL: URL; + alert(message?: any): void; + blur(): void; + cancelAnimationFrame(handle: number): void; + captureEvents(): void; + close(): void; + confirm(message?: string): boolean; + focus(): void; + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; + getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; + getSelection(): Selection; + matchMedia(mediaQuery: string): MediaQueryList; + moveBy(x?: number, y?: number): void; + moveTo(x?: number, y?: number): void; + msCancelRequestAnimationFrame(handle: number): void; + msMatchMedia(mediaQuery: string): MediaQueryList; + msRequestAnimationFrame(callback: FrameRequestCallback): number; + msWriteProfilerMark(profilerMarkName: string): void; + open(url?: string, target?: string, features?: string, replace?: boolean): Window; + postMessage(message: any, targetOrigin: string, ports?: any): void; + print(): void; + prompt(message?: string, _default?: string): string; + releaseEvents(): void; + requestAnimationFrame(callback: FrameRequestCallback): number; + resizeBy(x?: number, y?: number): void; + resizeTo(x?: number, y?: number): void; + scroll(x?: number, y?: number): void; + scrollBy(x?: number, y?: number): void; + scrollTo(x?: number, y?: number): void; + webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; + webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "compassneedscalibration", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; + addEventListener(type: "hashchange", listener: (ev: HashChangeEvent) => any, useCapture?: boolean): void; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; + addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "orientationchange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + [index: number]: Window; +} + +declare var Window: { + prototype: Window; + new(): Window; +} + +interface Worker extends EventTarget, AbstractWorker { + onmessage: (ev: MessageEvent) => any; + postMessage(message: any, ports?: any): void; + terminate(): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var Worker: { + prototype: Worker; + new(stringUrl: string): Worker; +} + +interface XMLDocument extends Document { +} + +declare var XMLDocument: { + prototype: XMLDocument; + new(): XMLDocument; +} + +interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { + msCaching: string; + onreadystatechange: (ev: ProgressEvent) => any; + readyState: number; + response: any; + responseBody: any; + responseText: string; + responseType: string; + responseXML: any; + status: number; + statusText: string; + timeout: number; + upload: XMLHttpRequestUpload; + withCredentials: boolean; + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string; + msCachingEnabled(): boolean; + open(method: string, url: string, async?: boolean, user?: string, password?: string): void; + overrideMimeType(mime: string): void; + send(data?: Document): void; + send(data?: string): void; + send(data?: any): void; + setRequestHeader(header: string, value: string): void; + DONE: number; + HEADERS_RECEIVED: number; + LOADING: number; + OPENED: number; + UNSENT: number; + addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeout", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new(): XMLHttpRequest; + DONE: number; + HEADERS_RECEIVED: number; + LOADING: number; + OPENED: number; + UNSENT: number; + create(): XMLHttpRequest; +} + +interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var XMLHttpRequestUpload: { + prototype: XMLHttpRequestUpload; + new(): XMLHttpRequestUpload; +} + +interface XMLSerializer { + serializeToString(target: Node): string; +} + +declare var XMLSerializer: { + prototype: XMLSerializer; + new(): XMLSerializer; +} + +interface XPathEvaluator { + createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; + createNSResolver(nodeResolver?: Node): XPathNSResolver; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; +} + +declare var XPathEvaluator: { + prototype: XPathEvaluator; + new(): XPathEvaluator; +} + +interface XPathExpression { + evaluate(contextNode: Node, type: number, result: XPathResult): XPathExpression; +} + +declare var XPathExpression: { + prototype: XPathExpression; + new(): XPathExpression; +} + +interface XPathNSResolver { + lookupNamespaceURI(prefix: string): string; +} + +declare var XPathNSResolver: { + prototype: XPathNSResolver; + new(): XPathNSResolver; +} + +interface XPathResult { + booleanValue: boolean; + invalidIteratorState: boolean; + numberValue: number; + resultType: number; + singleNodeValue: Node; + snapshotLength: number; + stringValue: string; + iterateNext(): Node; + snapshotItem(index: number): Node; + ANY_TYPE: number; + ANY_UNORDERED_NODE_TYPE: number; + BOOLEAN_TYPE: number; + FIRST_ORDERED_NODE_TYPE: number; + NUMBER_TYPE: number; + ORDERED_NODE_ITERATOR_TYPE: number; + ORDERED_NODE_SNAPSHOT_TYPE: number; + STRING_TYPE: number; + UNORDERED_NODE_ITERATOR_TYPE: number; + UNORDERED_NODE_SNAPSHOT_TYPE: number; +} + +declare var XPathResult: { + prototype: XPathResult; + new(): XPathResult; + ANY_TYPE: number; + ANY_UNORDERED_NODE_TYPE: number; + BOOLEAN_TYPE: number; + FIRST_ORDERED_NODE_TYPE: number; + NUMBER_TYPE: number; + ORDERED_NODE_ITERATOR_TYPE: number; + ORDERED_NODE_SNAPSHOT_TYPE: number; + STRING_TYPE: number; + UNORDERED_NODE_ITERATOR_TYPE: number; + UNORDERED_NODE_SNAPSHOT_TYPE: number; +} + +interface XSLTProcessor { + clearParameters(): void; + getParameter(namespaceURI: string, localName: string): any; + importStylesheet(style: Node): void; + removeParameter(namespaceURI: string, localName: string): void; + reset(): void; + setParameter(namespaceURI: string, localName: string, value: any): void; + transformToDocument(source: Node): Document; + transformToFragment(source: Node, document: Document): DocumentFragment; +} + +declare var XSLTProcessor: { + prototype: XSLTProcessor; + new(): XSLTProcessor; +} + +interface AbstractWorker { + onerror: (ev: Event) => any; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface ChildNode { + remove(): void; +} + +interface DOML2DeprecatedColorProperty { + color: string; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface DocumentEvent { + createEvent(eventInterface:"AnimationEvent"): AnimationEvent; + 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:"DeviceMotionEvent"): DeviceMotionEvent; + createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent; + createEvent(eventInterface:"DragEvent"): DragEvent; + createEvent(eventInterface:"ErrorEvent"): ErrorEvent; + createEvent(eventInterface:"Event"): Event; + createEvent(eventInterface:"Events"): Event; + createEvent(eventInterface:"FocusEvent"): FocusEvent; + createEvent(eventInterface:"GamepadEvent"): GamepadEvent; + createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent; + createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent; + createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent; + createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent; + createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent; + createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent; + createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; + createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; + createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent; + createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent; + createEvent(eventInterface:"MessageEvent"): MessageEvent; + createEvent(eventInterface:"MouseEvent"): MouseEvent; + createEvent(eventInterface:"MouseEvents"): MouseEvent; + createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent; + createEvent(eventInterface:"MutationEvent"): MutationEvent; + createEvent(eventInterface:"MutationEvents"): MutationEvent; + createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent; + createEvent(eventInterface:"NavigationEvent"): NavigationEvent; + createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer; + createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; + createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent; + createEvent(eventInterface:"PointerEvent"): PointerEvent; + createEvent(eventInterface:"PopStateEvent"): PopStateEvent; + createEvent(eventInterface:"ProgressEvent"): ProgressEvent; + createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent; + createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent; + createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent; + createEvent(eventInterface:"StorageEvent"): StorageEvent; + createEvent(eventInterface:"TextEvent"): TextEvent; + createEvent(eventInterface:"TouchEvent"): TouchEvent; + createEvent(eventInterface:"TrackEvent"): TrackEvent; + createEvent(eventInterface:"TransitionEvent"): TransitionEvent; + createEvent(eventInterface:"UIEvent"): UIEvent; + createEvent(eventInterface:"UIEvents"): UIEvent; + createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent; + createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent; + createEvent(eventInterface:"WheelEvent"): WheelEvent; + createEvent(eventInterface: string): Event; +} + +interface ElementTraversal { + childElementCount: number; + firstElementChild: Element; + lastElementChild: Element; + nextElementSibling: Element; + previousElementSibling: Element; +} + +interface GetSVGDocument { + getSVGDocument(): Document; +} + +interface GlobalEventHandlers { + onpointercancel: (ev: PointerEvent) => any; + onpointerdown: (ev: PointerEvent) => any; + onpointerenter: (ev: PointerEvent) => any; + onpointerleave: (ev: PointerEvent) => any; + onpointermove: (ev: PointerEvent) => any; + onpointerout: (ev: PointerEvent) => any; + onpointerover: (ev: PointerEvent) => any; + onpointerup: (ev: PointerEvent) => any; + onwheel: (ev: WheelEvent) => any; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface HTMLTableAlignment { + /** + * Sets or retrieves a value that you can use to implement your own ch functionality for the object. + */ + ch: string; + /** + * Sets or retrieves a value that you can use to implement your own chOff functionality for the object. + */ + chOff: string; + /** + * Sets or retrieves how text and other content are vertically aligned within the object that contains them. + */ + vAlign: string; +} + +interface IDBEnvironment { + indexedDB: IDBFactory; + msIndexedDB: IDBFactory; +} + +interface LinkStyle { + sheet: StyleSheet; +} + +interface MSBaseReader { + onabort: (ev: Event) => any; + onerror: (ev: Event) => any; + onload: (ev: Event) => any; + onloadend: (ev: ProgressEvent) => any; + onloadstart: (ev: Event) => any; + onprogress: (ev: ProgressEvent) => any; + readyState: number; + result: any; + abort(): void; + DONE: number; + EMPTY: number; + LOADING: number; + addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): boolean; + msSaveOrOpenBlob(blob: any, defaultName?: string): boolean; +} + +interface MSNavigatorDoNotTrack { + confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean; + confirmWebWideTrackingException(args: ExceptionInformation): boolean; + removeSiteSpecificTrackingException(args: ExceptionInformation): void; + removeWebWideTrackingException(args: ExceptionInformation): void; + storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void; + storeWebWideTrackingException(args: StoreExceptionsInformation): void; +} + +interface NavigatorContentUtils { +} + +interface NavigatorGeolocation { + geolocation: Geolocation; +} + +interface NavigatorID { + appName: string; + appVersion: string; + platform: string; + product: string; + productSub: string; + userAgent: string; + vendor: string; + vendorSub: string; +} + +interface NavigatorOnLine { + onLine: boolean; +} + +interface NavigatorStorageUtils { +} + +interface NodeSelector { + querySelector(selectors: string): Element; + querySelectorAll(selectors: string): NodeListOf; +} + +interface RandomSource { + getRandomValues(array: ArrayBufferView): ArrayBufferView; +} + +interface SVGAnimatedPathData { + pathSegList: SVGPathSegList; +} + +interface SVGAnimatedPoints { + animatedPoints: SVGPointList; + points: SVGPointList; +} + +interface SVGExternalResourcesRequired { + externalResourcesRequired: SVGAnimatedBoolean; +} + +interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { + height: SVGAnimatedLength; + result: SVGAnimatedString; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + y: SVGAnimatedLength; +} + +interface SVGFitToViewBox { + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + viewBox: SVGAnimatedRect; +} + +interface SVGLangSpace { + xmllang: string; + xmlspace: string; +} + +interface SVGLocatable { + farthestViewportElement: SVGElement; + nearestViewportElement: SVGElement; + getBBox(): SVGRect; + getCTM(): SVGMatrix; + getScreenCTM(): SVGMatrix; + getTransformToElement(element: SVGElement): SVGMatrix; +} + +interface SVGStylable { + className: any; + style: CSSStyleDeclaration; +} + +interface SVGTests { + requiredExtensions: SVGStringList; + requiredFeatures: SVGStringList; + systemLanguage: SVGStringList; + hasExtension(extension: string): boolean; +} + +interface SVGTransformable extends SVGLocatable { + transform: SVGAnimatedTransformList; +} + +interface SVGURIReference { + href: SVGAnimatedString; +} + +interface WindowBase64 { + atob(encodedString: string): string; + btoa(rawString: string): string; +} + +interface WindowConsole { + console: Console; +} + +interface WindowLocalStorage { + localStorage: Storage; +} + +interface WindowSessionStorage { + sessionStorage: Storage; +} + +interface WindowTimers extends Object, WindowTimersExtension { + clearInterval(handle: number): void; + clearTimeout(handle: number): void; + setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: any, timeout?: any, ...args: any[]): number; +} + +interface WindowTimersExtension { + clearImmediate(handle: number): void; + msClearImmediate(handle: number): void; + msSetImmediate(expression: any, ...args: any[]): number; + setImmediate(expression: any, ...args: any[]): number; +} + +interface XMLHttpRequestEventTarget { + onabort: (ev: Event) => any; + onerror: (ev: Event) => any; + onload: (ev: Event) => any; + onloadend: (ev: ProgressEvent) => any; + onloadstart: (ev: Event) => any; + onprogress: (ev: ProgressEvent) => any; + ontimeout: (ev: ProgressEvent) => any; + addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "timeout", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +interface StorageEventInit extends EventInit { + key?: string; + oldValue?: string; + newValue?: string; + url: string; + storageArea?: Storage; +} + +interface IDBObjectStoreParameters { + keyPath?: string | string[]; + autoIncrement?: boolean; +} + +interface IDBIndexParameters { + unique?: boolean; + multiEntry?: boolean; +} + +interface NodeListOf extends NodeList { + length: number; + item(index: number): TNode; + [index: number]: TNode; +} + +interface BlobPropertyBag { + type?: string; + endings?: string; +} + +interface FilePropertyBag { + type?: string; + lastModified?: number; +} + +interface EventListenerObject { + handleEvent(evt: Event): void; +} + +interface MessageEventInit extends EventInit { + data?: any; + origin?: string; + lastEventId?: string; + channel?: string; + source?: any; + ports?: MessagePort[]; +} + +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + +interface HTMLTemplateElement extends HTMLElement { + content: DocumentFragment; +} + +declare var HTMLTemplateElement: { + prototype: HTMLTemplateElement; + new(): HTMLTemplateElement; +} + +interface HTMLPictureElement extends HTMLElement { +} + +declare var HTMLPictureElement: { + prototype: HTMLPictureElement; + new(): HTMLPictureElement; +} + +declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; + +interface ErrorEventHandler { + (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void; +} +interface PositionCallback { + (position: Position): void; +} +interface PositionErrorCallback { + (error: PositionError): void; +} +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} +interface MSLaunchUriCallback { + (): void; +} +interface FrameRequestCallback { + (time: number): void; +} +interface MSUnsafeFunctionCallback { + (): any; +} +interface MSExecAtPriorityFunctionCallback { + (...args: any[]): any; +} +interface MutationCallback { + (mutations: MutationRecord[], observer: MutationObserver): void; +} +interface DecodeSuccessCallback { + (decodedData: AudioBuffer): void; +} +interface DecodeErrorCallback { + (error: DOMException): void; +} +interface FunctionStringCallback { + (data: string): void; +} +declare var Audio: {new(src?: string): HTMLAudioElement; }; +declare var Image: {new(width?: number, height?: number): HTMLImageElement; }; +declare var Option: {new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement; }; +declare var animationStartTime: number; +declare var applicationCache: ApplicationCache; +declare var clientInformation: Navigator; +declare var closed: boolean; +declare var crypto: Crypto; +declare var defaultStatus: string; +declare var devicePixelRatio: number; +declare var doNotTrack: string; +declare var document: Document; +declare var event: Event; +declare var external: External; +declare var frameElement: Element; +declare var frames: Window; +declare var history: History; +declare var innerHeight: number; +declare var innerWidth: number; +declare var length: number; +declare var location: Location; +declare var locationbar: BarProp; +declare var menubar: BarProp; +declare var msAnimationStartTime: number; +declare var name: string; +declare var navigator: Navigator; +declare var offscreenBuffering: string | boolean; +declare var onabort: (ev: Event) => any; +declare var onafterprint: (ev: Event) => any; +declare var onbeforeprint: (ev: Event) => any; +declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; +declare var onblur: (ev: FocusEvent) => any; +declare var oncanplay: (ev: Event) => any; +declare var oncanplaythrough: (ev: Event) => any; +declare var onchange: (ev: Event) => any; +declare var onclick: (ev: MouseEvent) => any; +declare var oncompassneedscalibration: (ev: Event) => any; +declare var oncontextmenu: (ev: PointerEvent) => any; +declare var ondblclick: (ev: MouseEvent) => any; +declare var ondevicemotion: (ev: DeviceMotionEvent) => any; +declare var ondeviceorientation: (ev: DeviceOrientationEvent) => any; +declare var ondrag: (ev: DragEvent) => any; +declare var ondragend: (ev: DragEvent) => any; +declare var ondragenter: (ev: DragEvent) => any; +declare var ondragleave: (ev: DragEvent) => any; +declare var ondragover: (ev: DragEvent) => any; +declare var ondragstart: (ev: DragEvent) => any; +declare var ondrop: (ev: DragEvent) => any; +declare var ondurationchange: (ev: Event) => any; +declare var onemptied: (ev: Event) => any; +declare var onended: (ev: Event) => any; +declare var onerror: ErrorEventHandler; +declare var onfocus: (ev: FocusEvent) => any; +declare var onhashchange: (ev: HashChangeEvent) => any; +declare var oninput: (ev: Event) => any; +declare var onkeydown: (ev: KeyboardEvent) => any; +declare var onkeypress: (ev: KeyboardEvent) => any; +declare var onkeyup: (ev: KeyboardEvent) => any; +declare var onload: (ev: Event) => any; +declare var onloadeddata: (ev: Event) => any; +declare var onloadedmetadata: (ev: Event) => any; +declare var onloadstart: (ev: Event) => any; +declare var onmessage: (ev: MessageEvent) => any; +declare var onmousedown: (ev: MouseEvent) => any; +declare var onmouseenter: (ev: MouseEvent) => any; +declare var onmouseleave: (ev: MouseEvent) => any; +declare var onmousemove: (ev: MouseEvent) => any; +declare var onmouseout: (ev: MouseEvent) => any; +declare var onmouseover: (ev: MouseEvent) => any; +declare var onmouseup: (ev: MouseEvent) => any; +declare var onmousewheel: (ev: MouseWheelEvent) => any; +declare var onmsgesturechange: (ev: MSGestureEvent) => any; +declare var onmsgesturedoubletap: (ev: MSGestureEvent) => any; +declare var onmsgestureend: (ev: MSGestureEvent) => any; +declare var onmsgesturehold: (ev: MSGestureEvent) => any; +declare var onmsgesturestart: (ev: MSGestureEvent) => any; +declare var onmsgesturetap: (ev: MSGestureEvent) => any; +declare var onmsinertiastart: (ev: MSGestureEvent) => any; +declare var onmspointercancel: (ev: MSPointerEvent) => any; +declare var onmspointerdown: (ev: MSPointerEvent) => any; +declare var onmspointerenter: (ev: MSPointerEvent) => any; +declare var onmspointerleave: (ev: MSPointerEvent) => any; +declare var onmspointermove: (ev: MSPointerEvent) => any; +declare var onmspointerout: (ev: MSPointerEvent) => any; +declare var onmspointerover: (ev: MSPointerEvent) => any; +declare var onmspointerup: (ev: MSPointerEvent) => any; +declare var onoffline: (ev: Event) => any; +declare var ononline: (ev: Event) => any; +declare var onorientationchange: (ev: Event) => any; +declare var onpagehide: (ev: PageTransitionEvent) => any; +declare var onpageshow: (ev: PageTransitionEvent) => any; +declare var onpause: (ev: Event) => any; +declare var onplay: (ev: Event) => any; +declare var onplaying: (ev: Event) => any; +declare var onpopstate: (ev: PopStateEvent) => any; +declare var onprogress: (ev: ProgressEvent) => any; +declare var onratechange: (ev: Event) => any; +declare var onreadystatechange: (ev: ProgressEvent) => any; +declare var onreset: (ev: Event) => any; +declare var onresize: (ev: UIEvent) => any; +declare var onscroll: (ev: UIEvent) => any; +declare var onseeked: (ev: Event) => any; +declare var onseeking: (ev: Event) => any; +declare var onselect: (ev: UIEvent) => any; +declare var onstalled: (ev: Event) => any; +declare var onstorage: (ev: StorageEvent) => any; +declare var onsubmit: (ev: Event) => any; +declare var onsuspend: (ev: Event) => any; +declare var ontimeupdate: (ev: Event) => any; +declare var ontouchcancel: any; +declare var ontouchend: any; +declare var ontouchmove: any; +declare var ontouchstart: any; +declare var onunload: (ev: Event) => any; +declare var onvolumechange: (ev: Event) => any; +declare var onwaiting: (ev: Event) => any; +declare var opener: Window; +declare var orientation: string | number; +declare var outerHeight: number; +declare var outerWidth: number; +declare var pageXOffset: number; +declare var pageYOffset: number; +declare var parent: Window; +declare var performance: Performance; +declare var personalbar: BarProp; +declare var screen: Screen; +declare var screenLeft: number; +declare var screenTop: number; +declare var screenX: number; +declare var screenY: number; +declare var scrollX: number; +declare var scrollY: number; +declare var scrollbars: BarProp; +declare var self: Window; +declare var status: string; +declare var statusbar: BarProp; +declare var styleMedia: StyleMedia; +declare var toolbar: BarProp; +declare var top: Window; +declare var window: Window; +declare var URL: URL; +declare function alert(message?: any): void; +declare function blur(): void; +declare function cancelAnimationFrame(handle: number): void; +declare function captureEvents(): void; +declare function close(): void; +declare function confirm(message?: string): boolean; +declare function focus(): void; +declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +declare function getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList; +declare function getSelection(): Selection; +declare function matchMedia(mediaQuery: string): MediaQueryList; +declare function moveBy(x?: number, y?: number): void; +declare function moveTo(x?: number, y?: number): void; +declare function msCancelRequestAnimationFrame(handle: number): void; +declare function msMatchMedia(mediaQuery: string): MediaQueryList; +declare function msRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function msWriteProfilerMark(profilerMarkName: string): void; +declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window; +declare function postMessage(message: any, targetOrigin: string, ports?: any): void; +declare function print(): void; +declare function prompt(message?: string, _default?: string): string; +declare function releaseEvents(): void; +declare function requestAnimationFrame(callback: FrameRequestCallback): number; +declare function resizeBy(x?: number, y?: number): void; +declare function resizeTo(x?: number, y?: number): void; +declare function scroll(x?: number, y?: number): void; +declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(x?: number, y?: number): void; +declare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint; +declare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint; +declare function toString(): string; +declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +declare function dispatchEvent(evt: Event): boolean; +declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +declare function clearInterval(handle: number): void; +declare function clearTimeout(handle: number): void; +declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; +declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; +declare function clearImmediate(handle: number): void; +declare function msClearImmediate(handle: number): void; +declare function msSetImmediate(expression: any, ...args: any[]): number; +declare function setImmediate(expression: any, ...args: any[]): number; +declare var sessionStorage: Storage; +declare var localStorage: Storage; +declare var console: Console; +declare var onpointercancel: (ev: PointerEvent) => any; +declare var onpointerdown: (ev: PointerEvent) => any; +declare var onpointerenter: (ev: PointerEvent) => any; +declare var onpointerleave: (ev: PointerEvent) => any; +declare var onpointermove: (ev: PointerEvent) => any; +declare var onpointerout: (ev: PointerEvent) => any; +declare var onpointerover: (ev: PointerEvent) => any; +declare var onpointerup: (ev: PointerEvent) => any; +declare var onwheel: (ev: WheelEvent) => any; +declare var indexedDB: IDBFactory; +declare var msIndexedDB: IDBFactory; +declare function atob(encodedString: string): string; +declare function btoa(rawString: string): string; +declare function addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "afterprint", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "beforeprint", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "beforeunload", listener: (ev: BeforeUnloadEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "compassneedscalibration", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "hashchange", listener: (ev: HashChangeEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "orientationchange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pagehide", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pageshow", listener: (ev: PageTransitionEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "popstate", listener: (ev: PopStateEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "readystatechange", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "storage", listener: (ev: StorageEvent) => any, useCapture?: boolean): void; +declare function addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): void; +declare function addEventListener(type: "unload", listener: (ev: Event) => any, useCapture?: boolean): void; +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;interface DOMTokenList { + [Symbol.iterator](): IterableIterator; +} + +interface NodeList { + [Symbol.iterator](): IterableIterator +} + +interface NodeListOf { + [Symbol.iterator](): IterableIterator +} + +///////////////////////////// +/// WorkerGlobalScope APIs +///////////////////////////// +// These are only available in a Web Worker +declare function importScripts(...urls: string[]): void; + + +///////////////////////////// +/// Windows Script Host APIS +///////////////////////////// + + +interface ActiveXObject { + new (s: string): any; +} +declare var ActiveXObject: ActiveXObject; + +interface ITextWriter { + Write(s: string): void; + WriteLine(s: string): void; + Close(): void; +} + +interface TextStreamBase { + /** + * The column number of the current character position in an input stream. + */ + Column: number; + + /** + * The current line number in an input stream. + */ + Line: number; + + /** + * Closes a text stream. + * It is not necessary to close standard streams; they close automatically when the process ends. If + * you close a standard stream, be aware that any other pointers to that standard stream become invalid. + */ + Close(): void; +} + +interface TextStreamWriter extends TextStreamBase { + /** + * Sends a string to an output stream. + */ + Write(s: string): void; + + /** + * Sends a specified number of blank lines (newline characters) to an output stream. + */ + WriteBlankLines(intLines: number): void; + + /** + * Sends a string followed by a newline character to an output stream. + */ + WriteLine(s: string): void; +} + +interface TextStreamReader extends TextStreamBase { + /** + * Returns a specified number of characters from an input stream, starting at the current pointer position. + * Does not return until the ENTER key is pressed. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + Read(characters: number): string; + + /** + * Returns all characters from an input stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadAll(): string; + + /** + * Returns an entire line from an input stream. + * Although this method extracts the newline character, it does not add it to the returned string. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + */ + ReadLine(): string; + + /** + * Skips a specified number of characters when reading from an input text stream. + * Can only be used on a stream in reading mode; causes an error in writing or appending mode. + * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) + */ + Skip(characters: number): void; + + /** + * Skips the next line when reading from an input text stream. + * Can only be used on a stream in reading mode, not writing or appending mode. + */ + SkipLine(): void; + + /** + * Indicates whether the stream pointer position is at the end of a line. + */ + AtEndOfLine: boolean; + + /** + * Indicates whether the stream pointer position is at the end of a stream. + */ + AtEndOfStream: boolean; +} + +declare var WScript: { + /** + * Outputs text to either a message box (under WScript.exe) or the command console window followed by + * a newline (under CScript.exe). + */ + Echo(s: any): void; + + /** + * Exposes the write-only error output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdErr: TextStreamWriter; + + /** + * Exposes the write-only output stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdOut: TextStreamWriter; + Arguments: { length: number; Item(n: number): string; }; + + /** + * The full path of the currently running script. + */ + ScriptFullName: string; + + /** + * Forces the script to stop immediately, with an optional exit code. + */ + Quit(exitCode?: number): number; + + /** + * The Windows Script Host build version number. + */ + BuildVersion: number; + + /** + * Fully qualified path of the host executable. + */ + FullName: string; + + /** + * Gets/sets the script mode - interactive(true) or batch(false). + */ + Interactive: boolean; + + /** + * The name of the host executable (WScript.exe or CScript.exe). + */ + Name: string; + + /** + * Path of the directory containing the host executable. + */ + Path: string; + + /** + * The filename of the currently running script. + */ + ScriptName: string; + + /** + * Exposes the read-only input stream for the current script. + * Can be accessed only while using CScript.exe. + */ + StdIn: TextStreamReader; + + /** + * Windows Script Host version + */ + Version: string; + + /** + * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. + */ + ConnectObject(objEventSource: any, strPrefix: string): void; + + /** + * Creates a COM object. + * @param strProgiID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + CreateObject(strProgID: string, strPrefix?: string): any; + + /** + * Disconnects a COM object from its event sources. + */ + DisconnectObject(obj: any): void; + + /** + * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. + * @param strPathname Fully qualified path to the file containing the object persisted to disk. + * For objects in memory, pass a zero-length string. + * @param strProgID + * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. + */ + GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; + + /** + * Suspends script execution for a specified length of time, then continues execution. + * @param intTime Interval (in milliseconds) to suspend script execution. + */ + Sleep(intTime: number): void; +}; + +/** + * Allows enumerating over a COM collection, which may not have indexed item access. + */ +interface Enumerator { + /** + * Returns true if the current item is the last one in the collection, or the collection is empty, + * or the current item is undefined. + */ + atEnd(): boolean; + + /** + * Returns the current item in the collection + */ + item(): T; + + /** + * Resets the current item in the collection to the first item. If there are no items in the collection, + * the current item is set to undefined. + */ + moveFirst(): void; + + /** + * Moves the current item to the next item in the collection. If the enumerator is at the end of + * the collection or the collection is empty, the current item is set to undefined. + */ + moveNext(): void; +} + +interface EnumeratorConstructor { + new (collection: any): Enumerator; + new (collection: any): Enumerator; +} + +declare var Enumerator: EnumeratorConstructor; + +/** + * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. + */ +interface VBArray { + /** + * Returns the number of dimensions (1-based). + */ + dimensions(): number; + + /** + * Takes an index for each dimension in the array, and returns the item at the corresponding location. + */ + getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; + + /** + * Returns the smallest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + lbound(dimension?: number): number; + + /** + * Returns the largest available index for a given dimension. + * @param dimension 1-based dimension (defaults to 1) + */ + ubound(dimension?: number): number; + + /** + * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, + * each successive dimension is appended to the end of the array. + * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] + */ + toArray(): T[]; +} + +interface VBArrayConstructor { + new (safeArray: any): VBArray; + new (safeArray: any): VBArray; +} + +declare var VBArray: VBArrayConstructor; diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 7ce06a6b4ac..43bc6fad9a0 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -286,7 +286,7 @@ interface Console { select(element: any): void; time(timerName?: string): void; timeEnd(timerName?: string): void; - trace(): void; + trace(message?: any, ...optionalParams: any[]): void; warn(message?: any, ...optionalParams: any[]): void; } @@ -492,7 +492,7 @@ interface IDBCursor { direction: string; key: any; primaryKey: any; - source: any; + source: IDBObjectStore | IDBIndex; advance(count: number): void; continue(key?: any): void; delete(): IDBRequest; @@ -526,11 +526,11 @@ interface IDBDatabase extends EventTarget { objectStoreNames: DOMStringList; onabort: (ev: Event) => any; onerror: (ev: Event) => any; - version: string; + version: number; close(): void; - createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; + createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore; deleteObjectStore(name: string): void; - transaction(storeNames: any, mode?: string): IDBTransaction; + transaction(storeNames: string | string[], mode?: string): IDBTransaction; addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -553,10 +553,11 @@ declare var IDBFactory: { } interface IDBIndex { - keyPath: string; + keyPath: string | string[]; name: string; objectStore: IDBObjectStore; unique: boolean; + multiEntry: boolean; count(key?: any): IDBRequest; get(key: any): IDBRequest; getKey(key: any): IDBRequest; @@ -587,13 +588,14 @@ declare var IDBKeyRange: { interface IDBObjectStore { indexNames: DOMStringList; - keyPath: string; + keyPath: string | string[]; name: string; transaction: IDBTransaction; + autoIncrement: boolean; add(value: any, key?: any): IDBRequest; clear(): IDBRequest; count(key?: any): IDBRequest; - createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; + createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex; delete(key: any): IDBRequest; deleteIndex(indexName: string): void; get(key: any): IDBRequest; @@ -628,7 +630,7 @@ interface IDBRequest extends EventTarget { onsuccess: (ev: Event) => any; readyState: string; result: any; - source: any; + source: IDBObjectStore | IDBIndex | IDBCursor; transaction: IDBTransaction; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void; @@ -677,7 +679,7 @@ declare var IDBVersionChangeEvent: { } interface ImageData { - data: number[]; + data: Uint8ClampedArray; height: number; width: number; } @@ -1109,6 +1111,16 @@ interface WorkerUtils extends Object, WindowBase64 { setTimeout(handler: any, timeout?: any, ...args: any[]): number; } +interface IDBObjectStoreParameters { + keyPath?: string | string[]; + autoIncrement?: boolean; +} + +interface IDBIndexParameters { + unique?: boolean; + multiEntry?: boolean; +} + interface BlobPropertyBag { type?: string; endings?: string; @@ -1165,7 +1177,7 @@ interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } interface DecodeErrorCallback { - (): void; + (error: DOMException): void; } interface FunctionStringCallback { (data: string): void; diff --git a/lib/tsc.js b/lib/tsc.js index bbbcedf0f47..4bdf0f84fae 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -19,7 +19,7 @@ var ts; function OperationCanceledException() { } return OperationCanceledException; - })(); + }()); ts.OperationCanceledException = OperationCanceledException; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -46,6 +46,21 @@ var ts; DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); var DiagnosticCategory = ts.DiagnosticCategory; + (function (ModuleResolutionKind) { + ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; + ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; + })(ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleResolutionKind = ts.ModuleResolutionKind; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; + ModuleKind[ModuleKind["System"] = 4] = "System"; + ModuleKind[ModuleKind["ES6"] = 5] = "ES6"; + ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + })(ts.ModuleKind || (ts.ModuleKind = {})); + var ModuleKind = ts.ModuleKind; })(ts || (ts = {})); var ts; (function (ts) { @@ -247,9 +262,11 @@ var ts; var count = array.length; if (count > 0) { var pos = 0; - var result = arguments.length <= 2 ? array[pos++] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos++; while (pos < count) { - result = f(result, array[pos++]); + result = f(result, array[pos]); + pos++; } return result; } @@ -261,9 +278,11 @@ var ts; if (array) { var pos = array.length - 1; if (pos >= 0) { - var result = arguments.length <= 2 ? array[pos--] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos--; while (pos >= 0) { - result = f(result, array[pos--]); + result = f(result, array[pos]); + pos--; } return result; } @@ -346,6 +365,22 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function reduceProperties(map, callback, initial) { + var result = initial; + if (map) { + for (var key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } + } + return result; + } + ts.reduceProperties = reduceProperties; + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; function memoize(callback) { var value; return function () { @@ -390,6 +425,14 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; + function formatMessage(dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; function createCompilerDiagnostic(message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 1) { @@ -616,7 +659,8 @@ var ts; if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { directoryComponents.length--; } - for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { + var joinStartIndex; + for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { break; } @@ -639,7 +683,7 @@ var ts; } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; function getBaseFileName(path) { - if (!path) { + if (path === undefined) { return undefined; } var i = path.lastIndexOf(ts.directorySeparator); @@ -664,14 +708,19 @@ var ts; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; - ts.supportedExtensions = [".ts", ".tsx", ".d.ts"]; - ts.moduleFileExtensions = ts.supportedExtensions; - function isSupportedSourceFileName(fileName) { + ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedJavascriptExtensions = [".js", ".jsx"]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options) { + return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + ts.getSupportedExtensions = getSupportedExtensions; + function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; } - for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; + for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -690,22 +739,6 @@ var ts; return path; } ts.removeFileExtension = removeFileExtension; - var backslashOrDoubleQuote = /[\"\\]/g; - var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { - "\0": "\\0", - "\t": "\\t", - "\v": "\\v", - "\f": "\\f", - "\b": "\\b", - "\r": "\\r", - "\n": "\\n", - "\\": "\\\\", - "\"": "\\\"", - "\u2028": "\\u2028", - "\u2029": "\\u2029", - "\u0085": "\\u0085" - }; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -716,17 +749,16 @@ var ts; } function Signature(checker) { } + function Node(kind, pos, end) { + this.kind = kind; + this.pos = pos; + this.end = end; + this.flags = 0; + this.parent = undefined; + } ts.objectAllocator = { - getNodeConstructor: function (kind) { - function Node(pos, end) { - this.pos = pos; - this.end = end; - this.flags = 0; - this.parent = undefined; - } - Node.prototype = { kind: kind }; - return Node; - }, + getNodeConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } @@ -765,6 +797,12 @@ var ts; return copiedList; } ts.copyListRemovingItem = copyListRemovingItem; + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; })(ts || (ts = {})); var ts; (function (ts) { @@ -903,8 +941,7 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); - var _tty = require("tty"); - function createWatchedFileSet(interval, chunkSize) { + function createPollingWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } if (chunkSize === void 0) { chunkSize = 30; } var watchedFiles = []; @@ -918,13 +955,13 @@ var ts; if (!watchedFile) { return; } - _fs.stat(watchedFile.fileName, function (err, stats) { + _fs.stat(watchedFile.filePath, function (err, stats) { if (err) { - watchedFile.callback(watchedFile.fileName); + watchedFile.callback(watchedFile.filePath); } else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) { - watchedFile.mtime = getModifiedTime(watchedFile.fileName); - watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0); + watchedFile.mtime = getModifiedTime(watchedFile.filePath); + watchedFile.callback(watchedFile.filePath, watchedFile.mtime.getTime() === 0); } }); } @@ -947,11 +984,11 @@ var ts; nextFileToCheck = nextToCheck; }, interval); } - function addFile(fileName, callback) { + function addFile(filePath, callback) { var file = { - fileName: fileName, + filePath: filePath, callback: callback, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(filePath) }; watchedFiles.push(file); if (watchedFiles.length === 1) { @@ -970,6 +1007,73 @@ var ts; removeFile: removeFile }; } + function createWatchedFileSet() { + var dirWatchers = ts.createFileMap(); + var fileWatcherCallbacks = ts.createFileMap(); + return { addFile: addFile, removeFile: removeFile }; + function reduceDirWatcherRefCountForFile(filePath) { + var dirPath = ts.getDirectoryPath(filePath); + if (dirWatchers.contains(dirPath)) { + var watcher = dirWatchers.get(dirPath); + watcher.referenceCount -= 1; + if (watcher.referenceCount <= 0) { + watcher.close(); + dirWatchers.remove(dirPath); + } + } + } + function addDirWatcher(dirPath) { + if (dirWatchers.contains(dirPath)) { + var watcher_1 = dirWatchers.get(dirPath); + watcher_1.referenceCount += 1; + return; + } + var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher.referenceCount = 1; + dirWatchers.set(dirPath, watcher); + return; + } + function addFileWatcherCallback(filePath, callback) { + if (fileWatcherCallbacks.contains(filePath)) { + fileWatcherCallbacks.get(filePath).push(callback); + } + else { + fileWatcherCallbacks.set(filePath, [callback]); + } + } + function addFile(filePath, callback) { + addFileWatcherCallback(filePath, callback); + addDirWatcher(ts.getDirectoryPath(filePath)); + return { filePath: filePath, callback: callback }; + } + function removeFile(watchedFile) { + removeFileWatcherCallback(watchedFile.filePath, watchedFile.callback); + reduceDirWatcherRefCountForFile(watchedFile.filePath); + } + function removeFileWatcherCallback(filePath, callback) { + if (fileWatcherCallbacks.contains(filePath)) { + var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks.get(filePath)); + if (newCallbacks.length === 0) { + fileWatcherCallbacks.remove(filePath); + } + else { + fileWatcherCallbacks.set(filePath, newCallbacks); + } + } + } + function fileEventHandler(eventName, relativeFileName, baseDirPath) { + var filePath = typeof relativeFileName !== "string" + ? undefined + : ts.toPath(relativeFileName, baseDirPath, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)); + if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks.contains(filePath)) { + for (var _i = 0, _a = fileWatcherCallbacks.get(filePath); _i < _a.length; _i++) { + var fileCallback = _a[_i]; + fileCallback(filePath); + } + } + } + } + var pollingWatchedFileSet = createPollingWatchedFileSet(); var watchedFileSet = createWatchedFileSet(); function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; @@ -977,7 +1081,7 @@ var ts; var platform = _os.platform(); var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; function readFile(fileName, encoding) { - if (!_fs.existsSync(fileName)) { + if (!fileExists(fileName)) { return undefined; } var buffer = _fs.readFileSync(fileName); @@ -1003,10 +1107,37 @@ var ts; if (writeByteOrderMark) { data = "\uFEFF" + data; } - _fs.writeFileSync(fileName, data, "utf8"); + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } } function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path.toLowerCase() : path; + return useCaseSensitiveFileNames ? path : path.toLowerCase(); + } + function fileSystemEntryExists(path, entryKind) { + try { + var stat = _fs.statSync(path); + switch (entryKind) { + case 0: return stat.isFile(); + case 1: return stat.isDirectory(); + } + } + catch (e) { + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1); } function readDirectory(path, extension, exclude) { var result = []; @@ -1046,17 +1177,22 @@ var ts; }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { - if (isNode4OrLater()) { - return _fs.watch(fileName, function (eventName, relativeFileName) { return callback(fileName); }); - } - var watchedFile = watchedFileSet.addFile(fileName, callback); + watchFile: function (filePath, callback) { + var watchSet = isNode4OrLater() ? watchedFileSet : pollingWatchedFileSet; + var watchedFile = watchSet.addFile(filePath, callback); return { - close: function () { return watchedFileSet.removeFile(watchedFile); } + close: function () { return watchSet.removeFile(watchedFile); } }; }, watchDirectory: function (path, callback, recursive) { - return _fs.watch(path, { persistent: true, recursive: !!recursive }, function (eventName, relativeFileName) { + var options; + if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + return _fs.watch(path, options, function (eventName, relativeFileName) { if (eventName === "rename") { callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(path, relativeFileName))); } @@ -1066,12 +1202,8 @@ var ts; resolvePath: function (path) { return _path.resolve(path); }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); - }, + fileExists: fileExists, + directoryExists: directoryExists, createDirectory: function (directoryName) { if (!this.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); @@ -1095,12 +1227,40 @@ var ts; } }; } + function getChakraSystem() { + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, encoding) { + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + if (writeByteOrderMark) { + data = "\uFEFF" + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + readDirectory: ChakraHost.readDirectory, + exit: ChakraHost.quit + }; + } if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { return getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { return getNodeSystem(); } + else if (typeof ChakraHost !== "undefined") { + return getChakraSystem(); + } else { return undefined; } @@ -1126,6 +1286,7 @@ var ts; An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_a_type_annotation_1021", message: "An index signature must have a type annotation." }, An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_must_have_a_type_annotation_1022", message: "An index signature parameter must have a type annotation." }, An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_type_must_be_string_or_number_1023", message: "An index signature parameter type must be 'string' or 'number'." }, + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: { code: 1024, category: ts.DiagnosticCategory.Error, key: "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", message: "'readonly' modifier can only appear on a property declaration or index signature." }, Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility_modifier_already_seen_1028", message: "Accessibility modifier already seen." }, _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{0}' modifier already seen." }, @@ -1139,7 +1300,7 @@ var ts; _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_a_class_declaration_1041", message: "'{0}' modifier cannot be used with a class declaration." }, _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_here_1042", message: "'{0}' modifier cannot be used here." }, _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_data_property_1043", message: "'{0}' modifier cannot appear on a data property." }, - _0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_element_1044", message: "'{0}' modifier cannot appear on a module element." }, + _0_modifier_cannot_appear_on_a_module_or_namespace_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", message: "'{0}' modifier cannot appear on a module or namespace element." }, A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", message: "A '{0}' modifier cannot be used with an interface declaration." }, A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", message: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_be_optional_1047", message: "A rest parameter cannot be optional." }, @@ -1158,8 +1319,11 @@ var ts; Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." }, _0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "{0} is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." }, + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." }, Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", message: "Unexpected token. A constructor, method, accessor, or property was expected." }, + _0_modifier_cannot_appear_on_a_type_member: { code: 1070, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_type_member_1070", message: "'{0}' modifier cannot appear on a type member." }, + _0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." }, A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." }, Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." }, Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher." }, @@ -1215,10 +1379,9 @@ var ts; String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, - Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: ts.DiagnosticCategory.Error, key: "Modifiers_not_permitted_on_index_signature_members_1145", message: "Modifiers not permitted on index signature members." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_1148", message: "Cannot compile modules unless the '--module' flag is provided." }, + Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting__1148", message: "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -1278,7 +1441,7 @@ var ts; Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_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_Speci_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning." }, + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_6_or_higher_1220", message: "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_1221", message: "Generators are not allowed in an ambient context." }, An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An_overload_signature_cannot_be_declared_as_a_generator_1222", message: "An overload signature cannot be declared as a generator." }, @@ -1301,10 +1464,14 @@ var ts; Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", message: "Unable to resolve signature of parameter decorator when called as an expression." }, Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", message: "Unable to resolve signature of property decorator when called as an expression." }, Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", message: "Unable to resolve signature of method decorator when called as an expression." }, - abstract_modifier_can_only_appear_on_a_class_or_method_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_or_method_declaration_1242", message: "'abstract' modifier can only appear on a class or method declaration." }, + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", message: "'abstract' modifier can only appear on a class, method, or property declaration." }, _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, + An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, + A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, + A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, @@ -1318,11 +1485,12 @@ var ts; Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list_2313", message: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." }, + Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, @@ -1332,6 +1500,7 @@ var ts; Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, + Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, @@ -1388,7 +1557,7 @@ var ts; get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", message: "Specialized overload signature is not assignable to any non-specialized signature." }, - Overload_signatures_must_all_be_exported_or_not_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_not_exported_2383", message: "Overload signatures must all be exported or not exported." }, + Overload_signatures_must_all_be_exported_or_non_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_non_exported_2383", message: "Overload signatures must all be exported or non-exported." }, Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", message: "Overload signatures must all be ambient or non-ambient." }, Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_public_private_or_protected_2385", message: "Overload signatures must all be public, private or protected." }, Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_optional_or_required_2386", message: "Overload signatures must all be optional or required." }, @@ -1402,6 +1571,7 @@ var ts; Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, @@ -1420,7 +1590,6 @@ var ts; Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'" }, Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." }, Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0: { code: 2419, category: ts.DiagnosticCategory.Error, key: "Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0_2419", message: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." }, Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." }, A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_implement_another_class_or_interface_2422", message: "A class may only implement another class or interface." }, Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, @@ -1428,7 +1597,7 @@ var ts; Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'" }, - All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_interface_must_have_identical_type_parameters_2428", message: "All declarations of an interface must have identical type parameters." }, + All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." }, Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'" }, In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, @@ -1448,8 +1617,8 @@ var ts; Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_2449", message: "The operand of an increment or decrement operator cannot be a constant." }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_2450", message: "Left-hand side of assignment expression cannot be a constant." }, + The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property_2449", message: "The operand of an increment or decrement operator cannot be a constant or a read-only property." }, + Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property_2450", message: "Left-hand side of assignment expression cannot be a constant or a read-only property." }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, @@ -1482,8 +1651,8 @@ var ts; Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" }, - The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant_2485", message: "The left-hand side of a 'for...of' statement cannot be a previously defined constant." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant_2486", message: "The left-hand side of a 'for...in' statement cannot be a previously defined constant." }, + The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property_2485", message: "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property." }, + The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property_2486", message: "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property." }, Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_of_statement_2487", message: "Invalid left-hand side in 'for...of' statement." }, Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, @@ -1509,12 +1678,13 @@ var ts; Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", message: "Base constructor return type '{0}' is not a class or interface type." }, Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base_constructors_must_all_have_the_same_return_type_2510", message: "Base constructors must all have the same return type." }, Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot_create_an_instance_of_the_abstract_class_0_2511", message: "Cannot create an instance of the abstract class '{0}'." }, - Overload_signatures_must_all_be_abstract_or_not_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_not_abstract_2512", message: "Overload signatures must all be abstract or not abstract." }, + Overload_signatures_must_all_be_abstract_or_non_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", message: "Overload signatures must all be abstract or non-abstract." }, Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", message: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes_containing_abstract_methods_must_be_marked_abstract_2514", message: "Classes containing abstract methods must be marked abstract." }, Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, @@ -1524,7 +1694,9 @@ var ts; A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_must_be_an_object_type_2600", message: "JSX element attributes type '{0}' must be an object type." }, + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, + Property_0_is_incompatible_with_index_signature: { code: 2530, category: ts.DiagnosticCategory.Error, key: "Property_0_is_incompatible_with_index_signature_2530", message: "Property '{0}' is incompatible with index signature." }, + JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'" }, @@ -1540,6 +1712,25 @@ var ts; Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element" }, + Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'" }, + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, + Cannot_re_export_name_that_is_not_defined_in_the_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_name_that_is_not_defined_in_the_module_2661", message: "Cannot re-export name that is not defined in the module." }, + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, + Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope_2665", message: "Module augmentation cannot introduce new names in the top level scope." }, + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: { code: 2672, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", message: "Cannot assign a '{0}' constructor type to a '{1}' constructor type." }, + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: { code: 2673, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", message: "Constructor of class '{0}' is private and only accessible within the class declaration." }, + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: { code: 2674, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", message: "Constructor of class '{0}' is protected and only accessible within the class declaration." }, + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: { code: 2675, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", message: "Cannot extend a class '{0}'. Class constructor is marked as private." }, + Accessors_must_both_be_abstract_or_non_abstract: { code: 2676, category: ts.DiagnosticCategory.Error, key: "Accessors_must_both_be_abstract_or_non_abstract_2676", message: "Accessors must both be abstract or non-abstract." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1624,6 +1815,14 @@ var ts; Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, + Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'" }, + The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'" }, + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." }, + Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, + Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character" }, + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character" }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -1634,6 +1833,7 @@ var ts; Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -1656,7 +1856,7 @@ var ts; Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." }, - Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015_6046", message: "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', or 'es2015'." }, + Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none_6046", message: "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'none'." }, Argument_for_target_option_must_be_ES3_ES5_or_ES2015: { code: 6047, category: ts.DiagnosticCategory.Error, key: "Argument_for_target_option_must_be_ES3_ES5_or_ES2015_6047", message: "Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'." }, Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form or -. For example '{0}' or '{1}'." }, Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." }, @@ -1673,6 +1873,7 @@ var ts; NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "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_6062", message: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Argument_for_moduleResolution_option_must_be_node_or_classic: { code: 6063, category: ts.DiagnosticCategory.Error, key: "Argument_for_moduleResolution_option_must_be_node_or_classic_6063", message: "Argument for '--moduleResolution' option must be 'node' or 'classic'." }, + Option_0_can_only_be_specified_in_tsconfig_json_file: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", message: "Option '{0}' can only be specified in 'tsconfig.json' file." }, Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, @@ -1688,6 +1889,37 @@ var ts; Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, + Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, + Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." }, + Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit_6084", message: "Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit" }, + Enable_tracing_of_the_module_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_module_resolution_process_6085", message: "Enable tracing of the module resolution process." }, + Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" }, + Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." }, + Module_resolution_kind_is_not_specified_using_0: { code: 6088, category: ts.DiagnosticCategory.Message, key: "Module_resolution_kind_is_not_specified_using_0_6088", message: "Module resolution kind is not specified, using '{0}'." }, + Module_name_0_was_successfully_resolved_to_1: { code: 6089, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_successfully_resolved_to_1_6089", message: "======== Module name '{0}' was successfully resolved to '{1}'. ========" }, + Module_name_0_was_not_resolved: { code: 6090, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_not_resolved_6090", message: "======== Module name '{0}' was not resolved. ========" }, + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: { code: 6091, category: ts.DiagnosticCategory.Message, key: "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", message: "'paths' option is specified, looking for a pattern to match module name '{0}'." }, + Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." }, + Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." }, + Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." }, + Loading_module_as_file_Slash_folder_candidate_module_location_0: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_6095", message: "Loading module as file / folder, candidate module location '{0}'." }, + File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." }, + File_0_exist_use_it_as_a_module_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_module_resolution_result_6097", message: "File '{0}' exist - use it as a module resolution result." }, + Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." }, + Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, + package_json_does_not_have_typings_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_typings_field_6100", message: "'package.json' does not have 'typings' field." }, + package_json_has_typings_field_0_that_references_1: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_typings_field_0_that_references_1_6101", message: "'package.json' has 'typings' field '{0}' that references '{1}'." }, + Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, + Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, + Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." }, + Expected_type_of_typings_field_in_package_json_to_be_string_got_0: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_typings_field_in_package_json_to_be_string_got_0_6105", message: "Expected type of 'typings' field in 'package.json' to be 'string', got '{0}'." }, + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'" }, + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'" }, + Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'" }, + Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'" }, + Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'" }, + Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed" }, + Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -1695,6 +1927,7 @@ var ts; _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", message: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, @@ -1725,7 +1958,6 @@ var ts; 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_8014", message: "'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_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, - 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_8017", message: "'decorators' can only be used in a .ts file." }, 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_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, @@ -1735,7 +1967,9 @@ var ts; Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'" }, An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." } + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, + JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." } }; })(ts || (ts = {})); var ts; @@ -1768,7 +2002,7 @@ var ts; "false": 84, "finally": 85, "for": 86, - "from": 133, + "from": 134, "function": 87, "get": 123, "if": 88, @@ -1783,24 +2017,26 @@ var ts; "namespace": 126, "new": 92, "null": 93, - "number": 128, + "number": 129, "package": 109, "private": 110, "protected": 111, "public": 112, - "require": 127, + "readonly": 127, + "require": 128, + "global": 135, "return": 94, - "set": 129, + "set": 130, "static": 113, - "string": 130, + "string": 131, "super": 95, "switch": 96, - "symbol": 131, + "symbol": 132, "this": 97, "throw": 98, "true": 99, "try": 100, - "type": 132, + "type": 133, "typeof": 101, "var": 102, "void": 103, @@ -1809,7 +2045,7 @@ var ts; "yield": 114, "async": 118, "await": 119, - "of": 134, + "of": 136, "{": 15, "}": 16, "(": 17, @@ -1925,7 +2161,8 @@ var ts; var pos = 0; var lineStart = 0; while (pos < text.length) { - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 13: if (text.charCodeAt(pos) === 10) { @@ -2028,6 +2265,9 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; function skipTrivia(text, pos, stopAfterLineBreak) { + if (!(pos >= 0)) { + return pos; + } while (true) { var ch = text.charCodeAt(pos); switch (ch) { @@ -2148,7 +2388,7 @@ var ts; function getCommentRanges(text, pos, trailing) { var result; var collecting = trailing || pos === 0; - while (true) { + while (pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13: @@ -2217,6 +2457,7 @@ var ts; } return result; } + return result; } function getLeadingCommentRanges(text, pos) { return getCommentRanges(text, pos, false); @@ -2244,6 +2485,18 @@ var ts; ch > 127 && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; + function isIdentifier(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1, n = name.length; i < n; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifier = isIdentifier; function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0; } var pos; @@ -2274,6 +2527,7 @@ var ts; scanJsxIdentifier: scanJsxIdentifier, reScanJsxToken: reScanJsxToken, scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, scan: scan, setText: setText, setScriptTarget: setScriptTarget, @@ -2281,7 +2535,8 @@ var ts; setOnError: setOnError, setTextPos: setTextPos, tryScan: tryScan, - lookAhead: lookAhead + lookAhead: lookAhead, + scanRange: scanRange }; function error(message, length) { if (onError) { @@ -2312,7 +2567,7 @@ var ts; error(ts.Diagnostics.Digit_expected); } } - return +(text.substring(start, end)); + return "" + +(text.substring(start, end)); } function scanOctalDigits() { var start = pos; @@ -2353,7 +2608,8 @@ var ts; return value; } function scanString() { - var quote = text.charCodeAt(pos++); + var quote = text.charCodeAt(pos); + pos++; var result = ""; var start = pos; while (true) { @@ -2440,7 +2696,8 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); return ""; } - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 48: return "\0"; @@ -2649,7 +2906,8 @@ var ts; } return pos += 2, token = 31; } - return pos++, token = 49; + pos++; + return token = 49; case 34: case 39: tokenValue = scanString(); @@ -2660,7 +2918,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 62; } - return pos++, token = 40; + pos++; + return token = 40; case 38: if (text.charCodeAt(pos + 1) === 38) { return pos += 2, token = 51; @@ -2668,11 +2927,14 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 66; } - return pos++, token = 46; + pos++; + return token = 46; case 40: - return pos++, token = 17; + pos++; + return token = 17; case 41: - return pos++, token = 18; + pos++; + return token = 18; case 42: if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 59; @@ -2683,7 +2945,8 @@ var ts; } return pos += 2, token = 38; } - return pos++, token = 37; + pos++; + return token = 37; case 43: if (text.charCodeAt(pos + 1) === 43) { return pos += 2, token = 41; @@ -2691,9 +2954,11 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 57; } - return pos++, token = 35; + pos++; + return token = 35; case 44: - return pos++, token = 24; + pos++; + return token = 24; case 45: if (text.charCodeAt(pos + 1) === 45) { return pos += 2, token = 42; @@ -2701,16 +2966,18 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 58; } - return pos++, token = 36; + pos++; + return token = 36; case 46: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = "" + scanNumber(); + tokenValue = scanNumber(); return token = 8; } if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { return pos += 3, token = 22; } - return pos++, token = 21; + pos++; + return token = 21; case 47: if (text.charCodeAt(pos + 1) === 47) { pos += 2; @@ -2756,7 +3023,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 61; } - return pos++, token = 39; + pos++; + return token = 39; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; @@ -2801,12 +3069,14 @@ var ts; case 55: case 56: case 57: - tokenValue = "" + scanNumber(); + tokenValue = scanNumber(); return token = 8; case 58: - return pos++, token = 54; + pos++; + return token = 54; case 59: - return pos++, token = 23; + pos++; + return token = 23; case 60: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2831,7 +3101,8 @@ var ts; text.charCodeAt(pos + 2) !== 42) { return pos += 2, token = 26; } - return pos++, token = 25; + pos++; + return token = 25; case 61: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2851,7 +3122,8 @@ var ts; if (text.charCodeAt(pos + 1) === 62) { return pos += 2, token = 34; } - return pos++, token = 56; + pos++; + return token = 56; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2862,20 +3134,26 @@ var ts; return token = 7; } } - return pos++, token = 27; + pos++; + return token = 27; case 63: - return pos++, token = 53; + pos++; + return token = 53; case 91: - return pos++, token = 19; + pos++; + return token = 19; case 93: - return pos++, token = 20; + pos++; + return token = 20; case 94: if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 68; } - return pos++, token = 48; + pos++; + return token = 48; case 123: - return pos++, token = 15; + pos++; + return token = 15; case 124: if (text.charCodeAt(pos + 1) === 124) { return pos += 2, token = 52; @@ -2883,13 +3161,17 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 67; } - return pos++, token = 47; + pos++; + return token = 47; case 125: - return pos++, token = 16; + pos++; + return token = 16; case 126: - return pos++, token = 50; + pos++; + return token = 50; case 64: - return pos++, token = 55; + pos++; + return token = 55; case 92: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -2898,7 +3180,8 @@ var ts; return token = getIdentifierToken(); } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0; + pos++; + return token = 0; default: if (isIdentifierStart(ch, languageVersion)) { pos++; @@ -2920,7 +3203,8 @@ var ts; continue; } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0; + pos++; + return token = 0; } } } @@ -2936,10 +3220,12 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 64; } - return pos++, token = 44; + pos++; + return token = 44; } if (text.charCodeAt(pos) === 61) { - return pos++, token = 29; + pos++; + return token = 29; } } return token; @@ -3022,7 +3308,7 @@ var ts; break; } } - return token = 236; + return token = 240; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { @@ -3040,6 +3326,54 @@ var ts; } return token; } + function scanJSDocToken() { + if (pos >= end) { + return token = 1; + } + startPos = pos; + var ch = text.charCodeAt(pos); + while (pos < end) { + ch = text.charCodeAt(pos); + if (isWhiteSpace(ch)) { + pos++; + } + else { + break; + } + } + tokenPos = pos; + switch (ch) { + case 64: + return pos += 1, token = 55; + case 10: + case 13: + return pos += 1, token = 4; + case 42: + return pos += 1, token = 37; + case 123: + return pos += 1, token = 15; + case 125: + return pos += 1, token = 16; + case 91: + return pos += 1, token = 19; + case 93: + return pos += 1, token = 20; + case 61: + return pos += 1, token = 56; + case 44: + return pos += 1, token = 24; + } + if (isIdentifierStart(ch, 2)) { + pos++; + while (isIdentifierPart(text.charCodeAt(pos), 2) && pos < end) { + pos++; + } + return token = 69; + } + else { + return pos += 1, token = 0; + } + } function speculationHelper(callback, isLookahead) { var savePos = pos; var saveStartPos = startPos; @@ -3058,6 +3392,29 @@ var ts; } return result; } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var savePrecedingLineBreak = precedingLineBreak; + var saveTokenValue = tokenValue; + var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + var saveTokenIsUnterminated = tokenIsUnterminated; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + precedingLineBreak = savePrecedingLineBreak; + tokenValue = saveTokenValue; + hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; + tokenIsUnterminated = saveTokenIsUnterminated; + return result; + } function lookAhead(callback) { return speculationHelper(callback, true); } @@ -3093,1034 +3450,6 @@ var ts; ts.createScanner = createScanner; })(ts || (ts = {})); var ts; -(function (ts) { - ts.bindTime = 0; - function or(state1, state2) { - return (state1 | state2) & 2 - ? 2 - : (state1 & state2) & 8 - ? 8 - : 4; - } - function getModuleInstanceState(node) { - if (node.kind === 215 || node.kind === 216) { - return 0; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2; - } - else if ((node.kind === 222 || node.kind === 221) && !(node.flags & 2)) { - return 0; - } - else if (node.kind === 219) { - var state = 0; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0: - return false; - case 2: - state = 2; - return false; - case 1: - state = 1; - return true; - } - }); - return state; - } - else if (node.kind === 218) { - return getModuleInstanceState(node.body); - } - else { - return 1; - } - } - ts.getModuleInstanceState = getModuleInstanceState; - var binder = createBinder(); - function bindSourceFile(file, options) { - var start = new Date().getTime(); - binder(file, options); - ts.bindTime += new Date().getTime() - start; - } - ts.bindSourceFile = bindSourceFile; - function createBinder() { - var file; - var options; - var parent; - var container; - var blockScopeContainer; - var lastContainer; - var seenThisKeyword; - var hasExplicitReturn; - var currentReachabilityState; - var labelStack; - var labelIndexMap; - var implicitLabels; - var inStrictMode; - var symbolCount = 0; - var Symbol; - var classifiableNames; - function bindSourceFile(f, opts) { - file = f; - options = opts; - inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; - Symbol = ts.objectAllocator.getSymbolConstructor(); - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - hasExplicitReturn = false; - labelStack = undefined; - labelIndexMap = undefined; - implicitLabels = undefined; - } - return bindSourceFile; - function createSymbol(flags, name) { - symbolCount++; - return new Symbol(flags, name); - } - function addDeclarationToSymbol(symbol, node, symbolFlags) { - symbol.flags |= symbolFlags; - node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = []; - } - symbol.declarations.push(node); - if (symbolFlags & 1952 && !symbol.exports) { - symbol.exports = {}; - } - if (symbolFlags & 6240 && !symbol.members) { - symbol.members = {}; - } - if (symbolFlags & 107455 && !symbol.valueDeclaration) { - symbol.valueDeclaration = node; - } - } - function getDeclarationName(node) { - if (node.name) { - if (node.kind === 218 && node.name.kind === 9) { - return "\"" + node.name.text + "\""; - } - if (node.name.kind === 136) { - var nameExpression = node.name.expression; - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); - } - return node.name.text; - } - switch (node.kind) { - case 144: - return "__constructor"; - case 152: - case 147: - return "__call"; - case 153: - case 148: - return "__new"; - case 149: - return "__index"; - case 228: - return "__export"; - case 227: - return node.isExportEquals ? "export=" : "default"; - case 213: - case 214: - return node.flags & 512 ? "default" : undefined; - } - } - function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); - } - function declareSymbol(symbolTable, parent, node, includes, excludes) { - ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 512; - var name = isDefaultExport && parent ? "default" : getDeclarationName(node); - var symbol; - if (name !== undefined) { - 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; - } - var message = symbol.flags & 2 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512) { - message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - }); - ts.forEach(symbol.declarations, function (declaration) { - 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); - } - } - else { - symbol = createSymbol(0, "__missing"); - } - addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; - return symbol; - } - function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 2; - if (symbolFlags & 8388608) { - if (node.kind === 230 || (node.kind === 221 && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - else { - if (hasExportModifier || container.flags & 131072) { - 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, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - } - function bindChildren(node) { - var saveParent = parent; - var saveContainer = container; - var savedBlockScopeContainer = blockScopeContainer; - parent = node; - var containerFlags = getContainerFlags(node); - if (containerFlags & 1) { - container = blockScopeContainer = node; - if (containerFlags & 4) { - container.locals = {}; - } - addToContainerChain(container); - } - else if (containerFlags & 2) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - var savedReachabilityState; - var savedLabelStack; - var savedLabels; - var savedImplicitLabels; - var savedHasExplicitReturn; - var kind = node.kind; - var flags = node.flags; - flags &= ~1572864; - if (kind === 215) { - seenThisKeyword = false; - } - var saveState = kind === 248 || kind === 219 || ts.isFunctionLikeKind(kind); - if (saveState) { - savedReachabilityState = currentReachabilityState; - savedLabelStack = labelStack; - savedLabels = labelIndexMap; - savedImplicitLabels = implicitLabels; - savedHasExplicitReturn = hasExplicitReturn; - currentReachabilityState = 2; - hasExplicitReturn = false; - labelStack = labelIndexMap = implicitLabels = undefined; - } - bindReachableStatement(node); - if (currentReachabilityState === 2 && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { - flags |= 524288; - if (hasExplicitReturn) { - flags |= 1048576; - } - } - if (kind === 215) { - flags = seenThisKeyword ? flags | 262144 : flags & ~262144; - } - node.flags = flags; - if (saveState) { - hasExplicitReturn = savedHasExplicitReturn; - currentReachabilityState = savedReachabilityState; - labelStack = savedLabelStack; - labelIndexMap = savedLabels; - implicitLabels = savedImplicitLabels; - } - container = saveContainer; - parent = saveParent; - blockScopeContainer = savedBlockScopeContainer; - } - function bindReachableStatement(node) { - if (checkUnreachable(node)) { - ts.forEachChild(node, bind); - return; - } - switch (node.kind) { - case 198: - bindWhileStatement(node); - break; - case 197: - bindDoStatement(node); - break; - case 199: - bindForStatement(node); - break; - case 200: - case 201: - bindForInOrForOfStatement(node); - break; - case 196: - bindIfStatement(node); - break; - case 204: - case 208: - bindReturnOrThrow(node); - break; - case 203: - case 202: - bindBreakOrContinueStatement(node); - break; - case 209: - bindTryStatement(node); - break; - case 206: - bindSwitchStatement(node); - break; - case 220: - bindCaseBlock(node); - break; - case 207: - bindLabeledStatement(node); - break; - default: - ts.forEachChild(node, bind); - break; - } - } - function bindWhileStatement(n) { - var preWhileState = n.expression.kind === 84 ? 4 : currentReachabilityState; - var postWhileState = n.expression.kind === 99 ? 4 : currentReachabilityState; - bind(n.expression); - currentReachabilityState = preWhileState; - var postWhileLabel = pushImplicitLabel(); - bind(n.statement); - popImplicitLabel(postWhileLabel, postWhileState); - } - function bindDoStatement(n) { - var preDoState = currentReachabilityState; - var postDoLabel = pushImplicitLabel(); - bind(n.statement); - var postDoState = n.expression.kind === 99 ? 4 : preDoState; - popImplicitLabel(postDoLabel, postDoState); - bind(n.expression); - } - function bindForStatement(n) { - var preForState = currentReachabilityState; - var postForLabel = pushImplicitLabel(); - bind(n.initializer); - bind(n.condition); - bind(n.incrementor); - bind(n.statement); - var isInfiniteLoop = (!n.condition || n.condition.kind === 99); - var postForState = isInfiniteLoop ? 4 : preForState; - popImplicitLabel(postForLabel, postForState); - } - function bindForInOrForOfStatement(n) { - var preStatementState = currentReachabilityState; - var postStatementLabel = pushImplicitLabel(); - bind(n.initializer); - bind(n.expression); - bind(n.statement); - popImplicitLabel(postStatementLabel, preStatementState); - } - function bindIfStatement(n) { - var ifTrueState = n.expression.kind === 84 ? 4 : currentReachabilityState; - var ifFalseState = n.expression.kind === 99 ? 4 : currentReachabilityState; - currentReachabilityState = ifTrueState; - bind(n.expression); - bind(n.thenStatement); - if (n.elseStatement) { - var preElseState = currentReachabilityState; - currentReachabilityState = ifFalseState; - bind(n.elseStatement); - currentReachabilityState = or(currentReachabilityState, preElseState); - } - else { - currentReachabilityState = or(currentReachabilityState, ifFalseState); - } - } - function bindReturnOrThrow(n) { - bind(n.expression); - if (n.kind === 204) { - hasExplicitReturn = true; - } - currentReachabilityState = 4; - } - function bindBreakOrContinueStatement(n) { - bind(n.label); - var isValidJump = jumpToLabel(n.label, n.kind === 203 ? currentReachabilityState : 4); - if (isValidJump) { - currentReachabilityState = 4; - } - } - function bindTryStatement(n) { - var preTryState = currentReachabilityState; - bind(n.tryBlock); - var postTryState = currentReachabilityState; - currentReachabilityState = preTryState; - bind(n.catchClause); - var postCatchState = currentReachabilityState; - currentReachabilityState = preTryState; - bind(n.finallyBlock); - currentReachabilityState = or(postTryState, postCatchState); - } - function bindSwitchStatement(n) { - var preSwitchState = currentReachabilityState; - var postSwitchLabel = pushImplicitLabel(); - bind(n.expression); - bind(n.caseBlock); - var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242; }); - var postSwitchState = hasDefault && currentReachabilityState !== 2 ? 4 : preSwitchState; - popImplicitLabel(postSwitchLabel, postSwitchState); - } - function bindCaseBlock(n) { - var startState = currentReachabilityState; - for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { - var clause = _a[_i]; - currentReachabilityState = startState; - bind(clause); - if (clause.statements.length && currentReachabilityState === 2 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } - } - } - function bindLabeledStatement(n) { - bind(n.label); - var ok = pushNamedLabel(n.label); - bind(n.statement); - if (ok) { - popNamedLabel(n.label, currentReachabilityState); - } - } - function getContainerFlags(node) { - switch (node.kind) { - case 186: - case 214: - case 215: - case 217: - case 155: - case 165: - return 1; - case 147: - case 148: - case 149: - case 143: - case 142: - case 213: - case 144: - case 145: - case 146: - case 152: - case 153: - case 173: - case 174: - case 218: - case 248: - case 216: - return 5; - case 244: - case 199: - case 200: - case 201: - case 220: - return 2; - case 192: - return ts.isFunctionLike(node.parent) ? 0 : 2; - } - 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 218: - return declareModuleMember(node, symbolFlags, symbolExcludes); - case 248: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 186: - case 214: - return declareClassMember(node, symbolFlags, symbolExcludes); - case 217: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 155: - case 165: - case 215: - return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 152: - case 153: - case 147: - case 148: - case 149: - case 143: - case 142: - case 144: - case 145: - case 146: - case 213: - case 173: - case 174: - case 216: - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 64 - ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) - : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - } - function declareSourceFileMember(node, symbolFlags, symbolExcludes) { - return ts.isExternalModule(file) - ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); - } - function hasExportDeclarations(node) { - var body = node.kind === 248 ? node : node.body; - if (body.kind === 248 || body.kind === 219) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var stat = _a[_i]; - if (stat.kind === 228 || stat.kind === 227) { - return true; - } - } - } - return false; - } - function setExportContextFlag(node) { - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 131072; - } - else { - node.flags &= ~131072; - } - } - function bindModuleDeclaration(node) { - setExportContextFlag(node); - if (node.name.kind === 9) { - declareSymbolAndAddToSymbolTable(node, 512, 106639); - } - else { - var state = getModuleInstanceState(node); - if (state === 0) { - declareSymbolAndAddToSymbolTable(node, 1024, 0); - } - else { - declareSymbolAndAddToSymbolTable(node, 512, 106639); - if (node.symbol.flags & (16 | 32 | 256)) { - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2; - if (node.symbol.constEnumOnlyModule === undefined) { - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } - } - } - } - function bindFunctionOrConstructorType(node) { - var symbol = createSymbol(131072, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072); - var typeLiteralSymbol = createSymbol(2048, "__type"); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); - var _a; - } - 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 !== 69) { - continue; - } - var identifier = prop.name; - var currentKind = prop.kind === 245 || prop.kind === 246 || prop.kind === 143 - ? 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 bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - addDeclarationToSymbol(symbol, node, symbolFlags); - } - function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { - switch (blockScopeContainer.kind) { - case 218: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case 248: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 107455); - } - function checkStrictModeIdentifier(node) { - if (inStrictMode && - node.originalKeywordKind >= 106 && - node.originalKeywordKind <= 114 && - !ts.isIdentifierName(node)) { - if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); - } - } - } - function getStrictModeIdentifierMessage(node) { - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - function checkStrictModeBinaryExpression(node) { - if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - checkStrictModeEvalOrArguments(node, node.left); - } - } - function checkStrictModeCatchClause(node) { - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - function checkStrictModeDeleteExpression(node) { - if (inStrictMode && node.expression.kind === 69) { - 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 === 69 && - (node.text === "eval" || node.text === "arguments"); - } - function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 69) { - 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.getContainingClass(node)) { - return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; - } - function checkStrictModeFunctionName(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - } - function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.flags & 32768) { - 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 === 41 || node.operator === 42) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - function checkStrictModeWithStatement(node) { - if (inStrictMode) { - errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - function getDestructuringParameterName(node) { - return "__" + ts.indexOf(node.parent.parameters, node); - } - function bind(node) { - if (!node) { - return; - } - node.parent = parent; - var savedInStrictMode = inStrictMode; - if (!savedInStrictMode) { - updateStrictMode(node); - } - bindWorker(node); - bindChildren(node); - inStrictMode = savedInStrictMode; - } - function updateStrictMode(node) { - switch (node.kind) { - case 248: - case 219: - updateStrictModeStatementList(node.statements); - return; - case 192: - if (ts.isFunctionLike(node.parent)) { - updateStrictModeStatementList(node.statements); - } - return; - case 214: - case 186: - inStrictMode = true; - return; - } - } - function updateStrictModeStatementList(statements) { - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; - if (!ts.isPrologueDirective(statement)) { - return; - } - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - function isUseStrictPrologueDirective(node) { - var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); - return nodeText === "\"use strict\"" || nodeText === "'use strict'"; - } - function bindWorker(node) { - switch (node.kind) { - case 69: - return checkStrictModeIdentifier(node); - case 181: - return checkStrictModeBinaryExpression(node); - case 244: - return checkStrictModeCatchClause(node); - case 175: - return checkStrictModeDeleteExpression(node); - case 8: - return checkStrictModeNumericLiteral(node); - case 180: - return checkStrictModePostfixUnaryExpression(node); - case 179: - return checkStrictModePrefixUnaryExpression(node); - case 205: - return checkStrictModeWithStatement(node); - case 97: - seenThisKeyword = true; - return; - case 137: - return declareSymbolAndAddToSymbolTable(node, 262144, 530912); - case 138: - return bindParameter(node); - case 211: - case 163: - return bindVariableDeclarationOrBindingElement(node); - case 141: - case 140: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); - case 245: - case 246: - return bindPropertyOrMethodOrAccessor(node, 4, 107455); - case 247: - return bindPropertyOrMethodOrAccessor(node, 8, 107455); - case 147: - case 148: - case 149: - return declareSymbolAndAddToSymbolTable(node, 131072, 0); - case 143: - case 142: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); - case 213: - checkStrictModeFunctionName(node); - return declareSymbolAndAddToSymbolTable(node, 16, 106927); - case 144: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); - case 145: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); - case 146: - return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 152: - case 153: - return bindFunctionOrConstructorType(node); - case 155: - return bindAnonymousDeclaration(node, 2048, "__type"); - case 165: - return bindObjectLiteralExpression(node); - case 173: - case 174: - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.text : "__function"; - return bindAnonymousDeclaration(node, 16, bindingName); - case 186: - case 214: - return bindClassLikeDeclaration(node); - case 215: - return bindBlockScopedDeclaration(node, 64, 792960); - case 216: - return bindBlockScopedDeclaration(node, 524288, 793056); - case 217: - return bindEnumDeclaration(node); - case 218: - return bindModuleDeclaration(node); - case 221: - case 224: - case 226: - case 230: - return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); - case 223: - return bindImportClause(node); - case 228: - return bindExportDeclaration(node); - case 227: - return bindExportAssignment(node); - case 248: - 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 === 69) { - 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 === 214) { - bindBlockScopedDeclaration(node, 32, 899519); - } - else { - var bindingName = node.name ? node.name.text : "__class"; - bindAnonymousDeclaration(node, 32, bindingName); - if (node.name) { - classifiableNames[node.name.text] = node.name.text; - } - } - 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)); - } - else { - declareSymbolAndAddToSymbolTable(node, 1, 107455); - } - if (node.flags & 56 && - node.parent.kind === 144 && - ts.isClassLike(node.parent.parent)) { - var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); - } - } - function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed") - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function pushNamedLabel(name) { - initializeReachabilityStateIfNecessary(); - if (ts.hasProperty(labelIndexMap, name.text)) { - return false; - } - labelIndexMap[name.text] = labelStack.push(1) - 1; - return true; - } - function pushImplicitLabel() { - initializeReachabilityStateIfNecessary(); - var index = labelStack.push(1) - 1; - implicitLabels.push(index); - return index; - } - function popNamedLabel(label, outerState) { - var index = labelIndexMap[label.text]; - ts.Debug.assert(index !== undefined); - ts.Debug.assert(labelStack.length == index + 1); - labelIndexMap[label.text] = undefined; - setCurrentStateAtLabel(labelStack.pop(), outerState, label); - } - function popImplicitLabel(implicitLabelIndex, outerState) { - if (labelStack.length !== implicitLabelIndex + 1) { - ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); - } - var i = implicitLabels.pop(); - if (implicitLabelIndex !== i) { - ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); - } - setCurrentStateAtLabel(labelStack.pop(), outerState, undefined); - } - function setCurrentStateAtLabel(innerMergedState, outerState, label) { - if (innerMergedState === 1) { - if (label && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); - } - currentReachabilityState = outerState; - } - else { - currentReachabilityState = or(innerMergedState, outerState); - } - } - function jumpToLabel(label, outerState) { - initializeReachabilityStateIfNecessary(); - var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); - if (index === undefined) { - return false; - } - var stateAtLabel = labelStack[index]; - labelStack[index] = stateAtLabel === 1 ? outerState : or(stateAtLabel, outerState); - return true; - } - function checkUnreachable(node) { - switch (currentReachabilityState) { - case 4: - var reportError = ts.isStatement(node) || - node.kind === 214 || - (node.kind === 218 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 217 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); - if (reportError) { - currentReachabilityState = 8; - var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 193 || - ts.getCombinedNodeFlags(node.declarationList) & 24576 || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); - } - } - case 8: - return true; - default: - return false; - } - function shouldReportErrorOnModuleDeclaration(node) { - var instanceState = getModuleInstanceState(node); - return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); - } - } - function initializeReachabilityStateIfNecessary() { - if (labelIndexMap) { - return; - } - currentReachabilityState = 2; - labelIndexMap = {}; - labelStack = []; - implicitLabels = []; - } - } -})(ts || (ts = {})); -var ts; (function (ts) { function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -4176,7 +3505,7 @@ var ts; if (array1.length !== array2.length) { return false; } - for (var i = 0; i < array1.length; ++i) { + for (var i = 0; i < array1.length; i++) { var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; if (!equals) { return false; @@ -4202,26 +3531,38 @@ var ts; ts.setResolvedModule = setResolvedModule; function containsParseError(node) { aggregateChildData(node); - return (node.parserContextFlags & 64) !== 0; + return (node.flags & 268435456) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.parserContextFlags & 128)) { - var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & 16) !== 0) || + if (!(node.flags & 536870912)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 67108864) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { - node.parserContextFlags |= 64; + node.flags |= 268435456; } - node.parserContextFlags |= 128; + node.flags |= 536870912; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 248) { + while (node && node.kind !== 252) { node = node.parent; } return node; } ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 196: + case 224: + case 203: + case 204: + case 205: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; function getStartPositionOfLine(line, sourceFile) { ts.Debug.assert(line >= 0); return ts.getLineStarts(sourceFile)[line]; @@ -4296,10 +3637,39 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 24576) !== 0 || + return (getCombinedNodeFlags(declaration) & 3072) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isAmbientModule(node) { + return node && node.kind === 222 && + (node.name.kind === 9 || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isBlockScopedContainerTopLevel(node) { + return node.kind === 252 || + node.kind === 222 || + isFunctionLike(node) || + isFunctionBlock(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 131072); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + if (!node || !isAmbientModule(node)) { + return false; + } + switch (node.parent.kind) { + case 252: + return isExternalModule(node.parent); + case 223: + return isAmbientModule(node.parent.parent) && !isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -4307,15 +3677,15 @@ var ts; return current; } switch (current.kind) { + case 252: + case 224: case 248: - case 220: - case 244: - case 218: - case 199: - case 200: - case 201: + case 222: + case 203: + case 204: + case 205: return current; - case 192: + case 196: if (!isFunctionLike(current.parent)) { return current; } @@ -4326,9 +3696,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 211 && + declaration.kind === 215 && declaration.parent && - declaration.parent.kind === 244; + declaration.parent.kind === 248; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; function declarationNameToString(name) { @@ -4364,22 +3734,26 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 248: + case 252: 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 211: - case 163: - case 214: - case 186: case 215: + case 167: case 218: + case 190: + case 219: + case 222: + case 221: + case 251: case 217: - case 247: - case 213: - case 173: + case 177: + case 145: + case 147: + case 148: + case 220: errorNode = node.name; break; } @@ -4396,16 +3770,20 @@ var ts; return file.externalModuleIndicator !== undefined; } ts.isExternalModule = isExternalModule; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; function isDeclarationFile(file) { - return (file.flags & 4096) !== 0; + return file.isDeclarationFile; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 217 && isConst(node); + return node.kind === 221 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 163 || isBindingPattern(node))) { + while (node && (node.kind === 167 || isBindingPattern(node))) { node = node.parent; } return node; @@ -4413,113 +3791,123 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 211) { + if (node.kind === 215) { node = node.parent; } - if (node && node.kind === 212) { + if (node && node.kind === 216) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 193) { + if (node && node.kind === 197) { flags |= node.flags; } return flags; } ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 16384); + return !!(getCombinedNodeFlags(node) & 2048); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 8192); + return !!(getCombinedNodeFlags(node) & 1024); } ts.isLet = isLet; + function isSuperCallExpression(n) { + return n.kind === 172 && n.expression.kind === 95; + } + ts.isSuperCallExpression = isSuperCallExpression; function isPrologueDirective(node) { - return node.kind === 195 && node.expression.kind === 9; + return node.kind === 199 && node.expression.kind === 9; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getLeadingCommentRangesOfNodeFromText(node, text) { + return ts.getLeadingCommentRanges(text, node.pos); + } + ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; function getJsDocComments(node, sourceFileOfNode) { - var commentRanges = (node.kind === 138 || node.kind === 137) ? - ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) : - getLeadingCommentRangesOfNode(node, sourceFileOfNode); - return ts.filter(commentRanges, isJsDocComment); - function isJsDocComment(comment) { - return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === 42 && - sourceFileOfNode.text.charCodeAt(comment.pos + 2) === 42 && - sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== 47; - } + return getJsDocCommentsFromText(node, sourceFileOfNode.text); } ts.getJsDocComments = getJsDocComments; + function getJsDocCommentsFromText(node, text) { + var commentRanges = (node.kind === 140 || node.kind === 139) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + getLeadingCommentRangesOfNodeFromText(node, text); + return ts.filter(commentRanges, isJsDocComment); + function isJsDocComment(comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 42 && + text.charCodeAt(comment.pos + 3) !== 47; + } + } + ts.getJsDocCommentsFromText = getJsDocCommentsFromText; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isTypeNode(node) { - if (151 <= node.kind && node.kind <= 160) { + if (152 <= node.kind && node.kind <= 164) { return true; } switch (node.kind) { case 117: - case 128: - case 130: - case 120: + case 129: case 131: + case 120: + case 132: return true; case 103: - return node.parent.kind !== 177; - case 9: - return node.parent.kind === 138; - case 188: + return node.parent.kind !== 181; + case 192: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); case 69: - if (node.parent.kind === 135 && node.parent.right === node) { + if (node.parent.kind === 137 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 166 && node.parent.name === node) { + else if (node.parent.kind === 170 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 69 || node.kind === 135 || node.kind === 166, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); - case 135: - case 166: + ts.Debug.assert(node.kind === 69 || node.kind === 137 || node.kind === 170, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + case 137: + case 170: case 97: var parent_1 = node.parent; - if (parent_1.kind === 154) { + if (parent_1.kind === 156) { return false; } - if (151 <= parent_1.kind && parent_1.kind <= 160) { + if (152 <= parent_1.kind && parent_1.kind <= 164) { return true; } switch (parent_1.kind) { - case 188: + case 192: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); - case 137: + case 139: return node === parent_1.constraint; - case 141: - case 140: - case 138: - case 211: - return node === parent_1.type; - case 213: - case 173: - case 174: - case 144: case 143: case 142: - case 145: - case 146: + case 140: + case 215: return node === parent_1.type; + case 217: + case 177: + case 178: + case 146: + case 145: + case 144: case 147: case 148: + return node === parent_1.type; case 149: + case 150: + case 151: return node === parent_1.type; - case 171: + case 175: return node === parent_1.type; - case 168: - case 169: + case 172: + case 173: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 170: + case 174: return false; } } @@ -4530,23 +3918,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 204: + case 208: return visitor(node); - case 220: - case 192: + case 224: case 196: - case 197: - case 198: - case 199: case 200: case 201: + case 202: + case 203: + case 204: case 205: - case 206: - case 241: - case 242: - case 207: case 209: - case 244: + case 210: + case 245: + case 246: + case 211: + case 213: + case 248: return ts.forEachChild(node, traverse); } } @@ -4556,23 +3944,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 184: + case 188: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 217: - case 215: + case 221: + case 219: + case 222: + case 220: case 218: - case 216: - case 214: - case 186: + case 190: return; default: if (isFunctionLike(node)) { var name_5 = node.name; - if (name_5 && name_5.kind === 136) { + if (name_5 && name_5.kind === 138) { traverse(name_5.expression); return; } @@ -4587,14 +3975,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 163: - case 247: - case 138: - case 245: - case 141: + case 167: + case 251: case 140: - case 246: - case 211: + case 249: + case 143: + case 142: + case 250: + case 215: return true; } } @@ -4602,11 +3990,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - return node && (node.kind === 145 || node.kind === 146); + return node && (node.kind === 147 || node.kind === 148); } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 214 || node.kind === 186); + return node && (node.kind === 218 || node.kind === 190); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -4615,32 +4003,32 @@ var ts; ts.isFunctionLike = isFunctionLike; function isFunctionLikeKind(kind) { switch (kind) { - case 144: - case 173: - case 213: - case 174: - case 143: - case 142: - case 145: case 146: + case 177: + case 217: + case 178: + case 145: + case 144: case 147: case 148: case 149: - case 152: - case 153: + case 150: + case 151: + case 154: + case 155: return true; } } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 143: - case 142: - case 144: case 145: + case 144: case 146: - case 213: - case 173: + case 147: + case 148: + case 217: + case 177: return true; } return false; @@ -4648,26 +4036,34 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 199: - case 200: + case 203: + case 204: + case 205: case 201: - case 197: - case 198: + case 202: return true; - case 207: + case 211: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 192 && isFunctionLike(node.parent); + return node && node.kind === 196 && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 143 && node.parent.kind === 165; + return node && node.kind === 145 && node.parent.kind === 169; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0; + } + ts.isThisTypePredicate = isThisTypePredicate; function getContainingFunction(node) { while (true) { node = node.parent; @@ -4693,91 +4089,95 @@ var ts; return undefined; } switch (node.kind) { - case 136: + case 138: if (isClassLike(node.parent.parent)) { return node; } node = node.parent; break; - case 139: - if (node.parent.kind === 138 && isClassElement(node.parent.parent)) { + case 141: + if (node.parent.kind === 140 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 174: + case 178: if (!includeArrowFunctions) { continue; } - case 213: - case 173: - case 218: - case 141: - case 140: + case 217: + case 177: + case 222: case 143: case 142: - case 144: case 145: + case 144: case 146: case 147: case 148: case 149: - case 217: - case 248: + case 150: + case 151: + case 221: + case 252: return node; } } } ts.getThisContainer = getThisContainer; - function getSuperContainer(node, includeFunctions) { + function getSuperContainer(node, stopOnFunctions) { while (true) { node = node.parent; - if (!node) + if (!node) { return node; + } switch (node.kind) { - case 136: - if (isClassLike(node.parent.parent)) { - return node; - } + case 138: node = node.parent; break; - case 139: - if (node.parent.kind === 138 && isClassElement(node.parent.parent)) { + case 217: + case 177: + case 178: + if (!stopOnFunctions) { + continue; + } + case 143: + case 142: + case 145: + case 144: + case 146: + case 147: + case 148: + return node; + case 141: + if (node.parent.kind === 140 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 213: - case 173: - case 174: - if (!includeFunctions) { - continue; - } - case 141: - case 140: - case 143: - case 142: - case 144: - case 145: - case 146: - return node; } } } ts.getSuperContainer = getSuperContainer; + function isSuperPropertyOrElementAccess(node) { + return (node.kind === 170 + || node.kind === 171) + && node.expression.kind === 95; + } + ts.isSuperPropertyOrElementAccess = isSuperPropertyOrElementAccess; function getEntityNameFromTypeNode(node) { if (node) { switch (node.kind) { - case 151: + case 153: return node.typeName; - case 188: + case 192: return node.expression; case 69: - case 135: + case 137: return node; } } @@ -4785,7 +4185,7 @@ var ts; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 170) { + if (node.kind === 174) { return node.tag; } return node.expression; @@ -4793,69 +4193,36 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 214: + case 218: return true; - case 141: - return node.parent.kind === 214; - case 138: - return node.parent.body && node.parent.parent.kind === 214; - case 145: - case 146: case 143: - return node.body && node.parent.kind === 214; + return node.parent.kind === 218; + case 147: + case 148: + case 145: + return node.body !== undefined + && node.parent.kind === 218; + case 140: + return node.parent.body !== undefined + && (node.parent.kind === 146 + || node.parent.kind === 145 + || node.parent.kind === 148) + && node.parent.parent.kind === 218; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { - switch (node.kind) { - case 214: - if (node.decorators) { - return true; - } - return false; - case 141: - case 138: - if (node.decorators) { - return true; - } - return false; - case 145: - if (node.body && node.decorators) { - return true; - } - return false; - case 143: - case 146: - if (node.body && node.decorators) { - return true; - } - return false; - } - return false; + return node.decorators !== undefined + && nodeCanBeDecorated(node); } ts.nodeIsDecorated = nodeIsDecorated; - function childIsDecorated(node) { - switch (node.kind) { - case 214: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 143: - case 146: - return ts.forEach(node.parameters, nodeIsDecorated); - } - return false; - } - ts.childIsDecorated = childIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); - } - ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function isPropertyAccessExpression(node) { - return node.kind === 166; + return node.kind === 170; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 167; + return node.kind === 171; } ts.isElementAccessExpression = isElementAccessExpression; function isExpression(node) { @@ -4865,42 +4232,42 @@ var ts; case 99: case 84: case 10: - case 164: - case 165: - case 166: - case 167: case 168: case 169: case 170: - case 189: case 171: case 172: case 173: - case 186: case 174: - case 177: + case 193: case 175: case 176: + case 177: + case 190: + case 178: + case 181: case 179: case 180: - case 181: - case 182: - case 185: case 183: - case 11: - case 187: - case 233: - case 234: case 184: - case 178: + case 185: + case 186: + case 189: + case 187: + case 11: + case 191: + case 237: + case 238: + case 188: + case 182: return true; - case 135: - while (node.parent.kind === 135) { + case 137: + while (node.parent.kind === 137) { node = node.parent; } - return node.parent.kind === 154; + return node.parent.kind === 156; case 69: - if (node.parent.kind === 154) { + if (node.parent.kind === 156) { return true; } case 8: @@ -4908,47 +4275,47 @@ var ts; case 97: var parent_2 = node.parent; switch (parent_2.kind) { - case 211: - case 138: - case 141: + case 215: case 140: - case 247: - case 245: - case 163: + case 143: + case 142: + case 251: + case 249: + case 167: return parent_2.initializer === node; - case 195: - case 196: - case 197: - case 198: - case 204: - case 205: - case 206: - case 241: - case 208: - case 206: - return parent_2.expression === node; case 199: - var forStatement = parent_2; - return (forStatement.initializer === node && forStatement.initializer.kind !== 212) || - forStatement.condition === node || - forStatement.incrementor === node; case 200: case 201: + case 202: + case 208: + case 209: + case 210: + case 245: + case 212: + case 210: + return parent_2.expression === node; + case 203: + var forStatement = parent_2; + return (forStatement.initializer === node && forStatement.initializer.kind !== 216) || + forStatement.condition === node || + forStatement.incrementor === node; + case 204: + case 205: var forInStatement = parent_2; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 212) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 216) || forInStatement.expression === node; - case 171: - case 189: + case 175: + case 193: return node === parent_2.expression; - case 190: + case 194: return node === parent_2.expression; - case 136: + case 138: return node === parent_2.expression; - case 139: - case 240: - case 239: + case 141: + case 244: + case 243: return true; - case 188: + case 192: return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: if (isExpression(parent_2)) { @@ -4970,7 +4337,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 && node.moduleReference.kind === 232; + return node.kind === 225 && node.moduleReference.kind === 236; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -4979,34 +4346,83 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 && node.moduleReference.kind !== 232; + return node.kind === 225 && node.moduleReference.kind !== 236; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJavaScript(file) { + return isInJavaScriptFile(file); + } + ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isInJavaScriptFile(node) { + return node && !!(node.flags & 134217728); + } + ts.isInJavaScriptFile = isInJavaScriptFile; + function isRequireCall(expression, checkArgumentIsStringLiteral) { + var isRequire = expression.kind === 172 && + expression.expression.kind === 69 && + expression.expression.text === "require" && + expression.arguments.length === 1; + return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9); + } + ts.isRequireCall = isRequireCall; + function getSpecialPropertyAssignmentKind(expression) { + if (expression.kind !== 185) { + return 0; + } + var expr = expression; + if (expr.operatorToken.kind !== 56 || expr.left.kind !== 170) { + return 0; + } + var lhs = expr.left; + if (lhs.expression.kind === 69) { + var lhsId = lhs.expression; + if (lhsId.text === "exports") { + return 1; + } + else if (lhsId.text === "module" && lhs.name.text === "exports") { + return 2; + } + } + else if (lhs.expression.kind === 97) { + return 4; + } + else if (lhs.expression.kind === 170) { + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 69 && innerPropertyAccess.name.text === "prototype") { + return 3; + } + } + return 0; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 222) { + if (node.kind === 226) { return node.moduleSpecifier; } - if (node.kind === 221) { + if (node.kind === 225) { var reference = node.moduleReference; - if (reference.kind === 232) { + if (reference.kind === 236) { return reference.expression; } } - if (node.kind === 228) { + if (node.kind === 232) { return node.moduleSpecifier; } + if (node.kind === 222 && node.name.kind === 9) { + return node.name; + } } ts.getExternalModuleName = getExternalModuleName; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 138: + case 140: + case 145: + case 144: + case 250: + case 249: case 143: case 142: - case 246: - case 245: - case 141: - case 140: return node.questionToken !== undefined; } } @@ -5014,49 +4430,83 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 261 && + return node.kind === 265 && node.parameters.length > 0 && - node.parameters[0].type.kind === 263; + node.parameters[0].type.kind === 267; } 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 getJSDocTag(node, kind, checkParentVariableStatement) { + if (!node) { + return undefined; + } + var jsDocComment = getJSDocComment(node, checkParentVariableStatement); + if (!jsDocComment) { + return undefined; + } + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === kind) { + return tag; } } } + function getJSDocComment(node, checkParentVariableStatement) { + if (node.jsDocComment) { + return node.jsDocComment; + } + if (checkParentVariableStatement) { + var isInitializerOfVariableDeclarationInStatement = node.parent.kind === 215 && + node.parent.initializer === node && + node.parent.parent.parent.kind === 197; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined; + if (variableStatementNode) { + return variableStatementNode.jsDocComment; + } + var parent_3 = node.parent; + var isSourceOfAssignmentExpressionStatement = parent_3 && parent_3.parent && + parent_3.kind === 185 && + parent_3.operatorToken.kind === 56 && + parent_3.parent.kind === 199; + if (isSourceOfAssignmentExpressionStatement) { + return parent_3.parent.jsDocComment; + } + var isPropertyAssignmentExpression = parent_3 && parent_3.kind === 249; + if (isPropertyAssignmentExpression) { + return parent_3.jsDocComment; + } + } + return undefined; + } function getJSDocTypeTag(node) { - return getJSDocTag(node, 269); + return getJSDocTag(node, 273, false); } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 268); + return getJSDocTag(node, 272, true); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 270); + return getJSDocTag(node, 274, false); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getCorrespondingJSDocParameterTag(parameter) { if (parameter.name && parameter.name.kind === 69) { var parameterName = parameter.name.text; - var docComment = parameter.parent.jsDocComment; - if (docComment) { - return ts.forEach(docComment.tags, function (t) { - if (t.kind === 267) { - var parameterTag = t; + var jsDocComment = getJSDocComment(parameter.parent, true); + if (jsDocComment) { + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === 271) { + var parameterTag = tag; var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; if (name_6.text === parameterName) { - return t; + return parameterTag; } } - }); + } } } + return undefined; } ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; function hasRestParameter(s) { @@ -5065,13 +4515,13 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { if (node) { - if (node.parserContextFlags & 32) { - if (node.type && node.type.kind === 262) { + if (node.flags & 134217728) { + if (node.type && node.type.kind === 266) { return true; } var paramTag = getCorrespondingJSDocParameterTag(node); if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 262; + return paramTag.typeExpression.type.kind === 266; } } return node.dotDotDotToken !== undefined; @@ -5092,7 +4542,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 162 || node.kind === 161); + return !!node && (node.kind === 166 || node.kind === 165); } ts.isBindingPattern = isBindingPattern; function isNodeDescendentOf(node, ancestor) { @@ -5106,7 +4556,7 @@ var ts; ts.isNodeDescendentOf = isNodeDescendentOf; function isInAmbientContext(node) { while (node) { - if (node.flags & (4 | 4096)) { + if (node.flags & 2 || (node.kind === 252 && node.isDeclarationFile)) { return true; } node = node.parent; @@ -5116,34 +4566,34 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 174: - case 163: - case 214: - case 186: - case 144: - case 217: - case 247: - case 230: - case 213: - case 173: - case 145: - case 223: + case 178: + case 167: + case 218: + case 190: + case 146: case 221: - case 226: - case 215: + case 251: + case 234: + case 217: + case 177: + case 147: + case 227: + case 225: + case 230: + case 219: + case 145: + case 144: + case 222: + case 228: + case 140: + case 249: case 143: case 142: - case 218: - case 224: - case 138: - case 245: - case 141: - case 140: - case 146: - case 246: - case 216: - case 137: - case 211: + case 148: + case 250: + case 220: + case 139: + case 215: return true; } return false; @@ -5151,25 +4601,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 203: - case 202: - case 210: - case 197: - case 195: - case 194: - case 200: + case 207: + case 206: + case 214: case 201: case 199: - case 196: - case 207: - case 204: - case 206: - case 208: - case 209: - case 193: case 198: + case 204: case 205: - case 227: + case 203: + case 200: + case 211: + case 208: + case 210: + case 212: + case 213: + case 197: + case 202: + case 209: + case 231: return true; default: return false; @@ -5178,13 +4628,13 @@ var ts; ts.isStatement = isStatement; function isClassElement(n) { switch (n.kind) { - case 144: - case 141: + case 146: case 143: case 145: - case 146: - case 142: - case 149: + case 147: + case 148: + case 144: + case 151: return true; default: return false; @@ -5196,7 +4646,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 226 || parent.kind === 230) { + if (parent.kind === 230 || parent.kind === 234) { if (parent.propertyName) { return true; } @@ -5210,40 +4660,40 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 141: - case 140: case 143: case 142: case 145: - case 146: - case 247: - case 245: - case 166: + case 144: + case 147: + case 148: + case 251: + case 249: + case 170: return parent.name === node; - case 135: + case 137: if (parent.right === node) { - while (parent.kind === 135) { + while (parent.kind === 137) { parent = parent.parent; } - return parent.kind === 154; + return parent.kind === 156; } return false; - case 163: - case 226: - return parent.propertyName === node; + case 167: case 230: + return parent.propertyName === node; + case 234: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 221 || - node.kind === 223 && !!node.name || - node.kind === 224 || - node.kind === 226 || + return node.kind === 225 || + node.kind === 227 && !!node.name || + node.kind === 228 || node.kind === 230 || - node.kind === 227 && node.expression.kind === 69; + node.kind === 234 || + node.kind === 231 && node.expression.kind === 69; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -5293,8 +4743,8 @@ var ts; function getFileReferenceFromReferencePath(comment, commentRange) { var simpleReferenceRegEx = /^\/\/\/\s*/gim; - if (simpleReferenceRegEx.exec(comment)) { - if (isNoDefaultLibRegEx.exec(comment)) { + if (simpleReferenceRegEx.test(comment)) { + if (isNoDefaultLibRegEx.test(comment)) { return { isNoDefaultLib: true }; @@ -5325,7 +4775,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 70 <= token && token <= 134; + return 70 <= token && token <= 136; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -5336,12 +4786,20 @@ var ts; return isFunctionLike(node) && (node.flags & 256) !== 0 && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; + function isStringOrNumericLiteral(kind) { + return kind === 9 || kind === 8; + } + ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && - declaration.name.kind === 136 && - !isWellKnownSymbolSyntactically(declaration.name.expression); + return declaration.name && isDynamicName(declaration.name); } ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 138 && + !isStringOrNumericLiteral(name.expression.kind) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; function isWellKnownSymbolSyntactically(node) { return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); } @@ -5350,7 +4808,7 @@ var ts; if (name.kind === 69 || name.kind === 9 || name.kind === 8) { return name.text; } - if (name.kind === 136) { + if (name.kind === 138) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -5368,7 +4826,7 @@ var ts; return node.kind === 69 && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; - function isModifier(token) { + function isModifierKind(token) { switch (token) { case 115: case 118: @@ -5379,44 +4837,62 @@ var ts; case 112: case 110: case 111: + case 127: case 113: return true; } return false; } - ts.isModifier = isModifier; + ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 138; + return root.kind === 140; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 163) { + while (node.kind === 167) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 218 || n.kind === 248; + return isFunctionLike(n) || n.kind === 222 || n.kind === 252; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneEntityName(node) { - if (node.kind === 69) { - var clone_1 = createSynthesizedNode(69); - clone_1.text = node.text; - return clone_1; + function cloneNode(node, location, flags, parent) { + var clone = location !== undefined + ? ts.createNode(node.kind, location.pos, location.end) + : createSynthesizedNode(node.kind); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; } - else { - var clone_2 = createSynthesizedNode(135); - clone_2.left = cloneEntityName(node.left); - clone_2.left.parent = clone_2; - clone_2.right = cloneEntityName(node.right); - clone_2.right.parent = clone_2; - return clone_2; + if (flags !== undefined) { + clone.flags = flags; } + if (parent !== undefined) { + clone.parent = parent; + } + return clone; + } + ts.cloneNode = cloneNode; + function cloneEntityName(node, parent) { + var clone = cloneNode(node, node, node.flags, parent); + if (isQualifiedName(clone)) { + var left = clone.left, right = clone.right; + clone.left = cloneEntityName(left, clone); + clone.right = cloneNode(right, right, right.flags, parent); + } + return clone; } ts.cloneEntityName = cloneEntityName; + function isQualifiedName(node) { + return node.kind === 137; + } + ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { return node.pos === -1; } @@ -5562,11 +5038,11 @@ var ts; } ts.getIndentSize = getIndentSize; function createTextWriter(newLine) { - var output = ""; - var indent = 0; - var lineStart = true; - var lineCount = 0; - var linePos = 0; + var output; + var indent; + var lineStart; + var lineCount; + var linePos; function write(s) { if (s && s.length) { if (lineStart) { @@ -5576,6 +5052,13 @@ var ts; output += s; } } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } function rawWrite(s) { if (s !== undefined) { if (lineStart) { @@ -5602,25 +5085,35 @@ var ts; lineStart = true; } } - function writeTextOfNode(sourceFile, node) { - write(getSourceTextOfNodeFromSourceFile(sourceFile, node)); + function writeTextOfNode(text, node) { + write(getTextOfNodeFromSourceText(text, node)); } + reset(); return { write: write, rawWrite: rawWrite, writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, - increaseIndent: function () { return indent++; }, - decreaseIndent: function () { return indent--; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, getLine: function () { return lineCount + 1; }, getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, - getText: function () { return output; } + getText: function () { return output; }, + reset: reset }; } ts.createTextWriter = createTextWriter; + function getExternalModuleNameFromPath(host, fileName) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); + return ts.removeFileExtension(relativePath); + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; function getOwnEmitOutputFilePath(sourceFile, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; @@ -5633,6 +5126,72 @@ var ts; return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + onBundledEmit(host); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + if (!isDeclarationFile(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + var extension = ".js"; + if (options.jsx === 1) { + if (isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + extension = ".jsx"; + } + } + else if (sourceFile.languageVariant === 1) { + extension = ".jsx"; + } + } + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined + }; + action(emitFileNames, [sourceFile], false); + } + function onBundledEmit(host) { + var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + (!isExternalModule(sourceFile) || + (getEmitModuleKind(options) && isExternalModule(sourceFile))); }); + if (bundledSources.length) { + var jsFilePath = options.outFile || options.out; + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options) + }; + action(emitFileNames, bundledSources, true); + } + } + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getDeclarationEmitFilePath(jsFilePath, options) { + return options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + } + } + ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); @@ -5641,7 +5200,7 @@ var ts; ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }); } ts.writeFile = writeFile; @@ -5649,9 +5208,13 @@ var ts; return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 144 && nodeIsPresent(member.body)) { + if (member.kind === 146 && nodeIsPresent(member.body)) { return member; } }); @@ -5661,16 +5224,6 @@ var ts; return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; - function shouldEmitToOwnFile(sourceFile, compilerOptions) { - if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) { - return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); - } - return false; - } - return false; - } - ts.shouldEmitToOwnFile = shouldEmitToOwnFile; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -5678,10 +5231,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 145) { + if (accessor.kind === 147) { getAccessor = accessor; } - else if (accessor.kind === 146) { + else if (accessor.kind === 148) { setAccessor = accessor; } else { @@ -5690,8 +5243,8 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 145 || member.kind === 146) - && (member.flags & 64) === (accessor.flags & 64)) { + if ((member.kind === 147 || member.kind === 148) + && (member.flags & 32) === (accessor.flags & 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -5701,10 +5254,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 145 && !getAccessor) { + if (member.kind === 147 && !getAccessor) { getAccessor = member; } - if (member.kind === 146 && !setAccessor) { + if (member.kind === 148 && !setAccessor) { setAccessor = member; } } @@ -5719,21 +5272,21 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) { + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && - getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) { + getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { writer.writeLine(); } } ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; - function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) { + function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) { var emitLeadingSpace = !trailingSeparator; ts.forEach(comments, function (comment) { if (emitLeadingSpace) { writer.write(" "); emitLeadingSpace = false; } - writeComment(currentSourceFile, writer, comment, newLine); + writeComment(text, lineMap, writer, comment, newLine); if (comment.hasTrailingNewLine) { writer.writeLine(); } @@ -5746,16 +5299,16 @@ var ts; }); } ts.emitComments = emitComments; - function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) { + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { var leadingComments; var currentDetachedCommentInfo; if (removeComments) { if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment); + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); } } else { - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + leadingComments = ts.getLeadingCommentRanges(text, node.pos); } if (leadingComments) { var detachedComments = []; @@ -5763,8 +5316,8 @@ var ts; for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { var comment = leadingComments_1[_i]; if (lastComment) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); if (commentLine >= lastCommentLine + 2) { break; } @@ -5773,37 +5326,37 @@ var ts; lastComment = comment; } if (detachedComments.length) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); - var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } } return currentDetachedCommentInfo; function isPinnedComment(comment) { - return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 33; + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 33; } } ts.emitDetachedComments = emitDetachedComments; - function writeCommentRange(currentSourceFile, writer, comment, newLine) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42) { - var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos); - var lineCount = ts.getLineStarts(currentSourceFile).length; + function writeCommentRange(text, lineMap, writer, comment, newLine) { + if (text.charCodeAt(comment.pos + 1) === 42) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos); + var lineCount = lineMap.length; var firstCommentLineIndent; for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { var nextLineStart = (currentLine + 1) === lineCount - ? currentSourceFile.text.length + 1 - : getStartPositionOfLine(currentLine + 1, currentSourceFile); + ? text.length + 1 + : lineMap[currentLine + 1]; if (pos !== comment.pos) { if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos); + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos); } var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); - var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); if (spacesToEmit > 0) { var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); @@ -5817,52 +5370,53 @@ var ts; writer.rawWrite(""); } } - writeTrimmedCurrentLine(pos, nextLineStart); + writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart); pos = nextLineStart; } } else { - writer.write(currentSourceFile.text.substring(comment.pos, comment.end)); - } - function writeTrimmedCurrentLine(pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); - var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ""); - if (currentLineText) { - writer.write(currentLineText); - if (end !== comment.end) { - writer.writeLine(); - } - } - else { - writer.writeLiteral(newLine); - } - } - function calculateIndent(pos, end) { - var currentLineIndent = 0; - for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) { - if (currentSourceFile.text.charCodeAt(pos) === 9) { - currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); - } - else { - currentLineIndent++; - } - } - return currentLineIndent; + writer.write(text.substring(comment.pos, comment.end)); } } ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) { + var end = Math.min(comment.end, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + writer.write(currentLineText); + if (end !== comment.end) { + writer.writeLine(); + } + } + else { + writer.writeLiteral(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpace(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9) { + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + currentLineIndent++; + } + } + return currentLineIndent; + } function modifierToFlag(token) { switch (token) { - case 113: return 64; - case 112: return 8; - case 111: return 32; - case 110: return 16; + case 113: return 32; + case 112: return 4; + case 111: return 16; + case 110: return 8; case 115: return 128; - case 82: return 2; - case 122: return 4; - case 74: return 16384; + case 82: return 1; + case 122: return 2; + case 74: return 2048; case 77: return 512; case 118: return 256; + case 127: return 64; } return 0; } @@ -5870,24 +5424,24 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 166: - case 167: - case 169: - case 168: - case 233: - case 234: case 170: - case 164: - case 172: - case 165: - case 186: + case 171: case 173: + case 172: + case 237: + case 238: + case 174: + case 168: + case 176: + case 169: + case 190: + case 177: case 69: case 10: case 8: case 9: case 11: - case 183: + case 187: case 84: case 93: case 97: @@ -5904,7 +5458,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 188 && + return node.kind === 192 && node.parent.token === 83 && isClassLike(node.parent.parent); } @@ -5925,16 +5479,16 @@ var ts; } } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 135 && node.parent.right === node) || - (node.parent.kind === 166 && node.parent.name === node); + return (node.parent.kind === 137 && node.parent.right === node) || + (node.parent.kind === 170 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 165) { + if (kind === 169) { return expression.properties.length === 0; } - if (kind === 164) { + if (kind === 168) { return expression.elements.length === 0; } return false; @@ -5944,14 +5498,10 @@ var ts; return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function isJavaScript(fileName) { - return ts.fileExtensionIs(fileName, ".js"); + function hasJavaScriptFileExtension(fileName) { + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.isJavaScript = isJavaScript; - function isTsx(fileName) { - return ts.fileExtensionIs(fileName, ".tsx"); - } - ts.isTsx = isTsx; + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -5981,6 +5531,39 @@ var ts; } return output; } + ts.stringify = typeof JSON !== "undefined" && JSON.stringify + ? JSON.stringify + : stringifyFallback; + function stringifyFallback(value) { + return value === undefined ? undefined : stringifyValue(value); + } + function stringifyValue(value) { + return typeof value === "string" ? "\"" + escapeString(value) + "\"" + : typeof value === "number" ? isFinite(value) ? String(value) : "null" + : typeof value === "boolean" ? value ? "true" : "false" + : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) + : "null"; + } + function cycleCheck(cb, value) { + ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); + value.__cycle = true; + var result = cb(value); + delete value.__cycle; + return result; + } + function stringifyArray(value) { + return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; + } + function stringifyElement(memo, value) { + return (memo ? memo + "," : memo) + stringifyValue(value); + } + function stringifyObject(value) { + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + } + function stringifyProperty(memo, value, key) { + return value === undefined || typeof value === "function" || key === "__cycle" ? memo + : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); + } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function convertToBase64(input) { var result = ""; @@ -6149,26 +5732,32 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 137) { + if (d && d.kind === 139) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 215) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 219) { return current; } } } } ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return node.flags & 28 && node.parent.kind === 146 && ts.isClassLike(node.parent.parent); + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; })(ts || (ts = {})); var ts; (function (ts) { - var nodeConstructors = new Array(272); ts.parseTime = 0; - function getNodeConstructor(kind) { - return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); - } - ts.getNodeConstructor = getNodeConstructor; + var NodeConstructor; + var SourceFileConstructor; function createNode(kind, pos, end) { - return new (getNodeConstructor(kind))(pos, end); + if (kind === 252) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } } ts.createNode = createNode; function visitNode(cbNode, node) { @@ -6199,26 +5788,26 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 135: + case 137: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 137: + case 139: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 246: + case 250: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 138: - case 141: case 140: - case 245: - case 211: - case 163: + case 143: + case 142: + case 249: + case 215: + case 167: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -6227,24 +5816,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 152: - case 153: - case 147: - case 148: + case 154: + case 155: case 149: + case 150: + case 151: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 143: - case 142: - case 144: case 145: + case 144: case 146: - case 173: - case 213: - case 174: + case 147: + case 148: + case 177: + case 217: + case 178: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -6255,302 +5844,318 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 151: + case 153: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 150: + case 152: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 154: - return visitNode(cbNode, node.exprName); - case 155: - return visitNodes(cbNodes, node.members); case 156: - return visitNode(cbNode, node.elementType); + return visitNode(cbNode, node.exprName); case 157: - return visitNodes(cbNodes, node.elementTypes); + return visitNodes(cbNodes, node.members); case 158: + return visitNode(cbNode, node.elementType); case 159: - return visitNodes(cbNodes, node.types); + return visitNodes(cbNodes, node.elementTypes); case 160: - return visitNode(cbNode, node.type); case 161: + return visitNodes(cbNodes, node.types); case 162: - return visitNodes(cbNodes, node.elements); - case 164: - return visitNodes(cbNodes, node.elements); + return visitNode(cbNode, node.type); case 165: - return visitNodes(cbNodes, node.properties); case 166: + return visitNodes(cbNodes, node.elements); + case 168: + return visitNodes(cbNodes, node.elements); + case 169: + return visitNodes(cbNodes, node.properties); + case 170: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 167: + case 171: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 168: - case 169: + case 172: + case 173: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 170: + case 174: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 171: + case 175: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 172: - return visitNode(cbNode, node.expression); - case 175: - return visitNode(cbNode, node.expression); case 176: return visitNode(cbNode, node.expression); - case 177: - return visitNode(cbNode, node.expression); case 179: - return visitNode(cbNode, node.operand); - case 184: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); - case 178: return visitNode(cbNode, node.expression); case 180: - return visitNode(cbNode, node.operand); + return visitNode(cbNode, node.expression); case 181: + return visitNode(cbNode, node.expression); + case 183: + return visitNode(cbNode, node.operand); + case 188: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 182: + return visitNode(cbNode, node.expression); + case 184: + return visitNode(cbNode, node.operand); + case 185: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 189: + case 193: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 182: + case 186: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 185: + case 189: return visitNode(cbNode, node.expression); - case 192: - case 219: + case 196: + case 223: return visitNodes(cbNodes, node.statements); - case 248: + case 252: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 193: + case 197: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 212: + case 216: return visitNodes(cbNodes, node.declarations); - case 195: + case 199: return visitNode(cbNode, node.expression); - case 196: + case 200: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 197: + case 201: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 198: + case 202: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 199: + case 203: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 200: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 201: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 202: - case 203: - return visitNode(cbNode, node.label); case 204: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); case 205: - return visitNode(cbNode, node.expression) || + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); case 206: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 220: - return visitNodes(cbNodes, node.clauses); - case 241: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 242: - return visitNodes(cbNodes, node.statements); case 207: - return visitNode(cbNode, node.label) || - visitNode(cbNode, node.statement); + return visitNode(cbNode, node.label); case 208: return visitNode(cbNode, node.expression); case 209: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 210: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 224: + return visitNodes(cbNodes, node.clauses); + case 245: + return visitNode(cbNode, node.expression) || + visitNodes(cbNodes, node.statements); + case 246: + return visitNodes(cbNodes, node.statements); + case 211: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 212: + return visitNode(cbNode, node.expression); + case 213: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 244: + case 248: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 139: + case 141: return visitNode(cbNode, node.expression); - case 214: - case 186: + case 218: + case 190: 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 215: + case 219: 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 216: + case 220: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 217: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.members); - case 247: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 218: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); case 221: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); + visitNodes(cbNodes, node.members); + case 251: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 222: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 225: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 226: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 223: + case 227: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 224: - return visitNode(cbNode, node.name); - case 225: - case 229: - return visitNodes(cbNodes, node.elements); case 228: + return visitNode(cbNode, node.name); + case 229: + case 233: + return visitNodes(cbNodes, node.elements); + case 232: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 226: case 230: + case 234: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 227: + case 231: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 183: + case 187: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 190: + case 194: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 136: + case 138: return visitNode(cbNode, node.expression); - case 243: + case 247: return visitNodes(cbNodes, node.types); - case 188: + case 192: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 232: + case 236: return visitNode(cbNode, node.expression); - case 231: + case 235: return visitNodes(cbNodes, node.decorators); - case 233: + case 237: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 234: - case 235: + case 238: + case 239: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 238: + case 242: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 239: + case 243: return visitNode(cbNode, node.expression); - case 240: + case 244: return visitNode(cbNode, node.expression); - case 237: + case 241: return visitNode(cbNode, node.tagName); - case 249: - return visitNode(cbNode, node.type); case 253: - return visitNodes(cbNodes, node.types); - case 254: - return visitNodes(cbNodes, node.types); - case 252: - return visitNode(cbNode, node.elementType); - case 256: - return visitNode(cbNode, node.type); - case 255: return visitNode(cbNode, node.type); case 257: - return visitNodes(cbNodes, node.members); - case 259: - return visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeArguments); + return visitNodes(cbNodes, node.types); + case 258: + return visitNodes(cbNodes, node.types); + case 256: + return visitNode(cbNode, node.elementType); case 260: return visitNode(cbNode, node.type); + case 259: + return visitNode(cbNode, node.type); case 261: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 262: - return visitNode(cbNode, node.type); + return visitNodes(cbNodes, node.members); case 263: - return visitNode(cbNode, node.type); + return visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeArguments); case 264: return visitNode(cbNode, node.type); - case 258: + case 265: + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 266: + return visitNode(cbNode, node.type); + case 267: + return visitNode(cbNode, node.type); + case 268: + return visitNode(cbNode, node.type); + case 262: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 265: + case 269: return visitNodes(cbNodes, node.tags); - case 267: + case 271: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 268: + case 272: return visitNode(cbNode, node.typeExpression); - case 269: + case 273: return visitNode(cbNode, node.typeExpression); - case 270: + case 274: return visitNodes(cbNodes, node.typeParameters); } } ts.forEachChild = forEachChild; - function createSourceFile(fileName, sourceText, languageVersion, setParentNodes) { + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } var start = new Date().getTime(); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); ts.parseTime += new Date().getTime() - start; return result; } ts.createSourceFile = createSourceFile; + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js": + return 1; + case ".jsx": + return 2; + case ".ts": + return 3; + case ".tsx": + return 4; + default: + return 3; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); } @@ -6566,7 +6171,9 @@ var ts; var Parser; (function (Parser) { var scanner = ts.createScanner(2, true); - var disallowInAndDecoratorContext = 1 | 4; + var disallowInAndDecoratorContext = 4194304 | 16777216; + var NodeConstructor; + var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; @@ -6578,14 +6185,20 @@ var ts; var parsingContext; var contextFlags; var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) { - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); - var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes, scriptKind) { + scriptKind = scriptKind ? scriptKind : getScriptKindFromFileName(fileName); + initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); return result; } Parser.parseSourceFile = parseSourceFile; - function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) { + function getLanguageVariant(scriptKind) { + return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 ? 1 : 0; + } + function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; @@ -6593,12 +6206,12 @@ var ts; identifiers = {}; identifierCount = 0; nodeCount = 0; - contextFlags = ts.isJavaScript(fileName) ? 32 : 0; + contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(ts.isTsx(fileName) ? 1 : 0); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); } function clearState() { scanner.setText(""); @@ -6609,8 +6222,9 @@ var ts; syntaxCursor = undefined; sourceText = undefined; } - function parseSourceFileWorker(fileName, languageVersion, setParentNodes) { - sourceFile = createSourceFile(fileName, languageVersion); + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + sourceFile.flags = contextFlags; token = nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); @@ -6624,35 +6238,22 @@ var ts; if (setParentNodes) { fixupParentReferences(sourceFile); } - if (ts.isJavaScript(fileName)) { - addJSDocComments(); - } return sourceFile; } - function addJSDocComments() { - forEachChild(sourceFile, visit); - return; - function visit(node) { - switch (node.kind) { - case 193: - case 213: - case 138: - addJSDocComment(node); - } - forEachChild(node, visit); - } - } function addJSDocComment(node) { - var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); - if (comments) { - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var comment = comments_1[_i]; - var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDocComment) { - node.jsDocComment = jsDocComment; + if (contextFlags & 134217728) { + var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); + if (comments) { + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (jsDocComment) { + node.jsDocComment = jsDocComment; + } } } } + return node; } function fixupParentReferences(sourceFile) { var parent = sourceFile; @@ -6669,16 +6270,16 @@ var ts; } } Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion) { - var sourceFile = createNode(248, 0); - sourceFile.pos = 0; - sourceFile.end = sourceText.length; + function createSourceFile(fileName, languageVersion, scriptKind) { + var sourceFile = new SourceFileConstructor(252, 0, sourceText.length); + nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 : 0; - sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 : 0; + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.scriptKind = scriptKind; return sourceFile; } function setContextFlag(val, flag) { @@ -6690,16 +6291,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 1); + setContextFlag(val, 4194304); } function setYieldContext(val) { - setContextFlag(val, 2); + setContextFlag(val, 8388608); } function setDecoratorContext(val) { - setContextFlag(val, 4); + setContextFlag(val, 16777216); } function setAwaitContext(val) { - setContextFlag(val, 8); + setContextFlag(val, 33554432); } function doOutsideOfContext(context, func) { var contextFlagsToClear = context & contextFlags; @@ -6722,46 +6323,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(1, func); + return doOutsideOfContext(4194304, func); } function disallowInAnd(func) { - return doInsideOfContext(1, func); + return doInsideOfContext(4194304, func); } function doInYieldContext(func) { - return doInsideOfContext(2, func); - } - function doOutsideOfYieldContext(func) { - return doOutsideOfContext(2, func); + return doInsideOfContext(8388608, func); } function doInDecoratorContext(func) { - return doInsideOfContext(4, func); + return doInsideOfContext(16777216, func); } function doInAwaitContext(func) { - return doInsideOfContext(8, func); + return doInsideOfContext(33554432, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(8, func); + return doOutsideOfContext(33554432, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(2 | 8, func); - } - function doOutsideOfYieldAndAwaitContext(func) { - return doOutsideOfContext(2 | 8, func); + return doInsideOfContext(8388608 | 33554432, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(2); + return inContext(8388608); } function inDisallowInContext() { - return inContext(1); + return inContext(4194304); } function inDecoratorContext() { - return inContext(4); + return inContext(16777216); } function inAwaitContext() { - return inContext(8); + return inContext(33554432); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -6788,9 +6383,6 @@ var ts; function nextToken() { return token = scanner.scan(); } - function getTokenPos(pos) { - return ts.skipTrivia(sourceText, pos); - } function reScanGreaterToken() { return token = scanner.reScanGreaterToken(); } @@ -6900,16 +6492,16 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return new (nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)))(pos, pos); + return new NodeConstructor(kind, pos, pos); } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; if (contextFlags) { - node.parserContextFlags = contextFlags; + node.flags |= contextFlags; } if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.parserContextFlags |= 16; + node.flags |= 67108864; } return node; } @@ -6971,7 +6563,7 @@ var ts; return token === 9 || token === 8 || ts.tokenIsIdentifierOrKeyword(token); } function parseComputedPropertyName() { - var node = createNode(136); + var node = createNode(138); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); @@ -6980,6 +6572,13 @@ var ts; function parseContextualModifier(t) { return token === t && tryParse(nextTokenCanFollowModifier); } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } function nextTokenCanFollowModifier() { if (token === 74) { return nextToken() === 81; @@ -6998,14 +6597,10 @@ var ts; nextToken(); return canFollowModifier(); } - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); + return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifier(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { return token === 19 @@ -7030,7 +6625,7 @@ var ts; case 2: return token === 71 || token === 77; case 4: - return isStartOfTypeMember(); + return lookAhead(isTypeMemberStart); case 5: return lookAhead(isClassMemberStart) || (token === 23 && !inErrorRecovery); case 6: @@ -7038,7 +6633,7 @@ var ts; case 12: return token === 19 || token === 37 || isLiteralPropertyName(); case 9: - return isLiteralPropertyName(); + return token === 19 || isLiteralPropertyName(); case 7: if (token === 15) { return lookAhead(isValidHeritageClauseObjectLiteral); @@ -7220,7 +6815,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.parserContextFlags & 31; + var nodeContextFlags = node.flags & 62914560; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -7267,14 +6862,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 144: - case 149: - case 145: case 146: - case 141: - case 191: - return true; + case 151: + case 147: + case 148: case 143: + case 195: + return true; + case 145: var methodDeclaration = node; var nameIsConstructor = methodDeclaration.name.kind === 69 && methodDeclaration.name.originalKeywordKind === 121; @@ -7286,8 +6881,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 241: - case 242: + case 245: + case 246: return true; } } @@ -7296,65 +6891,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 213: - case 193: - case 192: + case 217: + case 197: case 196: - case 195: + case 200: + case 199: + case 212: case 208: - case 204: + case 210: + case 207: case 206: + case 204: + case 205: case 203: case 202: - case 200: - case 201: - case 199: - case 198: - case 205: - case 194: case 209: - case 207: - case 197: - case 210: - case 222: - case 221: - case 228: - case 227: - case 218: + case 198: + case 213: + case 211: + case 201: case 214: - case 215: - case 217: - case 216: + case 226: + case 225: + case 232: + case 231: + case 222: + case 218: + case 219: + case 221: + case 220: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 247; + return node.kind === 251; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 148: + case 150: + case 144: + case 151: case 142: case 149: - case 140: - case 147: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 211) { + if (node.kind !== 215) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 138) { + if (node.kind !== 140) { return false; } var parameter = node; @@ -7399,7 +6994,7 @@ var ts; } } ; - function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimeter) { + function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; @@ -7417,7 +7012,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimeter && token === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -7454,7 +7049,7 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); while (parseOptional(21)) { - var node = createNode(135, entity.pos); + var node = createNode(137, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -7471,8 +7066,8 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(183); - template.head = parseLiteralNode(); + var template = createNode(187); + template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); var templateSpans = []; templateSpans.pos = getNodePos(); @@ -7484,12 +7079,12 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(190); + var span = createNode(194); span.expression = allowInAnd(parseExpression); var literal; if (token === 16) { reScanTemplateToken(); - literal = parseLiteralNode(); + literal = parseTemplateLiteralFragment(); } else { literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); @@ -7497,8 +7092,17 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(164, true); + } function parseLiteralNode(internName) { - var node = createNode(token); + return parseLiteralLikeNode(token, internName); + } + function parseTemplateLiteralFragment() { + return parseLiteralLikeNode(token, false); + } + function parseLiteralLikeNode(kind, internName) { + var node = createNode(kind); var text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -7513,34 +7117,39 @@ var ts; if (node.kind === 8 && sourceText.charCodeAt(tokenPos) === 48 && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - node.flags |= 32768; + node.isOctalLiteral = true; } return node; } - function parseTypeReferenceOrTypePredicate() { + function parseTypeReference() { var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); - if (typeName.kind === 69 && token === 124 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var node_1 = createNode(150, typeName.pos); - node_1.parameterName = typeName; - node_1.type = parseType(); - return finishNode(node_1); - } - var node = createNode(151, typeName.pos); + var node = createNode(153, typeName.pos); node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(152, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(163); + nextToken(); + return finishNode(node); + } function parseTypeQuery() { - var node = createNode(154); + var node = createNode(156); parseExpected(101); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(137); + var node = createNode(139); node.name = parseIdentifier(); if (parseOptional(83)) { if (isStartOfType() || !isStartOfExpression()) { @@ -7559,14 +7168,12 @@ var ts; } function parseParameterType() { if (parseOptional(54)) { - return token === 9 - ? parseLiteralNode(true) - : parseType(); + return parseType(); } return undefined; } function isStartOfParameter() { - return token === 22 || isIdentifierOrPattern() || ts.isModifier(token) || token === 55; + return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55; } function setModifiers(node, modifiers) { if (modifiers) { @@ -7575,18 +7182,18 @@ var ts; } } function parseParameter() { - var node = createNode(138); + var node = createNode(140); node.decorators = parseDecorators(); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifier(token)) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { nextToken(); } node.questionToken = parseOptionalToken(53); node.type = parseParameterType(); node.initializer = parseBindingElementInitializer(true); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseBindingElementInitializer(inParameter) { return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); @@ -7600,10 +7207,10 @@ var ts; signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); if (returnTokenRequired) { parseExpected(returnToken); - signature.type = parseType(); + signature.type = parseTypeOrTypePredicate(); } else if (parseOptional(returnToken)) { - signature.type = parseType(); + signature.type = parseTypeOrTypePredicate(); } } function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { @@ -7630,7 +7237,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 148) { + if (kind === 150) { parseExpected(92); } fillSignature(54, false, false, false, node); @@ -7648,7 +7255,7 @@ var ts; if (token === 22 || token === 20) { return true; } - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -7670,7 +7277,7 @@ var ts; return token === 54 || token === 24 || token === 20; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(149, fullStart); + var node = createNode(151, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.parameters = parseBracketedList(16, parseParameter, 19, 20); @@ -7678,12 +7285,12 @@ var ts; parseTypeMemberSemicolon(); return finishNode(node); } - function parsePropertyOrMethodSignature() { - var fullStart = scanner.getStartPos(); + function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53); if (token === 17 || token === 25) { - var method = createNode(142, fullStart); + var method = createNode(144, fullStart); + setModifiers(method, modifiers); method.name = name; method.questionToken = questionToken; fillSignature(54, false, false, false, method); @@ -7691,86 +7298,63 @@ var ts; return finishNode(method); } else { - var property = createNode(140, fullStart); + var property = createNode(142, fullStart); + setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); + if (token === 56) { + property.initializer = parseNonParameterInitializer(); + } parseTypeMemberSemicolon(); return finishNode(property); } } - function isStartOfTypeMember() { - switch (token) { - case 17: - case 25: - case 19: - return true; - default: - if (ts.isModifier(token)) { - var result = lookAhead(isStartOfIndexSignatureDeclaration); - if (result) { - return result; - } - } - return isLiteralPropertyName() && lookAhead(isTypeMemberWithLiteralPropertyName); + function isTypeMemberStart() { + var idToken; + if (token === 17 || token === 25) { + return true; } - } - function isStartOfIndexSignatureDeclaration() { - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { + idToken = token; nextToken(); } - return isIndexSignature(); - } - function isTypeMemberWithLiteralPropertyName() { - nextToken(); - return token === 17 || - token === 25 || - token === 53 || - token === 54 || - canParseSemicolon(); + if (token === 19) { + return true; + } + if (isLiteralPropertyName()) { + idToken = token; + nextToken(); + } + if (idToken) { + return token === 17 || + token === 25 || + token === 53 || + token === 54 || + canParseSemicolon(); + } + return false; } function parseTypeMember() { - switch (token) { - case 17: - case 25: - return parseSignatureMember(147); - case 19: - return isIndexSignature() - ? parseIndexSignatureDeclaration(scanner.getStartPos(), undefined, undefined) - : parsePropertyOrMethodSignature(); - case 92: - if (lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(148); - } - case 9: - case 8: - return parsePropertyOrMethodSignature(); - default: - if (ts.isModifier(token)) { - var result = tryParse(parseIndexSignatureWithModifiers); - if (result) { - return result; - } - } - if (ts.tokenIsIdentifierOrKeyword(token)) { - return parsePropertyOrMethodSignature(); - } + if (token === 17 || token === 25) { + return parseSignatureMember(149); } - } - function parseIndexSignatureWithModifiers() { - var fullStart = scanner.getStartPos(); - var decorators = parseDecorators(); + if (token === 92 && lookAhead(isStartOfConstructSignature)) { + return parseSignatureMember(150); + } + var fullStart = getNodePos(); var modifiers = parseModifiers(); - return isIndexSignature() - ? parseIndexSignatureDeclaration(fullStart, decorators, modifiers) - : undefined; + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); + } + return parsePropertyOrMethodSignature(fullStart, modifiers); } function isStartOfConstructSignature() { nextToken(); return token === 17 || token === 25; } function parseTypeLiteral() { - var node = createNode(155); + var node = createNode(157); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -7786,12 +7370,12 @@ var ts; return members; } function parseTupleType() { - var node = createNode(157); + var node = createNode(159); node.elementTypes = parseBracketedList(19, parseType, 19, 20); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(160); + var node = createNode(162); parseExpected(17); node.type = parseType(); parseExpected(18); @@ -7799,7 +7383,7 @@ var ts; } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 153) { + if (kind === 155) { parseExpected(92); } fillSignature(34, false, false, false, node); @@ -7812,15 +7396,25 @@ var ts; function parseNonArrayType() { switch (token) { case 117: - case 130: - case 128: - case 120: case 131: + case 129: + case 120: + case 132: var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReferenceOrTypePredicate(); + return node || parseTypeReference(); + case 9: + return parseStringLiteralTypeNode(); case 103: - case 97: return parseTokenNode(); + case 97: { + var thisKeyword = parseThisTypeNode(); + if (token === 124 && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } case 101: return parseTypeQuery(); case 15: @@ -7830,16 +7424,16 @@ var ts; case 17: return parseParenthesizedType(); default: - return parseTypeReferenceOrTypePredicate(); + return parseTypeReference(); } } function isStartOfType() { switch (token) { case 117: - case 130: - case 128: - case 120: case 131: + case 129: + case 120: + case 132: case 103: case 97: case 101: @@ -7847,6 +7441,7 @@ var ts; case 19: case 25: case 92: + case 9: return true; case 17: return lookAhead(isStartOfParenthesizedOrFunctionType); @@ -7862,7 +7457,7 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(19)) { parseExpected(20); - var node = createNode(156, type.pos); + var node = createNode(158, type.pos); node.elementType = type; type = finishNode(node); } @@ -7884,10 +7479,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(159, parseArrayTypeOrHigher, 46); + return parseUnionOrIntersectionType(161, parseArrayTypeOrHigher, 46); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(158, parseIntersectionTypeOrHigher, 47); + return parseUnionOrIntersectionType(160, parseIntersectionTypeOrHigher, 47); } function isStartOfFunctionType() { if (token === 25) { @@ -7895,16 +7490,29 @@ var ts; } return token === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); } + function skipParameterStart() { + if (ts.isModifierKind(token)) { + parseModifiers(); + } + if (isIdentifier()) { + nextToken(); + return true; + } + if (token === 19 || token === 15) { + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } function isUnambiguouslyStartOfFunctionType() { nextToken(); if (token === 18 || token === 22) { return true; } - if (isIdentifier() || ts.isModifier(token)) { - nextToken(); + if (skipParameterStart()) { if (token === 54 || token === 24 || - token === 53 || token === 56 || - isIdentifier() || ts.isModifier(token)) { + token === 53 || token === 56) { return true; } if (token === 18) { @@ -7916,15 +7524,35 @@ var ts; } return false; } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(152, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token === 124 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } function parseType() { - return doOutsideOfContext(10, parseTypeWorker); + return doOutsideOfContext(41943040, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(152); + return parseFunctionOrConstructorType(154); } if (token === 92) { - return parseFunctionOrConstructorType(153); + return parseFunctionOrConstructorType(155); } return parseUnionTypeOrHigher(); } @@ -7988,9 +7616,6 @@ var ts; token !== 55 && isStartOfExpression(); } - function allowInAndParseExpression() { - return allowInAnd(parseExpression); - } function parseExpression() { var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { @@ -8046,7 +7671,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(184); + var node = createNode(188); nextToken(); if (!scanner.hasPrecedingLineBreak() && (token === 37 || isStartOfExpression())) { @@ -8060,8 +7685,8 @@ var ts; } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(174, identifier.pos); - var parameter = createNode(138, identifier.pos); + var node = createNode(178, identifier.pos); + var parameter = createNode(140, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = [parameter]; @@ -8172,7 +7797,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(174); + var node = createNode(178); setModifiers(node, parseModifiersForArrowFunction()); var isAsync = !!(node.flags & 256); fillSignature(54, false, isAsync, !allowAmbiguity, node); @@ -8204,7 +7829,7 @@ var ts; if (!questionToken) { return leftOperand; } - var node = createNode(182, leftOperand.pos); + var node = createNode(186, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -8217,7 +7842,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 90 || t === 134; + return t === 90 || t === 136; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -8295,39 +7920,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(181, left.pos); + var node = createNode(185, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(189, left.pos); + var node = createNode(193, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(179); + var node = createNode(183); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(175); + var node = createNode(179); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(176); + var node = createNode(180); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(177); + var node = createNode(181); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -8342,7 +7967,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(178); + var node = createNode(182); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -8360,9 +7985,8 @@ var ts; var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === 38) { - var diagnostic; var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 171) { + if (simpleUnaryExpression.kind === 175) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -8410,7 +8034,7 @@ var ts; } function parseIncrementExpression() { if (token === 41 || token === 42) { - var node = createNode(179); + var node = createNode(183); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -8422,7 +8046,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 41 || token === 42) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(180, expression.pos); + var node = createNode(184, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -8445,31 +8069,44 @@ var ts; if (token === 17 || token === 21 || token === 19) { return expression; } - var node = createNode(166, expression.pos); + var node = createNode(170, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 69) { + return lhs.text === rhs.text; + } + return lhs.right.text === rhs.right.text && + tagNamesAreEquivalent(lhs.left, rhs.left); + } function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 235) { - var node = createNode(233, opening.pos); + if (opening.kind === 239) { + var node = createNode(237, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 234); + ts.Debug.assert(opening.kind === 238); result = opening; } if (inExpressionContext && token === 25) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(181, result.pos); + var badNode = createNode(185, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -8481,13 +8118,13 @@ var ts; return result; } function parseJsxText() { - var node = createNode(236, scanner.getStartPos()); + var node = createNode(240, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token) { - case 236: + case 240: return parseJsxText(); case 15: return parseJsxExpression(false); @@ -8507,7 +8144,7 @@ var ts; break; } else if (token === 1) { - parseErrorAtCurrentToken(ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } result.push(parseJsxChild()); @@ -8523,7 +8160,7 @@ var ts; var attributes = parseList(13, parseJsxAttribute); var node; if (token === 27) { - node = createNode(235, fullStart); + node = createNode(239, fullStart); scanJsxText(); } else { @@ -8535,7 +8172,7 @@ var ts; parseExpected(27, undefined, false); scanJsxText(); } - node = createNode(234, fullStart); + node = createNode(238, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -8546,7 +8183,7 @@ var ts; var elementName = parseIdentifierName(); while (parseOptional(21)) { scanJsxIdentifier(); - var node = createNode(135, elementName.pos); + var node = createNode(137, elementName.pos); node.left = elementName; node.right = parseIdentifierName(); elementName = finishNode(node); @@ -8554,10 +8191,10 @@ var ts; return elementName; } function parseJsxExpression(inExpressionContext) { - var node = createNode(240); + var node = createNode(244); parseExpected(15); if (token !== 16) { - node.expression = parseExpression(); + node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { parseExpected(16); @@ -8573,7 +8210,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(238); + var node = createNode(242); node.name = parseIdentifierName(); if (parseOptional(56)) { switch (token) { @@ -8588,7 +8225,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(239); + var node = createNode(243); parseExpected(15); parseExpected(22); node.expression = parseExpression(); @@ -8596,7 +8233,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(237); + var node = createNode(241); parseExpected(26); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -8609,7 +8246,7 @@ var ts; return finishNode(node); } function parseTypeAssertion() { - var node = createNode(171); + var node = createNode(175); parseExpected(25); node.type = parseType(); parseExpected(27); @@ -8620,7 +8257,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(21); if (dotToken) { - var propertyAccess = createNode(166, expression.pos); + var propertyAccess = createNode(170, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); @@ -8628,7 +8265,7 @@ var ts; continue; } if (!inDecoratorContext() && parseOptional(19)) { - var indexedAccess = createNode(167, expression.pos); + var indexedAccess = createNode(171, expression.pos); indexedAccess.expression = expression; if (token !== 20) { indexedAccess.argumentExpression = allowInAnd(parseExpression); @@ -8642,7 +8279,7 @@ var ts; continue; } if (token === 11 || token === 12) { - var tagExpression = createNode(170, expression.pos); + var tagExpression = createNode(174, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 11 ? parseLiteralNode() @@ -8661,7 +8298,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(168, expression.pos); + var callExpr = createNode(172, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -8669,7 +8306,7 @@ var ts; continue; } else if (token === 17) { - var callExpr = createNode(168, expression.pos); + var callExpr = createNode(172, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -8764,41 +8401,42 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(172); + var node = createNode(176); parseExpected(17); node.expression = allowInAnd(parseExpression); parseExpected(18); return finishNode(node); } function parseSpreadElement() { - var node = createNode(185); + var node = createNode(189); parseExpected(22); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 22 ? parseSpreadElement() : - token === 24 ? createNode(187) : + token === 24 ? createNode(191) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(164); + var node = createNode(168); parseExpected(19); - if (scanner.hasPrecedingLineBreak()) - node.flags |= 1024; + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); parseExpected(20); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(123)) { - return parseAccessorDeclaration(145, fullStart, decorators, modifiers); + return parseAccessorDeclaration(147, fullStart, decorators, modifiers); } - else if (parseContextualModifier(129)) { - return parseAccessorDeclaration(146, fullStart, decorators, modifiers); + else if (parseContextualModifier(130)) { + return parseAccessorDeclaration(148, fullStart, decorators, modifiers); } return undefined; } @@ -8812,7 +8450,6 @@ var ts; } var asteriskToken = parseOptionalToken(37); var tokenIsIdentifier = isIdentifier(); - var nameToken = token; var propertyName = parsePropertyName(); var questionToken = parseOptionalToken(53); if (asteriskToken || token === 17 || token === 25) { @@ -8820,7 +8457,7 @@ var ts; } var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 || token === 16 || token === 56); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(246, fullStart); + var shorthandDeclaration = createNode(250, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; var equalsToken = parseOptionalToken(56); @@ -8828,22 +8465,23 @@ var ts; shorthandDeclaration.equalsToken = equalsToken; shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return finishNode(shorthandDeclaration); + return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(245, fullStart); + var propertyAssignment = createNode(249, fullStart); + propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(54); propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return finishNode(propertyAssignment); + return addJSDocComment(finishNode(propertyAssignment)); } } function parseObjectLiteralExpression() { - var node = createNode(165); + var node = createNode(169); parseExpected(15); if (scanner.hasPrecedingLineBreak()) { - node.flags |= 1024; + node.multiLine = true; } node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); parseExpected(16); @@ -8854,7 +8492,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(173); + var node = createNode(177); setModifiers(node, parseModifiers()); parseExpected(87); node.asteriskToken = parseOptionalToken(37); @@ -8870,13 +8508,13 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(true); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(169); + var node = createNode(173); parseExpected(92); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -8886,7 +8524,7 @@ var ts; return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(192); + var node = createNode(196); if (parseExpected(15, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(1, parseStatement); parseExpected(16); @@ -8914,12 +8552,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(194); + var node = createNode(198); parseExpected(23); return finishNode(node); } function parseIfStatement() { - var node = createNode(196); + var node = createNode(200); parseExpected(88); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -8929,7 +8567,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(197); + var node = createNode(201); parseExpected(79); node.statement = parseStatement(); parseExpected(104); @@ -8940,7 +8578,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(198); + var node = createNode(202); parseExpected(104); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -8963,21 +8601,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(90)) { - var forInStatement = createNode(200, pos); + var forInStatement = createNode(204, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(18); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(134)) { - var forOfStatement = createNode(201, pos); + else if (parseOptional(136)) { + var forOfStatement = createNode(205, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(18); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(199, pos); + var forStatement = createNode(203, pos); forStatement.initializer = initializer; parseExpected(23); if (token !== 23 && token !== 18) { @@ -8995,7 +8633,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 203 ? 70 : 75); + parseExpected(kind === 207 ? 70 : 75); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -9003,7 +8641,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(204); + var node = createNode(208); parseExpected(94); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -9012,7 +8650,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(205); + var node = createNode(209); parseExpected(105); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -9021,7 +8659,7 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(241); + var node = createNode(245); parseExpected(71); node.expression = allowInAnd(parseExpression); parseExpected(54); @@ -9029,7 +8667,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(242); + var node = createNode(246); parseExpected(77); parseExpected(54); node.statements = parseList(3, parseStatement); @@ -9039,12 +8677,12 @@ var ts; return token === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(206); + var node = createNode(210); parseExpected(96); parseExpected(17); node.expression = allowInAnd(parseExpression); parseExpected(18); - var caseBlock = createNode(220, scanner.getStartPos()); + var caseBlock = createNode(224, scanner.getStartPos()); parseExpected(15); caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); parseExpected(16); @@ -9052,14 +8690,14 @@ var ts; return finishNode(node); } function parseThrowStatement() { - var node = createNode(208); + var node = createNode(212); parseExpected(98); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(209); + var node = createNode(213); parseExpected(100); node.tryBlock = parseBlock(false); node.catchClause = token === 72 ? parseCatchClause() : undefined; @@ -9070,7 +8708,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(244); + var result = createNode(248); parseExpected(72); if (parseExpected(17)) { result.variableDeclaration = parseVariableDeclaration(); @@ -9080,7 +8718,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(210); + var node = createNode(214); parseExpected(76); parseSemicolon(); return finishNode(node); @@ -9089,16 +8727,16 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 69 && parseOptional(54)) { - var labeledStatement = createNode(207, fullStart); + var labeledStatement = createNode(211, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); - return finishNode(labeledStatement); + return addJSDocComment(finishNode(labeledStatement)); } else { - var expressionStatement = createNode(195, fullStart); + var expressionStatement = createNode(199, fullStart); expressionStatement.expression = expression; parseSemicolon(); - return finishNode(expressionStatement); + return addJSDocComment(finishNode(expressionStatement)); } } function nextTokenIsIdentifierOrKeywordOnSameLine() { @@ -9124,7 +8762,7 @@ var ts; case 81: return true; case 107: - case 132: + case 133: return nextTokenIsIdentifierOnSameLine(); case 125: case 126: @@ -9135,11 +8773,14 @@ var ts; case 110: case 111: case 112: + case 127: nextToken(); if (scanner.hasPrecedingLineBreak()) { return false; } continue; + case 135: + return nextToken() === 15; case 89: nextToken(); return token === 9 || token === 37 || @@ -9196,12 +8837,14 @@ var ts; case 107: case 125: case 126: - case 132: + case 133: + case 135: return true; case 112: case 110: case 111: case 113: + case 127: return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); default: return isStartOfExpression(); @@ -9240,9 +8883,9 @@ var ts; case 86: return parseForOrForInOrForOfStatement(); case 75: - return parseBreakOrContinueStatement(202); + return parseBreakOrContinueStatement(206); case 70: - return parseBreakOrContinueStatement(203); + return parseBreakOrContinueStatement(207); case 94: return parseReturnStatement(); case 105: @@ -9261,7 +8904,7 @@ var ts; return parseDeclaration(); case 118: case 107: - case 132: + case 133: case 125: case 126: case 122: @@ -9274,6 +8917,8 @@ var ts; case 112: case 115: case 113: + case 127: + case 135: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -9296,10 +8941,11 @@ var ts; return parseClassDeclaration(fullStart, decorators, modifiers); case 107: return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 132: + case 133: return parseTypeAliasDeclaration(fullStart, decorators, modifiers); case 81: return parseEnumDeclaration(fullStart, decorators, modifiers); + case 135: case 125: case 126: return parseModuleDeclaration(fullStart, decorators, modifiers); @@ -9312,7 +8958,7 @@ var ts; parseExportDeclaration(fullStart, decorators, modifiers); default: if (decorators || modifiers) { - var node = createMissingNode(231, true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(235, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -9333,16 +8979,16 @@ var ts; } function parseArrayBindingElement() { if (token === 24) { - return createNode(187); + return createNode(191); } - var node = createNode(163); + var node = createNode(167); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(163); + var node = createNode(167); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 54) { @@ -9357,14 +9003,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(161); + var node = createNode(165); parseExpected(15); node.elements = parseDelimitedList(9, parseObjectBindingElement); parseExpected(16); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(162); + var node = createNode(166); parseExpected(19); node.elements = parseDelimitedList(10, parseArrayBindingElement); parseExpected(20); @@ -9383,7 +9029,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(211); + var node = createNode(215); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -9392,21 +9038,21 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(212); + var node = createNode(216); switch (token) { case 102: break; case 108: - node.flags |= 8192; + node.flags |= 1024; break; case 74: - node.flags |= 16384; + node.flags |= 2048; break; default: ts.Debug.fail(); } nextToken(); - if (token === 134 && lookAhead(canFollowContextualOfKeyword)) { + if (token === 136 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -9421,15 +9067,15 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 18; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(193, fullStart); + var node = createNode(197, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(213, fullStart); + var node = createNode(217, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(87); @@ -9439,19 +9085,19 @@ var ts; var isAsync = !!(node.flags & 256); fillSignature(54, isGenerator, isAsync, false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(144, pos); + var node = createNode(146, pos); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(121); fillSignature(54, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(143, fullStart); + var method = createNode(145, fullStart); method.decorators = decorators; setModifiers(method, modifiers); method.asteriskToken = asteriskToken; @@ -9461,18 +9107,18 @@ var ts; var isAsync = !!(method.flags & 256); fillSignature(54, isGenerator, isAsync, false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); - return finishNode(method); + return addJSDocComment(finishNode(method)); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(141, fullStart); + var property = createNode(143, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = modifiers && modifiers.flags & 64 + property.initializer = modifiers && modifiers.flags & 32 ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(2 | 1, parseNonParameterInitializer); + : doOutsideOfContext(8388608 | 4194304, parseNonParameterInitializer); parseSemicolon(); return finishNode(property); } @@ -9505,6 +9151,7 @@ var ts; case 110: case 111: case 113: + case 127: return true; default: return false; @@ -9515,7 +9162,7 @@ var ts; if (token === 55) { return true; } - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { idToken = token; if (isClassMemberModifier(idToken)) { return true; @@ -9533,7 +9180,7 @@ var ts; return true; } if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 129 || idToken === 123) { + if (!ts.isKeyword(idToken) || idToken === 130 || idToken === 123) { return true; } switch (token) { @@ -9558,9 +9205,9 @@ var ts; } if (!decorators) { decorators = []; - decorators.pos = scanner.getStartPos(); + decorators.pos = decoratorStart; } - var decorator = createNode(139, decoratorStart); + var decorator = createNode(141, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -9569,14 +9216,21 @@ var ts; } return decorators; } - function parseModifiers() { + function parseModifiers(permitInvalidConstAsModifier) { var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token; - if (!parseAnyContextualModifier()) { - break; + if (token === 74 && permitInvalidConstAsModifier) { + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } } if (!modifiers) { modifiers = []; @@ -9609,13 +9263,13 @@ var ts; } function parseClassElement() { if (token === 23) { - var result = createNode(191); + var result = createNode(195); nextToken(); return finishNode(result); } var fullStart = getNodePos(); var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var modifiers = parseModifiers(true); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; @@ -9640,10 +9294,10 @@ var ts; ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 186); + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 190); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 214); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 218); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); @@ -9676,12 +9330,9 @@ var ts; } return undefined; } - function parseHeritageClausesWorker() { - return parseList(20, parseHeritageClause); - } function parseHeritageClause() { if (token === 83 || token === 106) { - var node = createNode(243); + var node = createNode(247); node.token = token; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); @@ -9690,7 +9341,7 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(188); + var node = createNode(192); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); @@ -9704,7 +9355,7 @@ var ts; return parseList(5, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(215, fullStart); + var node = createNode(219, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(107); @@ -9715,10 +9366,10 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216, fullStart); + var node = createNode(220, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - parseExpected(132); + parseExpected(133); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); parseExpected(56); @@ -9727,13 +9378,13 @@ var ts; return finishNode(node); } function parseEnumMember() { - var node = createNode(247, scanner.getStartPos()); + var node = createNode(251, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(217, fullStart); + var node = createNode(221, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(81); @@ -9748,7 +9399,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(219, scanner.getStartPos()); + var node = createNode(223, scanner.getStartPos()); if (parseExpected(15)) { node.statements = parseList(1, parseStatement); parseExpected(16); @@ -9759,29 +9410,38 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(218, fullStart); - var namespaceFlag = flags & 65536; + var node = createNode(222, fullStart); + var namespaceFlag = flags & 4096; node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 2 | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 1 | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(218, fullStart); + var node = createNode(222, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.name = parseLiteralNode(true); + if (token === 135) { + node.name = parseIdentifier(); + node.flags |= 131072; + } + else { + node.name = parseLiteralNode(true); + } node.body = parseModuleBlock(); return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (parseOptional(126)) { - flags |= 65536; + if (token === 135) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(126)) { + flags |= 4096; } else { parseExpected(125); @@ -9792,7 +9452,7 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 127 && + return token === 128 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -9801,19 +9461,14 @@ var ts; function nextTokenIsSlash() { return nextToken() === 39; } - function nextTokenIsCommaOrFromKeyword() { - nextToken(); - return token === 24 || - token === 133; - } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(89); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 24 && token !== 133) { - var importEqualsDeclaration = createNode(221, fullStart); + if (token !== 24 && token !== 134) { + var importEqualsDeclaration = createNode(225, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -9823,27 +9478,27 @@ var ts; return finishNode(importEqualsDeclaration); } } - var importDeclaration = createNode(222, fullStart); + var importDeclaration = createNode(226, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || token === 37 || token === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(133); + parseExpected(134); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(importDeclaration); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(223, fullStart); + var importClause = createNode(227, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || parseOptional(24)) { - importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(225); + importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(229); } return finishNode(importClause); } @@ -9853,22 +9508,25 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(232); - parseExpected(127); + var node = createNode(236); + parseExpected(128); parseExpected(17); node.expression = parseModuleSpecifier(); parseExpected(18); return finishNode(node); } function parseModuleSpecifier() { - var result = parseExpression(); - if (result.kind === 9) { + if (token === 9) { + var result = parseLiteralNode(); internIdentifier(result.text); + return result; + } + else { + return parseExpression(); } - return result; } function parseNamespaceImport() { - var namespaceImport = createNode(224); + var namespaceImport = createNode(228); parseExpected(37); parseExpected(116); namespaceImport.name = parseIdentifier(); @@ -9876,14 +9534,14 @@ var ts; } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(21, kind === 225 ? parseImportSpecifier : parseExportSpecifier, 15, 16); + node.elements = parseBracketedList(21, kind === 229 ? parseImportSpecifier : parseExportSpecifier, 15, 16); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(230); + return parseImportOrExportSpecifier(234); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(226); + return parseImportOrExportSpecifier(230); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -9902,23 +9560,23 @@ var ts; else { node.name = identifierName; } - if (kind === 226 && checkIdentifierIsKeyword) { + if (kind === 230 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); + var node = createNode(232, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(37)) { - parseExpected(133); + parseExpected(134); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(229); - if (token === 133 || (token === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(133); + node.exportClause = parseNamedImportsOrExports(233); + if (token === 134 || (token === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(134); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -9926,7 +9584,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(227, fullStart); + var node = createNode(231, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(56)) { @@ -9946,11 +9604,13 @@ var ts; var amdModuleName; while (true) { var kind = triviaScanner.scan(); - if (kind === 5 || kind === 4 || kind === 3) { - continue; - } if (kind !== 2) { - break; + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } } var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; var comment = sourceText.substring(range.pos, range.end); @@ -9995,11 +9655,11 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 2 - || node.kind === 221 && node.moduleReference.kind === 232 - || node.kind === 222 - || node.kind === 227 - || node.kind === 228 + return node.flags & 1 + || node.kind === 225 && node.moduleReference.kind === 236 + || node.kind === 226 + || node.kind === 231 + || node.kind === 232 ? node : undefined; }); @@ -10024,17 +9684,17 @@ var ts; } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState("file.js", content, 2, undefined); - var jsDocTypeExpression = parseJSDocTypeExpression(start, length); + initializeState("file.js", content, 2, undefined, 1); + scanner.setText(content, start, length); + token = scanner.scan(); + var jsDocTypeExpression = parseJSDocTypeExpression(); 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(249); + function parseJSDocTypeExpression() { + var result = createNode(253, scanner.getTokenPos()); parseExpected(15); result.type = parseJSDocTopLevelType(); parseExpected(16); @@ -10045,12 +9705,12 @@ var ts; function parseJSDocTopLevelType() { var type = parseJSDocType(); if (token === 47) { - var unionType = createNode(253, type.pos); + var unionType = createNode(257, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === 56) { - var optionalType = createNode(260, type.pos); + var optionalType = createNode(264, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -10061,20 +9721,20 @@ var ts; var type = parseBasicTypeExpression(); while (true) { if (token === 19) { - var arrayType = createNode(252, type.pos); + var arrayType = createNode(256, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20); type = finishNode(arrayType); } else if (token === 53) { - var nullableType = createNode(255, type.pos); + var nullableType = createNode(259, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } else if (token === 49) { - var nonNullableType = createNode(256, type.pos); + var nonNullableType = createNode(260, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -10108,37 +9768,37 @@ var ts; case 97: return parseJSDocThisType(); case 117: - case 130: - case 128: - case 120: case 131: + case 129: + case 120: + case 132: case 103: return parseTokenNode(); } return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(264); + var result = createNode(268); nextToken(); parseExpected(54); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(263); + var result = createNode(267); nextToken(); parseExpected(54); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(262); + var result = createNode(266); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(261); + var result = createNode(265); nextToken(); parseExpected(17); result.parameters = parseDelimitedList(22, parseJSDocParameter); @@ -10151,26 +9811,28 @@ var ts; return finishNode(result); } function parseJSDocParameter() { - var parameter = createNode(138); + var parameter = createNode(140); parameter.type = parseJSDocType(); + if (parseOptional(56)) { + parameter.questionToken = createNode(56); + } return finishNode(parameter); } - function parseJSDocOptionalType(type) { - var result = createNode(260, type.pos); - nextToken(); - result.type = type; - return finishNode(result); - } function parseJSDocTypeReference() { - var result = createNode(259); + var result = createNode(263); result.name = parseSimplePropertyName(); - while (parseOptional(21)) { - if (token === 25) { - result.typeArguments = parseTypeArguments(); - break; - } - else { - result.name = parseQualifiedName(result.name); + if (token === 25) { + result.typeArguments = parseTypeArguments(); + } + else { + while (parseOptional(21)) { + if (token === 25) { + result.typeArguments = parseTypeArguments(); + break; + } + else { + result.name = parseQualifiedName(result.name); + } } } return finishNode(result); @@ -10191,13 +9853,13 @@ var ts; } } function parseQualifiedName(left) { - var result = createNode(135, left.pos); + var result = createNode(137, left.pos); result.left = left; result.right = parseIdentifierName(); return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(257); + var result = createNode(261); nextToken(); result.members = parseDelimitedList(24, parseJSDocRecordMember); checkForTrailingComma(result.members); @@ -10205,7 +9867,7 @@ var ts; return finishNode(result); } function parseJSDocRecordMember() { - var result = createNode(258); + var result = createNode(262); result.name = parseSimplePropertyName(); if (token === 54) { nextToken(); @@ -10214,13 +9876,13 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(256); + var result = createNode(260); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(254); + var result = createNode(258); nextToken(); result.types = parseDelimitedList(25, parseJSDocType); checkForTrailingComma(result.types); @@ -10234,7 +9896,7 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(253); + var result = createNode(257); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); parseExpected(18); @@ -10252,7 +9914,7 @@ var ts; return types; } function parseJSDocAllType() { - var result = createNode(250); + var result = createNode(254); nextToken(); return finishNode(result); } @@ -10265,29 +9927,35 @@ var ts; token === 27 || token === 56 || token === 47) { - var result = createNode(251, pos); + var result = createNode(255, pos); return finishNode(result); } else { - var result = createNode(255, pos); + var result = createNode(259, pos); result.type = parseJSDocType(); return finishNode(result); } } function parseIsolatedJSDocComment(content, start, length) { - initializeState("file.js", content, 2, undefined); - var jsDocComment = parseJSDocComment(undefined, start, length); + initializeState("file.js", content, 2, undefined, 1); + sourceFile = { languageVariant: 0, text: content }; + var jsDocComment = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var saveToken = token; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { - fixupParentReferences(comment); comment.parent = parent; } + token = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; } JSDocParser.parseJSDocComment = parseJSDocComment; @@ -10300,60 +9968,64 @@ var ts; 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 result; + if (content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42) { + scanner.scanRange(start + 3, length - 5, function () { 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) { + nextJSDocToken(); + while (token !== 1) { + switch (token) { + case 55: + if (canParseTag) { + parseTag(); + } + seenAsterisk = false; + break; + case 4: + canParseTag = true; + seenAsterisk = false; + break; + case 37: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 69: canParseTag = false; - } - seenAsterisk = true; - continue; + break; + case 1: + break; } - canParseTag = false; + nextJSDocToken(); } - } + result = createJSDocComment(); + }); } - return createJSDocComment(); + return result; function createJSDocComment() { if (!tags) { return undefined; } - var result = createNode(265, start); + var result = createNode(269, start); result.tags = tags; return finishNode(result, end); } function skipWhitespace() { - while (pos < end && ts.isWhiteSpace(content.charCodeAt(pos))) { - pos++; + while (token === 5 || token === 4) { + nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(content.charCodeAt(pos - 1) === 64); - var atToken = createNode(55, pos - 1); - atToken.end = pos; - var tagName = scanIdentifier(); + ts.Debug.assert(token === 55); + var atToken = createNode(55, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifier(); if (!tagName) { return; } @@ -10377,10 +10049,10 @@ var ts; return undefined; } function handleUnknownTag(atToken, tagName) { - var result = createNode(266, atToken.pos); + var result = createNode(270, atToken.pos); result.atToken = atToken; result.tagName = tagName; - return finishNode(result, pos); + return finishNode(result); } function addTag(tag) { if (tag) { @@ -10393,12 +10065,10 @@ var ts; } } function tryParseTypeExpression() { - skipWhitespace(); - if (content.charCodeAt(pos) !== 123) { + if (token !== 15) { return undefined; } - var typeExpression = parseJSDocTypeExpression(pos, end - pos); - pos = typeExpression.end; + var typeExpression = parseJSDocTypeExpression(); return typeExpression; } function handleParamTag(atToken, tagName) { @@ -10406,17 +10076,20 @@ var ts; skipWhitespace(); var name; var isBracketed; - if (content.charCodeAt(pos) === 91) { - pos++; - skipWhitespace(); - name = scanIdentifier(); + if (parseOptionalToken(19)) { + name = parseJSDocIdentifier(); isBracketed = true; + if (parseOptionalToken(56)) { + parseExpression(); + } + parseExpected(20); } - else { - name = scanIdentifier(); + else if (token === 69) { + name = parseJSDocIdentifier(); } if (!name) { - parseErrorAtPosition(pos, 0, ts.Diagnostics.Identifier_expected); + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; } var preName, postName; if (typeExpression) { @@ -10428,84 +10101,81 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(267, atToken.pos); + var result = createNode(271, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; result.typeExpression = typeExpression; result.postParameterName = postName; result.isBracketed = isBracketed; - return finishNode(result, pos); + return finishNode(result); } function handleReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 268; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 272; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(268, atToken.pos); + var result = createNode(272, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); - return finishNode(result, pos); + return finishNode(result); } function handleTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 269; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 273; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(269, atToken.pos); + var result = createNode(273, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); - return finishNode(result, pos); + return finishNode(result); } function handleTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 270; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 274; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } var typeParameters = []; - typeParameters.pos = pos; + typeParameters.pos = scanner.getStartPos(); while (true) { - skipWhitespace(); - var startPos = pos; - var name_8 = scanIdentifier(); + var name_8 = parseJSDocIdentifier(); if (!name_8) { - parseErrorAtPosition(startPos, 0, ts.Diagnostics.Identifier_expected); + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(137, name_8.pos); + var typeParameter = createNode(139, name_8.pos); typeParameter.name = name_8; - finishNode(typeParameter, pos); + finishNode(typeParameter); typeParameters.push(typeParameter); - skipWhitespace(); - if (content.charCodeAt(pos) !== 44) { + if (token === 24) { + nextJSDocToken(); + } + else { break; } - pos++; } - typeParameters.end = pos; - var result = createNode(270, atToken.pos); + var result = createNode(274, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; - return finishNode(result, pos); + finishNode(result); + typeParameters.end = result.end; + return result; } - 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) { + function nextJSDocToken() { + return token = scanner.scanJSDocToken(); + } + function parseJSDocIdentifier() { + if (token !== 69) { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); return undefined; } - var result = createNode(69, startPos); - result.text = content.substring(startPos, pos); - return finishNode(result, pos); + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(69, pos); + result.text = content.substring(pos, end); + finishNode(result, end); + nextJSDocToken(); + return result; } } JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; @@ -10520,7 +10190,7 @@ var ts; return sourceFile; } if (sourceFile.statements.length === 0) { - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true); + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); } var incrementalSourceFile = sourceFile; ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); @@ -10534,7 +10204,7 @@ var ts; ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); return result; } IncrementalParser.updateSourceFile = updateSourceFile; @@ -10794,20 +10464,1233 @@ var ts; })(IncrementalParser || (IncrementalParser = {})); })(ts || (ts = {})); var ts; +(function (ts) { + ts.bindTime = 0; + function or(state1, state2) { + return (state1 | state2) & 2 + ? 2 + : (state1 & state2) & 8 + ? 8 + : 4; + } + function getModuleInstanceState(node) { + if (node.kind === 219 || node.kind === 220) { + return 0; + } + else if (ts.isConstEnumDeclaration(node)) { + return 2; + } + else if ((node.kind === 226 || node.kind === 225) && !(node.flags & 1)) { + return 0; + } + else if (node.kind === 223) { + var state = 0; + ts.forEachChild(node, function (n) { + switch (getModuleInstanceState(n)) { + case 0: + return false; + case 2: + state = 2; + return false; + case 1: + state = 1; + return true; + } + }); + return state; + } + else if (node.kind === 222) { + return getModuleInstanceState(node.body); + } + else { + return 1; + } + } + ts.getModuleInstanceState = getModuleInstanceState; + var binder = createBinder(); + function bindSourceFile(file, options) { + var start = new Date().getTime(); + binder(file, options); + ts.bindTime += new Date().getTime() - start; + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var parent; + var container; + var blockScopeContainer; + var lastContainer; + var seenThisKeyword; + var hasExplicitReturn; + var currentReachabilityState; + var labelStack; + var labelIndexMap; + var implicitLabels; + var hasClassExtends; + var hasAsyncFunctions; + var hasDecorators; + var hasParameterDecorators; + var inStrictMode; + var symbolCount = 0; + var Symbol; + var classifiableNames; + function bindSourceFile(f, opts) { + file = f; + options = opts; + inStrictMode = !!file.externalModuleIndicator; + classifiableNames = {}; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + file = undefined; + options = undefined; + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + hasExplicitReturn = false; + labelStack = undefined; + labelIndexMap = undefined; + implicitLabels = undefined; + hasClassExtends = false; + hasAsyncFunctions = false; + hasDecorators = false; + hasParameterDecorators = false; + } + return bindSourceFile; + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 && !symbol.exports) { + symbol.exports = {}; + } + if (symbolFlags & 6240 && !symbol.members) { + symbol.members = {}; + } + if (symbolFlags & 107455) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 222)) { + symbol.valueDeclaration = node; + } + } + } + function getDeclarationName(node) { + if (node.name) { + if (ts.isAmbientModule(node)) { + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + } + if (node.name.kind === 138) { + var nameExpression = node.name.expression; + if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + return nameExpression.text; + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); + } + return node.name.text; + } + switch (node.kind) { + case 146: + return "__constructor"; + case 154: + case 149: + return "__call"; + case 155: + case 150: + return "__new"; + case 151: + return "__index"; + case 232: + return "__export"; + case 231: + return node.isExportEquals ? "export=" : "default"; + case 185: + switch (ts.getSpecialPropertyAssignmentKind(node)) { + case 2: + return "export="; + case 1: + case 4: + return node.left.name.text; + case 3: + return node.left.expression.name.text; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 217: + case 218: + return node.flags & 512 ? "default" : undefined; + case 265: + return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; + case 140: + ts.Debug.assert(node.parent.kind === 265); + var functionType = node.parent; + var index = ts.indexOf(functionType.parameters, node); + return "p" + index; + } + } + function getDisplayName(node) { + return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); + } + function declareSymbol(symbolTable, parent, node, includes, excludes) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = node.flags & 512; + var name = isDefaultExport && parent ? "default" : getDeclarationName(node); + var symbol; + if (name !== undefined) { + 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; + } + var message = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.flags & 512) { + message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + }); + ts.forEach(symbol.declarations, function (declaration) { + 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); + } + } + else { + symbol = createSymbol(0, "__missing"); + } + addDeclarationToSymbol(symbol, node, includes); + symbol.parent = parent; + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedNodeFlags(node) & 1; + if (symbolFlags & 8388608) { + if (node.kind === 234 || (node.kind === 225 && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + else { + if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { + 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, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + } + function bindChildren(node) { + var saveParent = parent; + var saveContainer = container; + var savedBlockScopeContainer = blockScopeContainer; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags & 1) { + container = blockScopeContainer = node; + if (containerFlags & 4) { + container.locals = {}; + } + addToContainerChain(container); + } + else if (containerFlags & 2) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + var savedReachabilityState; + var savedLabelStack; + var savedLabels; + var savedImplicitLabels; + var savedHasExplicitReturn; + var kind = node.kind; + var flags = node.flags; + flags &= ~98304; + flags &= ~3932160; + if (kind === 219) { + seenThisKeyword = false; + } + var saveState = kind === 252 || kind === 223 || ts.isFunctionLikeKind(kind); + if (saveState) { + savedReachabilityState = currentReachabilityState; + savedLabelStack = labelStack; + savedLabels = labelIndexMap; + savedImplicitLabels = implicitLabels; + savedHasExplicitReturn = hasExplicitReturn; + currentReachabilityState = 2; + hasExplicitReturn = false; + labelStack = labelIndexMap = implicitLabels = undefined; + } + if (ts.isInJavaScriptFile(node) && node.jsDocComment) { + bind(node.jsDocComment); + } + bindReachableStatement(node); + if (currentReachabilityState === 2 && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { + flags |= 32768; + if (hasExplicitReturn) { + flags |= 65536; + } + } + if (kind === 219) { + flags = seenThisKeyword ? flags | 16384 : flags & ~16384; + } + if (kind === 252) { + if (hasClassExtends) { + flags |= 262144; + } + if (hasDecorators) { + flags |= 524288; + } + if (hasParameterDecorators) { + flags |= 1048576; + } + if (hasAsyncFunctions) { + flags |= 2097152; + } + } + node.flags = flags; + if (saveState) { + hasExplicitReturn = savedHasExplicitReturn; + currentReachabilityState = savedReachabilityState; + labelStack = savedLabelStack; + labelIndexMap = savedLabels; + implicitLabels = savedImplicitLabels; + } + container = saveContainer; + parent = saveParent; + blockScopeContainer = savedBlockScopeContainer; + } + function bindReachableStatement(node) { + if (checkUnreachable(node)) { + ts.forEachChild(node, bind); + return; + } + switch (node.kind) { + case 202: + bindWhileStatement(node); + break; + case 201: + bindDoStatement(node); + break; + case 203: + bindForStatement(node); + break; + case 204: + case 205: + bindForInOrForOfStatement(node); + break; + case 200: + bindIfStatement(node); + break; + case 208: + case 212: + bindReturnOrThrow(node); + break; + case 207: + case 206: + bindBreakOrContinueStatement(node); + break; + case 213: + bindTryStatement(node); + break; + case 210: + bindSwitchStatement(node); + break; + case 224: + bindCaseBlock(node); + break; + case 211: + bindLabeledStatement(node); + break; + default: + ts.forEachChild(node, bind); + break; + } + } + function bindWhileStatement(n) { + var preWhileState = n.expression.kind === 84 ? 4 : currentReachabilityState; + var postWhileState = n.expression.kind === 99 ? 4 : currentReachabilityState; + bind(n.expression); + currentReachabilityState = preWhileState; + var postWhileLabel = pushImplicitLabel(); + bind(n.statement); + popImplicitLabel(postWhileLabel, postWhileState); + } + function bindDoStatement(n) { + var preDoState = currentReachabilityState; + var postDoLabel = pushImplicitLabel(); + bind(n.statement); + var postDoState = n.expression.kind === 99 ? 4 : preDoState; + popImplicitLabel(postDoLabel, postDoState); + bind(n.expression); + } + function bindForStatement(n) { + var preForState = currentReachabilityState; + var postForLabel = pushImplicitLabel(); + bind(n.initializer); + bind(n.condition); + bind(n.incrementor); + bind(n.statement); + var isInfiniteLoop = (!n.condition || n.condition.kind === 99); + var postForState = isInfiniteLoop ? 4 : preForState; + popImplicitLabel(postForLabel, postForState); + } + function bindForInOrForOfStatement(n) { + var preStatementState = currentReachabilityState; + var postStatementLabel = pushImplicitLabel(); + bind(n.initializer); + bind(n.expression); + bind(n.statement); + popImplicitLabel(postStatementLabel, preStatementState); + } + function bindIfStatement(n) { + var ifTrueState = n.expression.kind === 84 ? 4 : currentReachabilityState; + var ifFalseState = n.expression.kind === 99 ? 4 : currentReachabilityState; + currentReachabilityState = ifTrueState; + bind(n.expression); + bind(n.thenStatement); + if (n.elseStatement) { + var preElseState = currentReachabilityState; + currentReachabilityState = ifFalseState; + bind(n.elseStatement); + currentReachabilityState = or(currentReachabilityState, preElseState); + } + else { + currentReachabilityState = or(currentReachabilityState, ifFalseState); + } + } + function bindReturnOrThrow(n) { + bind(n.expression); + if (n.kind === 208) { + hasExplicitReturn = true; + } + currentReachabilityState = 4; + } + function bindBreakOrContinueStatement(n) { + bind(n.label); + var isValidJump = jumpToLabel(n.label, n.kind === 207 ? currentReachabilityState : 4); + if (isValidJump) { + currentReachabilityState = 4; + } + } + function bindTryStatement(n) { + var preTryState = currentReachabilityState; + bind(n.tryBlock); + var postTryState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.catchClause); + var postCatchState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.finallyBlock); + currentReachabilityState = or(postTryState, postCatchState); + } + function bindSwitchStatement(n) { + var preSwitchState = currentReachabilityState; + var postSwitchLabel = pushImplicitLabel(); + bind(n.expression); + bind(n.caseBlock); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 246; }); + var postSwitchState = hasDefault && currentReachabilityState !== 2 ? 4 : preSwitchState; + popImplicitLabel(postSwitchLabel, postSwitchState); + } + function bindCaseBlock(n) { + var startState = currentReachabilityState; + for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + currentReachabilityState = startState; + bind(clause); + if (clause.statements.length && currentReachabilityState === 2 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + } + function bindLabeledStatement(n) { + bind(n.label); + var ok = pushNamedLabel(n.label); + bind(n.statement); + if (ok) { + popNamedLabel(n.label, currentReachabilityState); + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 190: + case 218: + case 219: + case 221: + case 169: + case 157: + case 261: + return 1; + case 149: + case 150: + case 151: + case 145: + case 144: + case 217: + case 146: + case 147: + case 148: + case 154: + case 155: + case 177: + case 178: + case 222: + case 252: + case 220: + return 5; + case 248: + case 203: + case 204: + case 205: + case 224: + return 2; + case 196: + return ts.isFunctionLike(node.parent) ? 0 : 2; + } + 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 222: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 252: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 190: + case 218: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 221: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 157: + case 169: + case 219: + case 261: + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 154: + case 155: + case 149: + case 150: + case 151: + case 145: + case 144: + case 146: + case 147: + case 148: + case 217: + case 177: + case 178: + case 265: + case 220: + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return node.flags & 32 + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 252 ? node : node.body; + if (body.kind === 252 || body.kind === 223) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 232 || stat.kind === 231) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 8192; + } + else { + node.flags &= ~8192; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (node.flags & 1) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + declareSymbolAndAddToSymbolTable(node, 512, 106639); + } + else { + var state = getModuleInstanceState(node); + if (state === 0) { + declareSymbolAndAddToSymbolTable(node, 1024, 0); + } + else { + declareSymbolAndAddToSymbolTable(node, 512, 106639); + if (node.symbol.flags & (16 | 32 | 256)) { + node.symbol.constEnumOnlyModule = false; + } + else { + var currentModuleIsConstEnumOnly = state === 2; + if (node.symbol.constEnumOnlyModule === undefined) { + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + } + else { + node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + } + } + } + } + } + function bindFunctionOrConstructorType(node) { + var symbol = createSymbol(131072, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072); + var typeLiteralSymbol = createSymbol(2048, "__type"); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048); + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; + } + 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 !== 69) { + continue; + } + var identifier = prop.name; + var currentKind = prop.kind === 249 || prop.kind === 250 || prop.kind === 145 + ? 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 bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 222: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 252: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = {}; + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2, 107455); + } + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 106 && + node.originalKeywordKind <= 114 && + !ts.isIdentifierName(node)) { + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + if (inStrictMode && node.expression.kind === 69) { + 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 === 69 && + (node.text === "eval" || node.text === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 69) { + 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.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.isOctalLiteral) { + 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 === 41 || node.operator === 42) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function getDestructuringParameterName(node) { + return "__" + ts.indexOf(node.parent.parameters, node); + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var savedInStrictMode = inStrictMode; + if (!savedInStrictMode) { + updateStrictMode(node); + } + bindWorker(node); + bindChildren(node); + inStrictMode = savedInStrictMode; + } + function updateStrictMode(node) { + switch (node.kind) { + case 252: + case 223: + updateStrictModeStatementList(node.statements); + return; + case 196: + if (ts.isFunctionLike(node.parent)) { + updateStrictModeStatementList(node.statements); + } + return; + case 218: + case 190: + inStrictMode = true; + return; + } + } + function updateStrictModeStatementList(statements) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + return nodeText === "\"use strict\"" || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + case 69: + return checkStrictModeIdentifier(node); + case 185: + if (ts.isInJavaScriptFile(node)) { + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1: + bindExportsPropertyAssignment(node); + break; + case 2: + bindModuleExportsAssignment(node); + break; + case 3: + bindPrototypePropertyAssignment(node); + break; + case 4: + bindThisPropertyAssignment(node); + break; + case 0: + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + } + return checkStrictModeBinaryExpression(node); + case 248: + return checkStrictModeCatchClause(node); + case 179: + return checkStrictModeDeleteExpression(node); + case 8: + return checkStrictModeNumericLiteral(node); + case 184: + return checkStrictModePostfixUnaryExpression(node); + case 183: + return checkStrictModePrefixUnaryExpression(node); + case 209: + return checkStrictModeWithStatement(node); + case 163: + seenThisKeyword = true; + return; + case 152: + return checkTypePredicate(node); + case 139: + return declareSymbolAndAddToSymbolTable(node, 262144, 530912); + case 140: + return bindParameter(node); + case 215: + case 167: + return bindVariableDeclarationOrBindingElement(node); + case 143: + case 142: + case 262: + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); + case 249: + case 250: + return bindPropertyOrMethodOrAccessor(node, 4, 107455); + case 251: + return bindPropertyOrMethodOrAccessor(node, 8, 107455); + case 149: + case 150: + case 151: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); + case 145: + case 144: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); + case 217: + return bindFunctionDeclaration(node); + case 146: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 147: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 148: + return bindPropertyOrMethodOrAccessor(node, 65536, 74687); + case 154: + case 155: + case 265: + return bindFunctionOrConstructorType(node); + case 157: + case 261: + return bindAnonymousDeclaration(node, 2048, "__type"); + case 169: + return bindObjectLiteralExpression(node); + case 177: + case 178: + return bindFunctionExpression(node); + case 172: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + case 190: + case 218: + return bindClassLikeDeclaration(node); + case 219: + return bindBlockScopedDeclaration(node, 64, 792960); + case 220: + return bindBlockScopedDeclaration(node, 524288, 793056); + case 221: + return bindEnumDeclaration(node); + case 222: + return bindModuleDeclaration(node); + case 225: + case 228: + case 230: + case 234: + return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); + case 227: + return bindImportClause(node); + case 232: + return bindExportDeclaration(node); + case 231: + return bindExportAssignment(node); + case 252: + return bindSourceFileIfExternalModule(); + } + } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 69) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 163) { + seenThisKeyword = true; + } + bind(type); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + var boundExpression = node.kind === 231 ? node.expression : node.right; + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); + } + else if (boundExpression.kind === 69 && node.kind === 231) { + 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 setCommonJsModuleIndicator(node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + } + function bindExportsPropertyAssignment(node) { + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 7340032, 0); + } + function bindModuleExportsAssignment(node) { + setCommonJsModuleIndicator(node); + bindExportAssignment(node); + } + function bindThisPropertyAssignment(node) { + if (container.kind === 177 || container.kind === 217) { + container.symbol.members = container.symbol.members || {}; + declareSymbol(container.symbol.members, container.symbol, node, 4, 107455 & ~4); + } + } + function bindPrototypePropertyAssignment(node) { + var leftSideOfAssignment = node.left; + var classPrototype = leftSideOfAssignment.expression; + var constructorFunction = classPrototype.expression; + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + var funcSymbol = container.locals[constructorFunction.text]; + if (!funcSymbol || !(funcSymbol.flags & 16)) { + return; + } + if (!funcSymbol.members) { + funcSymbol.members = {}; + } + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 107455); + } + function bindCallExpression(node) { + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { + hasClassExtends = true; + } + if (ts.nodeIsDecorated(node)) { + hasDecorators = true; + } + } + if (node.kind === 218) { + bindBlockScopedDeclaration(node, 32, 899519); + } + else { + var bindingName = node.name ? node.name.text : "__class"; + bindAnonymousDeclaration(node, 32, bindingName); + if (node.name) { + classifiableNames[node.name.text] = node.name.text; + } + } + 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 (!ts.isDeclarationFile(file) && + !ts.isInAmbientContext(node) && + ts.nodeIsDecorated(node)) { + hasDecorators = true; + hasParameterDecorators = true; + } + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1, getDestructuringParameterName(node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1, 107455); + } + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); + } + } + function bindFunctionDeclaration(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + } + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, 16, 106927); + } + function bindFunctionExpression(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.text : "__function"; + return bindAnonymousDeclaration(node, 16, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + if (ts.nodeIsDecorated(node)) { + hasDecorators = true; + } + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function pushNamedLabel(name) { + initializeReachabilityStateIfNecessary(); + if (ts.hasProperty(labelIndexMap, name.text)) { + return false; + } + labelIndexMap[name.text] = labelStack.push(1) - 1; + return true; + } + function pushImplicitLabel() { + initializeReachabilityStateIfNecessary(); + var index = labelStack.push(1) - 1; + implicitLabels.push(index); + return index; + } + function popNamedLabel(label, outerState) { + var index = labelIndexMap[label.text]; + ts.Debug.assert(index !== undefined); + ts.Debug.assert(labelStack.length == index + 1); + labelIndexMap[label.text] = undefined; + setCurrentStateAtLabel(labelStack.pop(), outerState, label); + } + function popImplicitLabel(implicitLabelIndex, outerState) { + if (labelStack.length !== implicitLabelIndex + 1) { + ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); + } + var i = implicitLabels.pop(); + if (implicitLabelIndex !== i) { + ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); + } + setCurrentStateAtLabel(labelStack.pop(), outerState, undefined); + } + function setCurrentStateAtLabel(innerMergedState, outerState, label) { + if (innerMergedState === 1) { + if (label && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); + } + currentReachabilityState = outerState; + } + else { + currentReachabilityState = or(innerMergedState, outerState); + } + } + function jumpToLabel(label, outerState) { + initializeReachabilityStateIfNecessary(); + var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); + if (index === undefined) { + return false; + } + var stateAtLabel = labelStack[index]; + labelStack[index] = stateAtLabel === 1 ? outerState : or(stateAtLabel, outerState); + return true; + } + function checkUnreachable(node) { + switch (currentReachabilityState) { + case 4: + var reportError = (ts.isStatement(node) && node.kind !== 198) || + node.kind === 218 || + (node.kind === 222 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 221 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentReachabilityState = 8; + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 197 || + ts.getCombinedNodeFlags(node.declarationList) & 3072 || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + case 8: + return true; + default: + return false; + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); + } + } + function initializeReachabilityStateIfNecessary() { + if (labelIndexMap) { + return; + } + currentReachabilityState = 2; + labelIndexMap = {}; + labelStack = []; + implicitLabels = []; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; function getNodeId(node) { - if (!node.id) - node.id = nextNodeId++; + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } return node.id; } ts.getNodeId = getNodeId; ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { - symbol.id = nextSymbolId++; + symbol.id = nextSymbolId; + nextSymbolId++; } return symbol.id; } @@ -10823,9 +11706,11 @@ var ts; var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 ? 5 : 0; + var modulekind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; var emitResolver = createResolver(); var undefinedSymbol = createSymbol(4 | 67108864, "undefined"); + undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 | 67108864, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -10834,9 +11719,11 @@ var ts; getTypeCount: function () { return typeCount; }, isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, getDiagnostics: getDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, + getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: getPropertyOfType, @@ -10847,6 +11734,7 @@ var ts; getSymbolsInScope: getSymbolsInScope, getSymbolAtLocation: getSymbolAtLocation, getShorthandAssignmentValueSymbol: getShorthandAssignmentValueSymbol, + getExportSpecifierLocalTargetSymbol: getExportSpecifierLocalTargetSymbol, getTypeAtLocation: getTypeOfNode, typeToString: typeToString, getSymbolDisplayBuilder: getSymbolDisplayBuilder, @@ -10878,8 +11766,8 @@ var ts; var undefinedType = createIntrinsicType(32 | 2097152, "undefined"); var nullType = createIntrinsicType(64 | 2097152, "null"); var unknownType = createIntrinsicType(1, "unknown"); - var circularType = createIntrinsicType(1, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyUnionType = emptyObjectType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -10887,24 +11775,25 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var enumNumberIndexInfo = createIndexInfo(stringType, true); var globals = {}; var globalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; var globalObjectType; var globalFunctionType; var globalArrayType; + var globalReadonlyArrayType; var globalStringType; var globalNumberType; var globalBooleanType; var globalRegExpType; var globalTemplateStringsArrayType; var globalESSymbolType; - var jsxElementType; - var jsxIntrinsicElementsType; var globalIterableType; var globalIteratorType; var globalIterableIteratorType; var anyArrayType; + var anyReadonlyArrayType; var getGlobalClassDecoratorType; var getGlobalParameterDecoratorType; var getGlobalPropertyDecoratorType; @@ -10917,15 +11806,11 @@ var ts; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; var jsxElementClassType; + var deferredNodes; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; var stringLiteralTypes = {}; - var emitExtends = false; - var emitDecorate = false; - var emitParam = false; - var emitAwaiter = false; - var emitGenerator = false; var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -10951,19 +11836,31 @@ var ts; "symbol": { type: esSymbolType, flags: 16777216 + }, + "undefined": { + type: undefinedType, + flags: 2097152 } }; + var jsxElementType; + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", ElementClass: "ElementClass", ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - Element: "Element" + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" }; var subtypeRelation = {}; var assignableRelation = {}; var identityRelation = {}; var _displayBuilder; + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -11017,8 +11914,10 @@ var ts; return result; } function recordMergedSymbol(target, source) { - if (!source.mergeId) - source.mergeId = nextMergeId++; + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { @@ -11042,8 +11941,11 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (!target.valueDeclaration && source.valueDeclaration) + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 222 && source.valueDeclaration.kind !== 222))) { target.valueDeclaration = source.valueDeclaration; + } ts.forEach(source.declarations, function (node) { target.declarations.push(node); }); @@ -11095,6 +11997,45 @@ var ts; } } } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.valueDeclaration !== moduleAugmentation) { + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found); + if (!mainModule) { + return; + } + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1536) { + mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + for (var id in source) { + if (ts.hasProperty(source, id)) { + if (ts.hasProperty(target, id)) { + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } + } + } + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } function getSymbolLinks(symbol) { if (symbol.flags & 67108864) return symbol; @@ -11105,11 +12046,8 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } - function getSourceFile(node) { - return ts.getAncestor(node, 248); - } function isGlobalSourceFile(node) { - return node.kind === 248 && !ts.isExternalModule(node); + return node.kind === 252 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -11126,6 +12064,16 @@ var ts; } } } + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); @@ -11137,18 +12085,18 @@ var ts; return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { - return declaration.kind !== 211 || + return declaration.kind !== 215 || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } return isUsedInFunctionOrNonStaticProperty(declaration, usage); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); - if (declaration.parent.parent.kind === 193 || - declaration.parent.parent.kind === 199) { + if (declaration.parent.parent.kind === 197 || + declaration.parent.parent.kind === 203) { return isSameScopeDescendentOf(usage, declaration, container); } - else if (declaration.parent.parent.kind === 201 || - declaration.parent.parent.kind === 200) { + else if (declaration.parent.parent.kind === 205 || + declaration.parent.parent.kind === 204) { var expression = declaration.parent.parent.expression; return isSameScopeDescendentOf(usage, expression, container); } @@ -11164,8 +12112,8 @@ var ts; return true; } var initializerOfNonStaticProperty = current.parent && - current.parent.kind === 141 && - (current.parent.flags & 64) === 0 && + current.parent.kind === 143 && + (current.parent.flags & 32) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -11184,47 +12132,62 @@ var ts; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - if (!(meaning & 793056) || - !(result.flags & (793056 & ~262144)) || - !ts.isFunctionLike(location) || - lastLocation === location.body) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + if (meaning & result.flags & 793056 && lastLocation.kind !== 269) { + useResult = result.flags & 262144 + ? lastLocation === location.type || + lastLocation.kind === 140 || + lastLocation.kind === 139 + : false; + } + if (meaning & 107455 && result.flags & 1) { + useResult = + lastLocation.kind === 140 || + (lastLocation === location.type && + result.valueDeclaration.kind === 140); + } + } + if (useResult) { break loop; } - result = undefined; + else { + result = undefined; + } } } switch (location.kind) { - case 248: - if (!ts.isExternalModule(location)) + case 252: + if (!ts.isExternalOrCommonJsModule(location)) break; - case 218: + case 222: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 248 || - (location.kind === 218 && location.name.kind === 9)) { + if (location.kind === 252 || ts.isAmbientModule(location)) { + if (result = moduleExports["default"]) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { + break loop; + } + result = undefined; + } if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 && - ts.getDeclarationOfKind(moduleExports[name], 230)) { + ts.getDeclarationOfKind(moduleExports[name], 234)) { break; } - 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 217: + case 221: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; - case 141: - case 140: - if (ts.isClassLike(location.parent) && !(location.flags & 64)) { + case 143: + case 142: + if (ts.isClassLike(location.parent) && !(location.flags & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -11233,17 +12196,17 @@ var ts; } } break; - case 214: - case 186: - case 215: + case 218: + case 190: + case 219: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { - if (lastLocation && lastLocation.flags & 64) { + if (lastLocation && lastLocation.flags & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } break loop; } - if (location.kind === 186 && meaning & 32) { + if (location.kind === 190 && meaning & 32) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -11251,28 +12214,28 @@ var ts; } } break; - case 136: + case 138: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 215) { + if (ts.isClassLike(grandparent) || grandparent.kind === 219) { 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 143: - case 142: - case 144: case 145: + case 144: case 146: - case 213: - case 174: + case 147: + case 148: + case 217: + case 178: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 173: + case 177: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -11285,8 +12248,8 @@ var ts; } } break; - case 139: - if (location.parent && location.parent.kind === 138) { + case 141: + if (location.parent && location.parent.kind === 140) { location = location.parent; } if (location.parent && ts.isClassElement(location.parent)) { @@ -11302,7 +12265,9 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } return undefined; } @@ -11321,11 +12286,40 @@ var ts; } return result; } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!errorLocation || (errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + return false; + } + var container = ts.getThisContainer(errorLocation, true); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); + return true; + } + if (location === container && !(location.flags & 32)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 211), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 215), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -11342,10 +12336,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 221) { + if (node.kind === 225) { return node; } - while (node && node.kind !== 222) { + while (node && node.kind !== 226) { node = node.parent; } return node; @@ -11355,7 +12349,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 232) { + if (node.moduleReference.kind === 236) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -11364,9 +12358,12 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); - if (!exportDefaultSymbol) { + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } return exportDefaultSymbol; } } @@ -11374,14 +12371,6 @@ var ts; var moduleSpecifier = node.parent.parent.moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } - function getMemberOfModuleVariable(moduleSymbol, name) { - if (moduleSymbol.flags & 3) { - var typeAnnotation = moduleSymbol.valueDeclaration.type; - if (typeAnnotation) { - return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); - } - } - } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { if (valueSymbol.flags & (793056 | 1536)) { return valueSymbol; @@ -11444,17 +12433,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 221: + case 225: return getTargetOfImportEqualsDeclaration(node); - case 223: - return getTargetOfImportClause(node); - case 224: - return getTargetOfNamespaceImport(node); - case 226: - return getTargetOfImportSpecifier(node); - case 230: - return getTargetOfExportSpecifier(node); case 227: + return getTargetOfImportClause(node); + case 228: + return getTargetOfNamespaceImport(node); + case 230: + return getTargetOfImportSpecifier(node); + case 234: + return getTargetOfExportSpecifier(node); + case 231: return getTargetOfExportAssignment(node); } } @@ -11496,10 +12485,10 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 227) { + if (node.kind === 231) { checkExpressionCached(node.expression); } - else if (node.kind === 230) { + else if (node.kind === 234) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -11509,17 +12498,17 @@ var ts; } function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 221); + importDeclaration = ts.getAncestor(entityName, 225); ts.Debug.assert(importDeclaration !== undefined); } if (entityName.kind === 69 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 69 || entityName.parent.kind === 135) { + if (entityName.kind === 69 || entityName.parent.kind === 137) { return resolveEntityName(entityName, 1536); } else { - ts.Debug.assert(entityName.parent.kind === 221); + ts.Debug.assert(entityName.parent.kind === 225); return resolveEntityName(entityName, 107455 | 793056 | 1536); } } @@ -11538,9 +12527,9 @@ var ts; return undefined; } } - else if (name.kind === 135 || name.kind === 166) { - var left = name.kind === 135 ? name.left : name.expression; - var right = name.kind === 135 ? name.right : name.name; + else if (name.kind === 137 || name.kind === 170) { + var left = name.kind === 137 ? name.left : name.expression; + var right = name.kind === 137 ? name.right : name.name; var namespace = resolveEntityName(left, 1536, ignoreErrors); if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) { return undefined; @@ -11560,11 +12549,13 @@ var ts; return symbol.flags & meaning ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError) { if (moduleReferenceExpression.kind !== 9) { return; } var moduleReferenceLiteral = moduleReferenceExpression; - var searchPath = ts.getDirectoryPath(getSourceFile(location).fileName); var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); if (moduleName === undefined) { return; @@ -11573,22 +12564,27 @@ var ts; if (!isRelative) { var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); if (symbol) { - return symbol; + return getMergedSymbol(symbol); } } - var resolvedModule = ts.getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReferenceLiteral.text); var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - return sourceFile.symbol; + return getMergedSymbol(sourceFile.symbol); } - error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - return; + if (moduleNotFoundError) { + error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; } - error(moduleReferenceLiteral, ts.Diagnostics.Cannot_find_module_0, moduleName); + if (moduleNotFoundError) { + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + } + return undefined; } function resolveExternalModuleSymbol(moduleSymbol) { - return moduleSymbol && resolveSymbol(moduleSymbol.exports["export="]) || moduleSymbol; + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports["export="])) || moduleSymbol; } function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression) { var symbol = resolveExternalModuleSymbol(moduleSymbol); @@ -11598,8 +12594,8 @@ var ts; } return symbol; } - function getExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports["export="]; + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports["export="] !== undefined; } function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); @@ -11611,35 +12607,58 @@ var ts; var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } - function extendExportSymbols(target, source) { + function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; + if (lookupTable && exportNode) { + lookupTable[id] = { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }; + } + } + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + if (!lookupTable[id].exportsWithDuplicate) { + lookupTable[id].exportsWithDuplicate = [exportNode]; + } + else { + lookupTable[id].exportsWithDuplicate.push(exportNode); + } } } } function getExportsForModule(moduleSymbol) { - var result; var visitedSymbols = []; - visit(moduleSymbol); - return result || moduleSymbol.exports; + return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { - if (symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol)) { - visitedSymbols.push(symbol); - if (symbol !== moduleSymbol) { - if (!result) { - result = cloneSymbolTable(moduleSymbol.exports); - } - extendExportSymbols(result, symbol.exports); - } - var exportStars = symbol.exports["__export"]; - if (exportStars) { - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - visit(resolveExternalModuleName(node, node.moduleSpecifier)); - } - } + if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { + return; } + visitedSymbols.push(symbol); + var symbols = cloneSymbolTable(symbol.exports); + var exportStars = symbol.exports["__export"]; + if (exportStars) { + var nestedSymbols = {}; + var lookupTable = {}; + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); + } + for (var id in lookupTable) { + var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + continue; + } + for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { + var node = exportsWithDuplicate_1[_b]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable[id].specifierText, id)); + } + } + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; } } function getMergedSymbol(symbol) { @@ -11673,14 +12692,15 @@ var ts; var members = node.members; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var member = members_1[_i]; - if (member.kind === 144 && ts.nodeIsPresent(member.body)) { + if (member.kind === 146 && ts.nodeIsPresent(member.body)) { return member; } } } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount++; + result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -11715,19 +12735,19 @@ var ts; } return result || emptyArray; } - function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { + function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; type.properties = getNamedMembers(members); type.callSignatures = callSignatures; type.constructSignatures = constructSignatures; - if (stringIndexType) - type.stringIndexType = stringIndexType; - if (numberIndexType) - type.numberIndexType = numberIndexType; + if (stringIndexInfo) + type.stringIndexInfo = stringIndexInfo; + if (numberIndexInfo) + type.numberIndexInfo = numberIndexInfo; return type; } - function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { - return setObjectTypeMembers(createObjectType(65536, symbol), members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setObjectTypeMembers(createObjectType(65536, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -11738,17 +12758,17 @@ var ts; } } switch (location_1.kind) { - case 248: - if (!ts.isExternalModule(location_1)) { + case 252: + if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 218: + case 222: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 214: - case 215: + case 218: + case 219: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -11781,7 +12801,7 @@ var ts; return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230)) { + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 234)) { if (!useOnlyExternalAliasing || ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); @@ -11810,7 +12830,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 234)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -11865,8 +12885,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 218 && declaration.name.kind === 9) || - (declaration.kind === 248 && ts.isExternalModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 252 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -11878,7 +12897,7 @@ var ts; if (!isDeclarationVisible(declaration)) { var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 2) && + !(anyImportSyntax.flags & 1) && isDeclarationVisible(anyImportSyntax.parent)) { getNodeLinks(declaration).isVisible = true; if (aliasesToMakeVisible) { @@ -11898,11 +12917,11 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 154) { + if (entityName.parent.kind === 156) { meaning = 107455 | 1048576; } - else if (entityName.kind === 135 || entityName.kind === 166 || - entityName.parent.kind === 221) { + else if (entityName.kind === 137 || entityName.kind === 170 || + entityName.parent.kind === 225) { meaning = 1536; } else { @@ -11932,9 +12951,9 @@ var ts; ts.releaseStringWriter(writer); return result; } - function signatureToString(signature, enclosingDeclaration, flags) { + function signatureToString(signature, enclosingDeclaration, flags, kind) { var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); var result = writer.string(); ts.releaseStringWriter(writer); return result; @@ -11950,18 +12969,39 @@ var ts; } return result; } + function typePredicateToString(typePredicate, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + return result; + } + function visibilityToString(flags) { + if (flags === 8) { + return "private"; + } + if (flags === 16) { + return "protected"; + } + return "public"; + } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048) { var node = type.symbol.declarations[0].parent; - while (node.kind === 160) { + while (node.kind === 162) { node = node.parent; } - if (node.kind === 216) { + if (node.kind === 220) { return getSymbolOfNode(node); } } return undefined; } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 223 && + ts.isExternalModuleAugmentation(node.parent.parent); + } function getSymbolDisplayBuilder() { function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { @@ -11970,10 +13010,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 186: + case 190: return "(Anonymous class)"; - case 173: - case 174: + case 177: + case 178: return "(Anonymous function)"; } } @@ -12064,7 +13104,7 @@ var ts; writeAnonymousType(type, flags); } else if (type.flags & 256) { - writer.writeStringLiteral(type.text); + writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } else { writePunctuation(writer, 15); @@ -12092,11 +13132,13 @@ var ts; } if (pos < end) { writePunctuation(writer, 25); - writeType(typeArguments[pos++], 0); + writeType(typeArguments[pos], 0); + pos++; while (pos < end) { writePunctuation(writer, 24); writeSpace(writer); - writeType(typeArguments[pos++], 0); + writeType(typeArguments[pos], 0); + pos++; } writePunctuation(writer, 27); } @@ -12115,12 +13157,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_3 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_4 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_3); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_4); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_3, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_4, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -12175,11 +13217,11 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 64; })); + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 32; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 248 || declaration.parent.kind === 219; + return declaration.parent.kind === 252 || declaration.parent.kind === 223; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 2) || @@ -12192,17 +13234,38 @@ var ts; writeSpace(writer); buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); } - function getIndexerParameterName(type, indexKind, fallbackName) { - var declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); - if (!declaration) { - return fallbackName; + function writeIndexSignature(info, keyword) { + if (info) { + if (info.isReadonly) { + writeKeyword(writer, 127); + writeSpace(writer); + } + writePunctuation(writer, 19); + writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); + writePunctuation(writer, 54); + writeSpace(writer); + writeKeyword(writer, keyword); + writePunctuation(writer, 20); + writePunctuation(writer, 54); + writeSpace(writer); + writeType(info.type, 0); + writePunctuation(writer, 23); + writer.writeLine(); + } + } + function writePropertyWithModifiers(prop) { + if (isReadonlySymbol(prop)) { + writeKeyword(writer, 127); + writeSpace(writer); + } + buildSymbolDisplay(prop, writer); + if (prop.flags & 536870912) { + writePunctuation(writer, 53); } - ts.Debug.assert(declaration.parameters.length !== 0); - return ts.declarationNameToString(declaration.parameters[0].name); } function writeLiteralType(type, flags) { var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) { + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { writePunctuation(writer, 15); writePunctuation(writer, 16); @@ -12212,7 +13275,7 @@ var ts; if (flags & 64) { writePunctuation(writer, 17); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { writePunctuation(writer, 18); } @@ -12224,7 +13287,7 @@ var ts; } writeKeyword(writer, 92); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { writePunctuation(writer, 18); } @@ -12238,44 +13301,18 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - writeKeyword(writer, 92); - writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); - writePunctuation(writer, 23); - writer.writeLine(); - } - if (resolved.stringIndexType) { - writePunctuation(writer, 19); - writer.writeParameter(getIndexerParameterName(resolved, 0, "x")); - writePunctuation(writer, 54); - writeSpace(writer); - writeKeyword(writer, 130); - writePunctuation(writer, 20); - writePunctuation(writer, 54); - writeSpace(writer); - writeType(resolved.stringIndexType, 0); - writePunctuation(writer, 23); - writer.writeLine(); - } - if (resolved.numberIndexType) { - writePunctuation(writer, 19); - writer.writeParameter(getIndexerParameterName(resolved, 1, "x")); - writePunctuation(writer, 54); - writeSpace(writer); - writeKeyword(writer, 128); - writePunctuation(writer, 20); - writePunctuation(writer, 54); - writeSpace(writer); - writeType(resolved.numberIndexType, 0); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } + writeIndexSignature(resolved.stringIndexInfo, 131); + writeIndexSignature(resolved.numberIndexInfo, 129); for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); @@ -12283,20 +13320,14 @@ var ts; var signatures = getSignaturesOfType(t, 0); for (var _f = 0, signatures_1 = signatures; _f < signatures_1.length; _f++) { var signature = signatures_1[_f]; - buildSymbolDisplay(p, writer); - if (p.flags & 536870912) { - writePunctuation(writer, 53); - } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + writePropertyWithModifiers(p); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } } else { - buildSymbolDisplay(p, writer); - if (p.flags & 536870912) { - writePunctuation(writer, 53); - } + writePropertyWithModifiers(p); writePunctuation(writer, 54); writeSpace(writer); writeType(t, 0); @@ -12309,10 +13340,10 @@ var ts; inObjectTypeLiteral = saveInObjectTypeLiteral; } } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaraiton, flags) { + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { var targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); } } function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { @@ -12375,6 +13406,18 @@ var ts; } writePunctuation(writer, 18); } + function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 97); + } + writeSpace(writer); + writeKeyword(writer, 124); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8) { writeSpace(writer); @@ -12384,20 +13427,19 @@ var ts; writePunctuation(writer, 54); } writeSpace(writer); - var returnType; if (signature.typePredicate) { - writer.writeParameter(signature.typePredicate.parameterName); - writeSpace(writer); - writeKeyword(writer, 124); - writeSpace(writer); - returnType = signature.typePredicate.type; + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); } else { - returnType = getReturnTypeOfSignature(signature); + var returnType = getReturnTypeOfSignature(signature); + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1) { + writeKeyword(writer, 92); + writeSpace(writer); + } if (signature.target && (flags & 32)) { buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); } @@ -12411,6 +13453,7 @@ var ts; buildSymbolDisplay: buildSymbolDisplay, buildTypeDisplay: buildTypeDisplay, buildTypeParameterDisplay: buildTypeParameterDisplay, + buildTypePredicateDisplay: buildTypePredicateDisplay, buildParameterDisplay: buildParameterDisplay, buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, @@ -12420,114 +13463,6 @@ var ts; }); } function isDeclarationVisible(node) { - function getContainingExternalModule(node) { - for (; node; node = node.parent) { - if (node.kind === 218) { - if (node.name.kind === 9) { - return node; - } - } - else if (node.kind === 248) { - return ts.isExternalModule(node) ? node : undefined; - } - } - ts.Debug.fail("getContainingModule cant reach here"); - } - function isUsedInExportAssignment(node) { - var externalModule = getContainingExternalModule(node); - var exportAssignmentSymbol; - var resolvedExportSymbol; - if (externalModule) { - var externalModuleSymbol = getSymbolOfNode(externalModule); - exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - var symbolOfNode = getSymbolOfNode(node); - if (isSymbolUsedInExportAssignment(symbolOfNode)) { - return true; - } - if (symbolOfNode.flags & 8388608) { - return isSymbolUsedInExportAssignment(resolveAlias(symbolOfNode)); - } - } - function isSymbolUsedInExportAssignment(symbol) { - if (exportAssignmentSymbol === symbol) { - return true; - } - if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608)) { - resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol); - if (resolvedExportSymbol === symbol) { - return true; - } - return ts.forEach(resolvedExportSymbol.declarations, function (current) { - while (current) { - if (current === node) { - return true; - } - current = current.parent; - } - }); - } - } - } - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 163: - return isDeclarationVisible(node.parent.parent); - case 211: - if (ts.isBindingPattern(node.name) && - !node.name.elements.length) { - return false; - } - case 218: - case 214: - case 215: - case 216: - case 213: - case 217: - case 221: - var parent_4 = getDeclarationContainer(node); - if (!(ts.getCombinedNodeFlags(node) & 2) && - !(node.kind !== 221 && parent_4.kind !== 248 && ts.isInAmbientContext(parent_4))) { - return isGlobalSourceFile(parent_4); - } - return isDeclarationVisible(parent_4); - case 141: - case 140: - case 145: - case 146: - case 143: - case 142: - if (node.flags & (16 | 32)) { - return false; - } - case 144: - case 148: - case 147: - case 149: - case 138: - case 219: - case 152: - case 153: - case 155: - case 151: - case 156: - case 157: - case 158: - case 159: - case 160: - return isDeclarationVisible(node.parent); - case 223: - case 224: - case 226: - return false; - case 137: - case 248: - return true; - case 227: - return false; - default: - ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); - } - } if (node) { var links = getNodeLinks(node); if (links.isVisible === undefined) { @@ -12535,13 +13470,77 @@ var ts; } return links.isVisible; } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 167: + return isDeclarationVisible(node.parent.parent); + case 215: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + return false; + } + case 222: + case 218: + case 219: + case 220: + case 217: + case 221: + case 225: + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent_5 = getDeclarationContainer(node); + if (!(ts.getCombinedNodeFlags(node) & 1) && + !(node.kind !== 225 && parent_5.kind !== 252 && ts.isInAmbientContext(parent_5))) { + return isGlobalSourceFile(parent_5); + } + return isDeclarationVisible(parent_5); + case 143: + case 142: + case 147: + case 148: + case 145: + case 144: + if (node.flags & (8 | 16)) { + return false; + } + case 146: + case 150: + case 149: + case 151: + case 140: + case 223: + case 154: + case 155: + case 157: + case 153: + case 158: + case 159: + case 160: + case 161: + case 162: + return isDeclarationVisible(node.parent); + case 227: + case 228: + case 230: + return false; + case 139: + case 252: + return true; + case 231: + return false; + default: + ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); + } + } } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 227) { + if (node.parent && node.parent.kind === 231) { exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 230) { + else if (node.parent.kind === 234) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -12563,7 +13562,9 @@ var ts; var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793056 | 1536, ts.Diagnostics.Cannot_find_name_0, firstIdentifier); - buildVisibleNodeList(importSymbol.declarations); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } } }); } @@ -12616,10 +13617,23 @@ var ts; } function getDeclarationContainer(node) { node = ts.getRootDeclaration(node); - return node.kind === 211 ? node.parent.parent.parent : node.parent; + while (node) { + switch (node.kind) { + case 215: + case 216: + case 230: + case 229: + case 228: + case 227: + node = node.parent; + break; + default: + return node.parent; + } + } } function getTypeOfPrototypeProperty(prototype) { - var classType = getDeclaredTypeOfSymbol(prototype.parent); + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; } function getTypeOfPropertyOfType(type, name) { @@ -12633,6 +13647,23 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); } + function getTextOfPropertyName(name) { + switch (name.kind) { + case 69: + return name.text; + case 9: + case 8: + return name.text; + case 138: + if (ts.isStringOrNumericLiteral(name.expression.kind)) { + return name.expression.text; + } + } + return undefined; + } + function isComputedNonLiteralName(name) { + return name.kind === 138 && !ts.isStringOrNumericLiteral(name.expression.kind); + } function getTypeForBindingElement(declaration) { var pattern = declaration.parent; var parentType = getTypeForBindingElementParent(pattern.parent); @@ -12646,10 +13677,14 @@ var ts; return parentType; } var type; - if (pattern.kind === 161) { + if (pattern.kind === 165) { var name_10 = declaration.propertyName || declaration.name; - type = getTypeOfPropertyOfType(parentType, name_10.text) || - isNumericLiteralName(name_10.text) && getIndexTypeOfType(parentType, 1) || + if (isComputedNonLiteralName(name_10)) { + return anyType; + } + var text = getTextOfPropertyName(name_10); + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10)); @@ -12679,11 +13714,44 @@ var ts; } return type; } - function getTypeForVariableLikeDeclaration(declaration) { - if (declaration.parent.parent.kind === 200) { - return anyType; + function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return getTypeFromTypeNode(jsDocType); } - if (declaration.parent.parent.kind === 201) { + } + function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + var typeTag = ts.getJSDocTypeTag(declaration); + if (typeTag && typeTag.typeExpression) { + return typeTag.typeExpression.type; + } + if (declaration.kind === 215 && + declaration.parent.kind === 216 && + declaration.parent.parent.kind === 197) { + var annotation = ts.getJSDocTypeTag(declaration.parent.parent); + if (annotation && annotation.typeExpression) { + return annotation.typeExpression.type; + } + } + else if (declaration.kind === 140) { + var paramTag = ts.getCorrespondingJSDocParameterTag(declaration); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type; + } + } + return undefined; + } + function getTypeForVariableLikeDeclaration(declaration) { + if (declaration.flags & 134217728) { + var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (type && type !== unknownType) { + return type; + } + } + if (declaration.parent.parent.kind === 204) { + return stringType; + } + if (declaration.parent.parent.kind === 205) { return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -12692,10 +13760,10 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 138) { + if (declaration.kind === 140) { var func = declaration.parent; - if (func.kind === 146 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 145); + if (func.kind === 148 && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 147); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } @@ -12708,7 +13776,7 @@ var ts; if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } - if (declaration.kind === 246) { + if (declaration.kind === 250) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { @@ -12727,10 +13795,16 @@ var ts; } function getTypeFromObjectBindingPattern(pattern, includePatternInType) { var members = {}; + var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { - var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var name = e.propertyName || e.name; - var symbol = createSymbol(flags, name.text); + if (isComputedNonLiteralName(name)) { + hasComputedProperties = true; + return; + } + var text = getTextOfPropertyName(name); + var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); + var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; @@ -12739,6 +13813,9 @@ var ts; if (includePatternInType) { result.pattern = pattern; } + if (hasComputedProperties) { + result.flags |= 67108864; + } return result; } function getTypeFromArrayBindingPattern(pattern, includePatternInType) { @@ -12746,7 +13823,7 @@ var ts; if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } - var elementTypes = ts.map(elements, function (e) { return e.kind === 187 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return e.kind === 191 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { var result = createNewTupleType(elementTypes); result.pattern = pattern; @@ -12755,7 +13832,7 @@ var ts; return createTupleType(elementTypes); } function getTypeFromBindingPattern(pattern, includePatternInType) { - return pattern.kind === 161 + return pattern.kind === 165 ? getTypeFromObjectBindingPattern(pattern, includePatternInType) : getTypeFromArrayBindingPattern(pattern, includePatternInType); } @@ -12765,12 +13842,15 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - return declaration.kind !== 245 ? getWidenedType(type) : type; + if (declaration.kind === 249) { + return type; + } + return getWidenedType(type); } type = declaration.dotDotDotToken ? anyArrayType : anyType; if (reportErrors && compilerOptions.noImplicitAny) { var root = ts.getRootDeclaration(declaration); - if (!isPrivateWithinAmbient(root) && !(root.kind === 138 && isPrivateWithinAmbient(root.parent))) { + if (!isPrivateWithinAmbient(root) && !(root.kind === 140 && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } } @@ -12783,12 +13863,20 @@ var ts; return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 244) { + if (declaration.parent.kind === 248) { return links.type = anyType; } - if (declaration.kind === 227) { + if (declaration.kind === 231) { return links.type = checkExpression(declaration.expression); } + if (declaration.kind === 185) { + return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + if (declaration.kind === 170) { + if (declaration.parent.kind === 185) { + return links.type = checkExpressionCached(declaration.parent.right); + } + } if (!pushTypeResolution(symbol, 0)) { return unknownType; } @@ -12811,7 +13899,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 145) { + if (accessor.kind === 147) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -12827,8 +13915,8 @@ var ts; if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var getter = ts.getDeclarationOfKind(symbol, 145); - var setter = ts.getDeclarationOfKind(symbol, 146); + var getter = ts.getDeclarationOfKind(symbol, 147); + var setter = ts.getDeclarationOfKind(symbol, 148); var type; var getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { @@ -12854,7 +13942,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 145); + var getter_1 = ts.getDeclarationOfKind(symbol, 147); 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)); } } @@ -12943,9 +14031,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 214 || node.kind === 186 || - node.kind === 213 || node.kind === 173 || - node.kind === 143 || node.kind === 174) { + if (node.kind === 218 || node.kind === 190 || + node.kind === 217 || node.kind === 177 || + node.kind === 145 || node.kind === 178) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -12954,15 +14042,15 @@ var ts; } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 215); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 219); return appendOuterTypeParameters(undefined, declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 215 || node.kind === 214 || - node.kind === 186 || node.kind === 216) { + if (node.kind === 219 || node.kind === 218 || + node.kind === 190 || node.kind === 220) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -13017,9 +14105,6 @@ var ts; } return type.resolvedBaseConstructorType; } - function hasClassBaseType(type) { - return !!ts.forEach(getBaseTypes(type), function (t) { return !!(t.symbol.flags & 32); }); - } function getBaseTypes(type) { var isClass = type.symbol.flags & 32; var isInterface = type.symbol.flags & 64; @@ -13038,17 +14123,19 @@ var ts; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - var baseContructorType = getBaseConstructorTypeOfClass(type); - if (!(baseContructorType.flags & 80896)) { + var baseConstructorType = getBaseConstructorTypeOfClass(type); + if (!(baseConstructorType.flags & 80896)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); var baseType; - if (baseContructorType.symbol && baseContructorType.symbol.flags & 32) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol); + var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && + areAllOuterTypeParametersApplied(originalBaseType)) { + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); } else { - var constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return; @@ -13073,11 +14160,20 @@ var ts; type.resolvedBaseTypes.push(baseType); } } + function areAllOuterTypeParametersApplied(type) { + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 219 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -13106,8 +14202,8 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215) { - if (declaration.flags & 262144) { + if (declaration.kind === 219) { + if (declaration.flags & 16384) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); @@ -13144,7 +14240,7 @@ var ts; type.typeArguments = type.typeParameters; type.thisType = createType(512 | 33554432); type.thisType.symbol = symbol; - type.thisType.constraint = getTypeWithThisArgument(type); + type.thisType.constraint = type; } } return links.declaredType; @@ -13155,7 +14251,7 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 216); + var declaration = ts.getDeclarationOfKind(symbol, 220); var type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -13186,7 +14282,7 @@ var ts; if (!links.declaredType) { var type = createType(512); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 137).constraint) { + if (!ts.getDeclarationOfKind(symbol, 139).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -13233,16 +14329,16 @@ var ts; function isIndependentType(node) { switch (node.kind) { case 117: - case 130: - case 128: - case 120: case 131: + case 129: + case 120: + case 132: case 103: - case 9: + case 164: return true; - case 156: + case 158: return isIndependentType(node.elementType); - case 151: + case 153: return isIndependentTypeReference(node); } return false; @@ -13251,7 +14347,7 @@ var ts; return node.type && isIndependentType(node.type) || !node.type && !node.initializer; } function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 144 && (!node.type || !isIndependentType(node.type))) { + if (node.kind !== 146 && (!node.type || !isIndependentType(node.type))) { return false; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -13267,12 +14363,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 141: - case 140: - return isIndependentVariableLikeDeclaration(declaration); case 143: case 142: + return isIndependentVariableLikeDeclaration(declaration); + case 145: case 144: + case 146: return isIndependentFunctionLikeDeclaration(declaration); } } @@ -13303,22 +14399,14 @@ var ts; } } } - function addInheritedSignatures(signatures, baseSignatures) { - if (baseSignatures) { - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var signature = baseSignatures_1[_i]; - signatures.push(signature); - } - } - } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; type.declaredProperties = getNamedMembers(symbol.members); type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]); type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]); - type.declaredStringIndexType = getIndexTypeOfSymbol(symbol, 0); - type.declaredNumberIndexType = getIndexTypeOfSymbol(symbol, 1); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); } return type; } @@ -13333,15 +14421,15 @@ var ts; var members = source.symbol.members; var callSignatures = source.declaredCallSignatures; var constructSignatures = source.declaredConstructSignatures; - var stringIndexType = source.declaredStringIndexType; - var numberIndexType = source.declaredNumberIndexType; + var stringIndexInfo = source.declaredStringIndexInfo; + var numberIndexInfo = source.declaredNumberIndexInfo; if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); - stringIndexType = instantiateType(source.declaredStringIndexType, mapper); - numberIndexType = instantiateType(source.declaredNumberIndexType, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } var baseTypes = getBaseTypes(source); if (baseTypes.length) { @@ -13355,11 +14443,11 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1)); - stringIndexType = stringIndexType || getIndexTypeOfType(instantiatedBaseType, 0); - numberIndexType = numberIndexType || getIndexTypeOfType(instantiatedBaseType, 1); + stringIndexInfo = stringIndexInfo || getIndexInfoOfType(instantiatedBaseType, 0); + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type) { resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); @@ -13387,17 +14475,17 @@ var ts; return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - if (!hasClassBaseType(classType)) { - return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; + } var baseTypeNode = getBaseTypeNodeOfClass(classType); var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { - var baseSig = baseSignatures_2[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -13422,12 +14510,12 @@ var ts; var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); var members = createTupleTypeMemberSymbols(type.elementTypes); addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); } function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreReturnTypes, compareTypesIdentical)) { return s; } } @@ -13478,73 +14566,71 @@ var ts; } return result || emptyArray; } - function getUnionIndexType(types, kind) { + function getUnionIndexInfo(types, kind) { var indexTypes = []; + var isAnyReadonly = false; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; - var indexType = getIndexTypeOfType(type, kind); - if (!indexType) { + var indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { return undefined; } - indexTypes.push(indexType); + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return getUnionType(indexTypes); + return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); } function resolveUnionTypeMembers(type) { var callSignatures = getUnionSignatures(type.types, 0); var constructSignatures = getUnionSignatures(type.types, 1); - var stringIndexType = getUnionIndexType(type.types, 0); - var numberIndexType = getUnionIndexType(type.types, 1); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + var stringIndexInfo = getUnionIndexInfo(type.types, 0); + var numberIndexInfo = getUnionIndexInfo(type.types, 1); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1, type2) { return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } function resolveIntersectionTypeMembers(type) { var callSignatures = emptyArray; var constructSignatures = emptyArray; - var stringIndexType = undefined; - var numberIndexType = undefined; + var stringIndexInfo = undefined; + var numberIndexInfo = undefined; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0)); constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(t, 1)); - stringIndexType = intersectTypes(stringIndexType, getIndexTypeOfType(t, 0)); - numberIndexType = intersectTypes(numberIndexType, getIndexTypeOfType(t, 1)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; - var members; - var callSignatures; - var constructSignatures; - var stringIndexType; - var numberIndexType; if (type.target) { - members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); - constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); - stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0), type.mapper); - numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1), type.mapper); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); + var callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); + var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048) { - members = symbol.members; - callSignatures = getSignaturesOfSymbol(members["__call"]); - constructSignatures = getSignaturesOfSymbol(members["__new"]); - stringIndexType = getIndexTypeOfSymbol(symbol, 0); - numberIndexType = getIndexTypeOfSymbol(symbol, 1); + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members["__call"]); + var constructSignatures = getSignaturesOfSymbol(members["__new"]); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { - members = emptySymbols; - callSignatures = emptyArray; - constructSignatures = emptyArray; + var members = emptySymbols; + var constructSignatures = emptyArray; if (symbol.flags & 1952) { members = getExportsOfSymbol(symbol); } - if (symbol.flags & (16 | 8192)) { - callSignatures = getSignaturesOfSymbol(symbol); - } if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); @@ -13557,10 +14643,12 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } - stringIndexType = undefined; - numberIndexType = (symbol.flags & 384) ? stringType : undefined; + var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; + setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + if (symbol.flags & (16 | 8192)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -13619,14 +14707,19 @@ var ts; type = getApparentType(type); return type.flags & 49152 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getApparentTypeOfTypeParameter(type) { + if (!type.resolvedApparentType) { + var constraintType = getConstraintOfTypeParameter(type); + while (constraintType && constraintType.flags & 512) { + constraintType = getConstraintOfTypeParameter(constraintType); + } + type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); + } + return type.resolvedApparentType; + } function getApparentType(type) { if (type.flags & 512) { - do { - type = getConstraintOfTypeParameter(type); - } while (type && type.flags & 512); - if (!type) { - type = emptyObjectType; - } + type = getApparentTypeOfTypeParameter(type); } if (type.flags & 258) { type = globalStringType; @@ -13645,12 +14738,14 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; + var commonFlags = (containingType.flags & 32768) ? 536870912 : 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 | 32))) { + if (prop && !(getDeclarationFlagsFromSymbol(prop) & (8 | 16))) { + commonFlags &= prop.flags; if (!props) { props = [prop]; } @@ -13678,7 +14773,10 @@ var ts; } propTypes.push(getTypeOfSymbol(prop)); } - var result = createSymbol(4 | 67108864 | 268435456, name); + var result = createSymbol(4 | + 67108864 | + 268435456 | + commonFlags, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & 16384 ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -13728,31 +14826,44 @@ var ts; function getSignaturesOfType(type, kind) { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function typeHasConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & (80896 | 16384)) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.constructSignatures.length > 0; - } - return false; - } - function typeHasCallOrConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & 130048) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; - } - return false; - } - function getIndexTypeOfStructuredType(type, kind) { + function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 130048) { var resolved = resolveStructuredTypeMembers(type); - return kind === 0 ? resolved.stringIndexType : resolved.numberIndexType; + return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } function getIndexTypeOfType(type, kind) { return getIndexTypeOfStructuredType(getApparentType(type), kind); } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectLiteralType(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.name)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + return getUnionType(propTypes); + } + return undefined; + } + function getTypeParametersFromJSDocTemplate(declaration) { + if (declaration.flags & 134217728) { + var templateTag = ts.getJSDocTemplateTag(declaration); + if (templateTag) { + return getTypeParametersFromDeclaration(templateTag.typeParameters); + } + } + return undefined; + } function getTypeParametersFromDeclaration(typeParameterDeclarations) { var result = []; ts.forEach(typeParameterDeclarations, function (node) { @@ -13773,33 +14884,73 @@ var ts; return result; } function isOptionalParameter(node) { + if (node.flags & 134217728) { + if (node.type && node.type.kind === 264) { + return true; + } + var paramTag = ts.getCorrespondingJSDocParameterTag(node); + if (paramTag) { + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 264; + } + } + } if (ts.hasQuestionToken(node)) { return true; } if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = signatureDeclaration.parameters.indexOf(node); + var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } return false; } + function createTypePredicateFromTypePredicateNode(node) { + if (node.parameterName.kind === 69) { + var parameterName = node.parameterName; + return { + kind: 1, + parameterName: parameterName ? parameterName.text : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0, + type: getTypeFromTypeNode(node.type) + }; + } + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { - var classType = declaration.kind === 144 ? + var classType = declaration.kind === 146 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; + declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : + getTypeParametersFromJSDocTemplate(declaration); var parameters = []; var hasStringLiterals = false; var minArgumentCount = -1; - for (var i = 0, n = declaration.parameters.length; i < n; i++) { + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var returnType = undefined; + var typePredicate = undefined; + for (var i = isJSConstructSignature ? 1 : 0, n = declaration.parameters.length; i < n; i++) { var param = declaration.parameters[i]; - parameters.push(param.symbol); - if (param.type && param.type.kind === 9) { + var paramSymbol = param.symbol; + if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.name, 107455, undefined, undefined); + paramSymbol = resolvedSymbol; + } + parameters.push(paramSymbol); + if (param.type && param.type.kind === 164) { hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken) { @@ -13814,25 +14965,28 @@ var ts; if (minArgumentCount < 0) { minArgumentCount = declaration.parameters.length; } - var returnType; - var typePredicate; - if (classType) { + if (isJSConstructSignature) { + minArgumentCount--; + returnType = getTypeFromTypeNode(declaration.parameters[0].type); + } + else if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); - if (declaration.type.kind === 150) { - 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) - }; + if (declaration.type.kind === 152) { + typePredicate = createTypePredicateFromTypePredicateNode(declaration.type); } } else { - if (declaration.kind === 145 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 146); + if (declaration.flags & 134217728) { + var type = getReturnTypeFromJSDocComment(declaration); + if (type && type !== unknownType) { + returnType = type; + } + } + if (declaration.kind === 147 && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 148); returnType = getAnnotatedAccessorType(setter); } if (!returnType && ts.nodeIsMissing(declaration.body)) { @@ -13850,19 +15004,20 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 152: - case 153: - case 213: - case 143: - case 142: + case 154: + case 155: + case 217: + case 145: case 144: + case 146: + case 149: + case 150: + case 151: case 147: case 148: - case 149: - case 145: - case 146: - case 173: - case 174: + case 177: + case 178: + case 265: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -13874,6 +15029,16 @@ var ts; } return result; } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3)) { @@ -13932,7 +15097,7 @@ var ts; } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 144 || signature.declaration.kind === 148; + var isConstructor = signature.declaration.kind === 146 || signature.declaration.kind === 150; var type = createObjectType(65536 | 262144); type.members = emptySymbols; type.properties = emptyArray; @@ -13946,7 +15111,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 128 : 130; + var syntaxKind = kind === 1 ? 129 : 131; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -13962,26 +15127,51 @@ var ts; } return undefined; } - function getIndexTypeOfSymbol(symbol, kind) { - var declaration = getIndexDeclarationOfSymbol(symbol, kind); - return declaration - ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType - : undefined; + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; } - function getConstraintOfTypeParameter(type) { - if (!type.constraint) { - if (type.target) { - var targetConstraint = getConstraintOfTypeParameter(type.target); - type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (declaration.flags & 64) !== 0, declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 139).constraint; + } + function hasConstraintReferenceTo(type, target) { + var checked; + while (type && !(type.flags & 33554432) && type.flags & 512 && !ts.contains(checked, type)) { + if (type === target) { + return true; + } + (checked || (checked = [])).push(type); + var constraintDeclaration = getConstraintDeclaration(type); + type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration); + } + return false; + } + function getConstraintOfTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 137).constraint); + var constraintDeclaration = getConstraintDeclaration(typeParameter); + var constraint = getTypeFromTypeNode(constraintDeclaration); + if (hasConstraintReferenceTo(constraint, typeParameter)) { + error(constraintDeclaration, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + constraint = unknownType; + } + typeParameter.constraint = constraint; } } - return type.constraint === noConstraintType ? undefined : type.constraint; + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 137).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 139).parent); } function getTypeListId(types) { if (types) { @@ -14022,40 +15212,6 @@ var ts; } return type; } - function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode, typeParameterSymbol) { - var links = getNodeLinks(typeReferenceNode); - if (links.isIllegalTypeReferenceInConstraint !== undefined) { - return links.isIllegalTypeReferenceInConstraint; - } - var currentNode = typeReferenceNode; - while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { - currentNode = currentNode.parent; - } - links.isIllegalTypeReferenceInConstraint = currentNode.kind === 137; - return links.isIllegalTypeReferenceInConstraint; - } - function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { - var typeParameterSymbol; - function check(n) { - if (n.kind === 151 && n.typeName.kind === 69) { - 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; }); - } - } - if (links.isIllegalTypeReferenceInConstraint) { - error(typeParameter, ts.Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); - } - } - ts.forEachChild(n, check); - } - if (typeParameter.constraint) { - typeParameterSymbol = getSymbolOfNode(typeParameter); - check(typeParameter.constraint); - } - } function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = type.localTypeParameters; @@ -14092,26 +15248,68 @@ var ts; 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 getTypeReferenceName(node) { + switch (node.kind) { + case 153: + return node.typeName; + case 263: + return node.name; + case 192: + if (ts.isSupportedExpressionWithTypeArguments(node)) { + return node.expression; + } + } + return undefined; + } + function resolveTypeReferenceName(node, typeReferenceName) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + if (symbol === unknownSymbol) { + return unknownType; + } + if (symbol.flags & (32 | 64)) { + return getTypeFromClassOrInterfaceReference(node, symbol); + } + if (symbol.flags & 524288) { + return getTypeFromTypeAliasReference(node, symbol); + } + if (symbol.flags & 107455 && node.kind === 263) { + return getTypeOfSymbol(symbol); + } + return getTypeFromNonGenericTypeReference(node, symbol); + } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var typeNameOrExpression = node.kind === 151 ? 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); + var symbol; + var type; + if (node.kind === 263) { + var typeReferenceName = getTypeReferenceName(node); + symbol = resolveTypeReferenceName(node, typeReferenceName); + type = getTypeReferenceType(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + else { + var typeNameOrExpression = node.kind === 153 ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056) || unknownSymbol; + 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; } @@ -14130,9 +15328,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 214: - case 215: - case 217: + case 218: + case 219: + case 221: return declaration; } } @@ -14164,10 +15362,6 @@ var ts; if (arity === void 0) { arity = 0; } return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } - function tryGetGlobalType(name, arity) { - if (arity === void 0) { arity = 0; } - return getTypeOfGlobalSymbol(getGlobalSymbol(name, 793056, undefined), arity); - } function getExportedTypeFromNamespace(namespace, name) { var namespaceSymbol = getGlobalSymbol(namespace, 1536, undefined); var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056); @@ -14268,7 +15462,7 @@ var ts; } function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { - return emptyObjectType; + return emptyUnionType; } var typeSet = []; addTypesToSet(typeSet, types, 16384); @@ -14334,27 +15528,43 @@ var ts; } return links.resolvedType; } - function getStringLiteralType(node) { - if (ts.hasProperty(stringLiteralTypes, node.text)) { - return stringLiteralTypes[node.text]; + function getStringLiteralTypeForText(text) { + if (ts.hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; } - var type = stringLiteralTypes[node.text] = createType(256); - type.text = ts.getTextOfNode(node); + var type = stringLiteralTypes[text] = createType(256); + type.text = text; return type; } - function getTypeFromStringLiteral(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralType(node); + links.resolvedType = getStringLiteralTypeForText(node.text); + } + return links.resolvedType; + } + function getTypeFromJSDocVariadicType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + function getTypeFromJSDocTupleType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var types = ts.map(node.types, getTypeFromTypeNode); + links.resolvedType = createTupleType(types); } return links.resolvedType; } function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 215)) { - if (!(container.flags & 64) && - (container.kind !== 144 || ts.isNodeDescendentOf(node, container.body))) { + if (parent && (ts.isClassLike(parent) || parent.kind === 219)) { + if (!(container.flags & 32) && + (container.kind !== 146 || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -14371,47 +15581,63 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 117: + case 254: + case 255: return anyType; - case 130: + case 131: return stringType; - case 128: + case 129: return numberType; case 120: return booleanType; - case 131: + case 132: return esSymbolType; case 103: return voidType; - case 97: + case 163: return getTypeFromThisTypeNode(node); - case 9: - return getTypeFromStringLiteral(node); - case 151: - return getTypeFromTypeReference(node); - case 150: - return booleanType; - case 188: - return getTypeFromTypeReference(node); - case 154: - return getTypeFromTypeQueryNode(node); - case 156: - return getTypeFromArrayTypeNode(node); - case 157: - return getTypeFromTupleTypeNode(node); - case 158: - return getTypeFromUnionTypeNode(node); - case 159: - return getTypeFromIntersectionTypeNode(node); - case 160: - return getTypeFromTypeNode(node.type); - case 152: + case 164: + return getTypeFromStringLiteralTypeNode(node); case 153: + case 263: + return getTypeFromTypeReference(node); + case 152: + return booleanType; + case 192: + return getTypeFromTypeReference(node); + case 156: + return getTypeFromTypeQueryNode(node); + case 158: + case 256: + return getTypeFromArrayTypeNode(node); + case 159: + return getTypeFromTupleTypeNode(node); + case 160: + case 257: + return getTypeFromUnionTypeNode(node); + case 161: + return getTypeFromIntersectionTypeNode(node); + case 162: + case 259: + case 260: + case 267: + case 268: + case 264: + return getTypeFromTypeNode(node.type); + case 154: case 155: + case 157: + case 265: + case 261: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 69: - case 135: + case 137: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); + case 258: + return getTypeFromJSDocTupleType(node); + case 266: + return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -14468,18 +15694,22 @@ var ts; return t; }; } - function createInferenceMapper(context) { - var mapper = function (t) { - for (var i = 0; i < context.typeParameters.length; i++) { - if (t === context.typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); + function getInferenceMapper(context) { + if (!context.mapper) { + var mapper = function (t) { + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (t === typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } } - } - return t; - }; - mapper.context = context; - return mapper; + return t; + }; + mapper.context = context; + context.mapper = mapper; + } + return context.mapper; } function identityMapper(type) { return type; @@ -14487,31 +15717,41 @@ var ts; function combineTypeMappers(mapper1, mapper2) { return function (t) { return instantiateType(mapper1(t), mapper2); }; } - function instantiateTypeParameter(typeParameter, mapper) { + function cloneTypeParameter(typeParameter) { var result = createType(512); result.symbol = typeParameter.symbol; - if (typeParameter.constraint) { - result.constraint = instantiateType(typeParameter.constraint, mapper); + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; } else { - result.target = typeParameter; - result.mapper = mapper; + return { + kind: 0, + type: instantiateType(predicate.type, mapper) + }; } - return result; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } } if (signature.typePredicate) { - freshTypePredicate = { - parameterName: signature.typePredicate.parameterName, - parameterIndex: signature.typePredicate.parameterIndex, - type: instantiateType(signature.typePredicate.type, mapper) - }; + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; @@ -14574,28 +15814,31 @@ var ts; } return type; } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 173: - case 174: + case 177: + case 178: return isContextSensitiveFunctionLikeDeclaration(node); - case 165: + case 169: return ts.forEach(node.properties, isContextSensitive); - case 164: + case 168: return ts.forEach(node.elements, isContextSensitive); - case 182: + case 186: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 181: + case 185: return node.operatorToken.kind === 52 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 245: + case 249: return isContextSensitive(node.initializer); - case 143: - case 142: + case 145: + case 144: return isContextSensitiveFunctionLikeDeclaration(node); - case 172: + case 176: return isContextSensitive(node.expression); } return false; @@ -14620,9 +15863,12 @@ var ts; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined); } - function compareTypes(source, target) { + function compareTypesIdentical(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined) ? -1 : 0; } + function compareTypesAssignable(source, target) { + return checkTypeRelatedTo(source, target, assignableRelation, undefined) ? -1 : 0; + } function isTypeSubtypeOf(source, target) { return checkTypeSubtypeOf(source, target, undefined); } @@ -14635,10 +15881,116 @@ var ts; function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } - function isSignatureAssignableTo(source, target) { - var sourceType = getOrCreateTypeFromSignature(source); - var targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, undefined); + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; + } + function compareSignaturesRelated(source, target, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + if (source === target) { + return -1; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return 0; + } + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1; + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + var sourceParams = source.parameters; + var targetParams = target.parameters; + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(sourceParams[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(targetParams[i]) : getRestTypeOfSignature(target); + var related = compareTypes(t, s, false) || compareTypes(s, t, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name); + } + return 0; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return 0; + } + } + else { + result &= compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + if (source.kind === 1) { + var sourceIdentifierPredicate = source; + var targetIdentifierPredicate = target; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, undefined)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; @@ -14648,18 +16000,12 @@ var ts; var expandingFlags; var depth = 0; var overflow = false; - var elaborateErrors = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, errorNode !== undefined, headMessage); + var result = isRelatedTo(source, target, !!errorNode, headMessage); if (overflow) { error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { - if (errorInfo.next === undefined) { - errorInfo = undefined; - elaborateErrors = true; - isRelatedTo(source, target, errorNode !== undefined, headMessage); - } if (containingMessageChain) { errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } @@ -14667,6 +16013,7 @@ var ts; } return result !== 0; function reportError(message, arg0, arg1, arg2) { + ts.Debug.assert(!!errorNode); errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } function reportRelationError(message, source, target) { @@ -14693,6 +16040,11 @@ var ts; return -1; if (source.flags & 128 && target === numberType) return -1; + if (source.flags & 128 && target.flags & 128) { + if (result = enumRelatedTo(source, target)) { + return result; + } + } if (source.flags & 256 && target === stringType) return -1; if (relation === assignableRelation) { @@ -14701,6 +16053,9 @@ var ts; if (source === numberType && target.flags & 128) return -1; } + if (source.flags & 8 && target.flags & 8) { + return -1; + } if (source.flags & 1048576) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -14752,10 +16107,10 @@ var ts; return result; } } - var apparentType = getApparentType(source); - if (apparentType.flags & (80896 | 32768) && target.flags & 80896) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; - if (result = objectTypeRelatedTo(apparentType, source, target, reportStructuralErrors)) { + var apparentSource = getApparentType(source); + if (apparentSource.flags & (80896 | 32768) && target.flags & 80896) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726); + if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; } @@ -14776,9 +16131,6 @@ var ts; } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 512 && target.flags & 512) { - return typeParameterIdenticalTo(source, target); - } if (source.flags & 16384 && target.flags & 16384 || source.flags & 32768 && target.flags & 32768) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -14793,7 +16145,7 @@ var ts; if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if (relation === assignableRelation && (type === globalObjectType || resolved.properties.length === 0) || - resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) { + resolved.stringIndexInfo || resolved.numberIndexInfo || getPropertyOfType(type, name)) { return true; } } @@ -14808,11 +16160,12 @@ var ts; return false; } function hasExcessProperties(source, target, reportErrors) { - if (someConstituentTypeHasKind(target, 80896)) { + if (!(target.flags & 67108864) && maybeTypeOfKind(target, 80896)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { if (reportErrors) { + ts.Debug.assert(!!errorNode); errorNode = prop.valueDeclaration; reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } @@ -14887,8 +16240,9 @@ var ts; if (sources.length !== targets.length && relation === identityRelation) { return 0; } + var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1; - for (var i = 0; i < targets.length; i++) { + for (var i = 0; i < length; i++) { var related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return 0; @@ -14897,26 +16251,17 @@ var ts; } return result; } - function typeParameterIdenticalTo(source, target) { - if (source.symbol.name !== target.symbol.name) { - return 0; - } - if (source.constraint === target.constraint) { - return -1; - } - if (source.constraint === noConstraintType || target.constraint === noConstraintType) { - return 0; - } - return isIdenticalTo(source.constraint, target.constraint); - } - function objectTypeRelatedTo(apparentSource, originalSource, target, reportErrors) { + function objectTypeRelatedTo(source, originalSource, target, reportErrors) { if (overflow) { return 0; } - var id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { - if (!elaborateErrors || (related === 3)) { + if (reportErrors && related === 2) { + relation[id] = 3; + } + else { return related === 1 ? -1 : 0; } } @@ -14937,13 +16282,13 @@ var ts; maybeStack = []; expandingFlags = 0; } - sourceStack[depth] = apparentSource; + sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; @@ -14952,15 +16297,15 @@ var ts; result = 1; } else { - result = propertiesRelatedTo(apparentSource, target, reportErrors); + result = propertiesRelatedTo(source, target, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 0, reportErrors); + result &= signaturesRelatedTo(source, target, 0, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 1, reportErrors); + result &= signaturesRelatedTo(source, target, 1, reportErrors); if (result) { - result &= stringIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= indexTypesRelatedTo(source, originalSource, target, 0, reportErrors); if (result) { - result &= numberIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= indexTypesRelatedTo(source, originalSource, target, 1, reportErrors); } } } @@ -15000,23 +16345,23 @@ var ts; else if (!(targetProp.flags & 134217728)) { var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); - if (sourcePropFlags & 16 || targetPropFlags & 16) { + if (sourcePropFlags & 8 || targetPropFlags & 8) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & 16 && targetPropFlags & 16) { + if (sourcePropFlags & 8 && targetPropFlags & 8) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 16 ? source : target), typeToString(sourcePropFlags & 16 ? target : source)); + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 ? source : target), typeToString(sourcePropFlags & 8 ? target : source)); } } return 0; } } - else if (targetPropFlags & 32) { + else if (targetPropFlags & 16) { var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; - var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); + var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; + var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); @@ -15024,7 +16369,7 @@ var ts; return 0; } } - else if (sourcePropFlags & 32) { + else if (sourcePropFlags & 16) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -15082,140 +16427,41 @@ var ts; } var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 && sourceSignatures.length && targetSignatures.length) { + if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0; + } + } var result = -1; var saveErrorInfo = errorInfo; - if (kind === 1) { - var sourceSig = sourceSignatures[0]; - var targetSig = targetSignatures[0]; - result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); - if (result !== -1) { - return result; - } - } outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; - if (!t.hasStringLiterals || target.flags & 262144) { - var localErrors = reportErrors; - var checkedAbstractAssignability = false; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - if (!s.hasStringLiterals || source.flags & 262144) { - var related = signatureRelatedTo(s, t, localErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; - } - localErrors = false; - } + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; } - return 0; + shouldElaborateErrors = false; } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } return result; - function abstractSignatureRelatedTo(source, sourceSig, target, targetSig) { - if (sourceSig && targetSig) { - var sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - var targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); - if (!sourceDecl) { - return -1; - } - var sourceErasedSignature = getErasedSignature(sourceSig); - var targetErasedSignature = getErasedSignature(targetSig); - var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128; - if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0; - } - } - return -1; - } } function signatureRelatedTo(source, target, reportErrors) { - if (source === target) { - return -1; - } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return 0; - } - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var checkCount; - if (source.hasRestParameter && target.hasRestParameter) { - checkCount = sourceMax > targetMax ? sourceMax : targetMax; - sourceMax--; - targetMax--; - } - else if (source.hasRestParameter) { - sourceMax--; - checkCount = targetMax; - } - else if (target.hasRestParameter) { - targetMax--; - checkCount = sourceMax; - } - else { - checkCount = sourceMax < targetMax ? sourceMax : targetMax; - } - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1; - for (var i = 0; i < checkCount; i++) { - var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); - var saveErrorInfo = errorInfo; - var related = isRelatedTo(s, t, reportErrors); - if (!related) { - related = isRelatedTo(t, s, false); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); - } - return 0; - } - errorInfo = saveErrorInfo; - } - 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 targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) - return result; - var sourceReturnType = getReturnTypeOfSignature(source); - return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); + return compareSignaturesRelated(source, target, false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -15224,8 +16470,8 @@ var ts; return 0; } var result = -1; - for (var i = 0, len = sourceSignatures.length; i < len; ++i) { - var related = compareSignatures(sourceSignatures[i], targetSignatures[i], false, false, isRelatedTo); + for (var i = 0, len = sourceSignatures.length; i < len; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, isRelatedTo); if (!related) { return 0; } @@ -15233,78 +16479,123 @@ var ts; } return result; } - function stringIndexTypesRelatedTo(source, originalSource, target, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(0, source, target); - } - var targetType = getIndexTypeOfType(target, 0); - if (targetType) { - if ((targetType.flags & 1) && !(originalSource.flags & 16777726)) { - return -1; - } - var sourceType = getIndexTypeOfType(source, 0); - if (!sourceType) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.name)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0; } - return 0; + result &= related; } - var related = isRelatedTo(sourceType, targetType, reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return 0; - } - return related; } - return -1; + return result; } - function numberIndexTypesRelatedTo(source, originalSource, target, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(1, source, target); + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); } - var targetType = getIndexTypeOfType(target, 1); - if (targetType) { - if ((targetType.flags & 1) && !(originalSource.flags & 16777726)) { - return -1; - } - var sourceStringType = getIndexTypeOfType(source, 0); - var sourceNumberType = getIndexTypeOfType(source, 1); - if (!(sourceStringType || sourceNumberType)) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); - } - return 0; - } - var related; - if (sourceStringType && sourceNumberType) { - related = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors); - } - else { - related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); - } - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return 0; - } - return related; - } - return -1; + return related; } - function indexTypesIdenticalTo(indexKind, source, target) { - var targetType = getIndexTypeOfType(target, indexKind); - var sourceType = getIndexTypeOfType(source, indexKind); - if (!sourceType && !targetType) { + function indexTypesRelatedTo(source, originalSource, target, kind, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 16777726))) { return -1; } - if (sourceType && targetType) { - return isRelatedTo(sourceType, targetType); + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 && getIndexInfoOfType(source, 0); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isObjectLiteralType(source)) { + var related = -1; + if (kind === 0) { + var sourceNumberInfo = getIndexInfoOfType(source, 1); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } return 0; } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0; + } + function enumRelatedTo(source, target) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & 128 || + target.symbol.flags & 128) { + return 0; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8)) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + return 0; + } + } + } + return -1; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = sourceSignature.declaration.flags & (8 | 16); + var targetAccessibility = targetSignature.declaration.flags & (8 | 16); + if (targetAccessibility === 8) { + return true; + } + if (targetAccessibility === 16 && sourceAccessibility !== 8) { + return true; + } + if (targetAccessibility !== 16 && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function isAbstractConstructorType(type) { + if (type.flags & 65536) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && declaration.flags & 128) { + return true; + } + } + } + return false; } function isDeeplyNestedGeneric(type, stack, depth) { if (type.flags & (4096 | 131072) && depth >= 5) { @@ -15322,14 +16613,14 @@ var ts; return false; } function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypes) !== 0; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; } function compareProperties(sourceProp, targetProp, compareTypes) { if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (16 | 32); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (16 | 32); + var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (8 | 16); + var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (8 | 16); if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -15343,39 +16634,36 @@ var ts; return 0; } } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0; + } return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } - function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + function isMatchingSignature(source, target, partialMatch) { + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + function compareSignaturesIdentical(source, target, partialMatch, ignoreReturnTypes, compareTypes) { if (source === target) { return -1; } - if (source.parameters.length !== target.parameters.length || - source.minArgumentCount !== target.minArgumentCount || - source.hasRestParameter !== target.hasRestParameter) { - if (!partialMatch || - source.parameters.length < target.parameters.length && !source.hasRestParameter || - source.minArgumentCount > target.minArgumentCount) { - return 0; - } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0; } - var result = -1; - if (source.typeParameters && target.typeParameters) { - if (source.typeParameters.length !== target.typeParameters.length) { - return 0; - } - for (var i = 0, len = source.typeParameters.length; i < len; ++i) { - var related = compareTypes(source.typeParameters[i], target.typeParameters[i]); - if (!related) { - return 0; - } - result &= related; - } - } - else if (source.typeParameters || target.typeParameters) { + if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) { return 0; } source = getErasedSignature(source); target = getErasedSignature(target); + var result = -1; var targetLen = target.parameters.length; for (var i = 0; i < targetLen; i++) { var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); @@ -15436,14 +16724,23 @@ var ts; return type.flags & 4096 && type.target === globalArrayType; } function isArrayLikeType(type) { - return !(type.flags & (32 | 64)) && isTypeAssignableTo(type, anyArrayType); + return type.flags & 4096 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & (32 | 64)) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } + function isStringLiteralType(type) { + return type.flags & 256; + } function isTupleType(type) { return !!(type.flags & 8192); } + function isObjectLiteralType(type) { + return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && + getSignaturesOfType(type, 0).length === 0 && + getSignaturesOfType(type, 1).length === 0; + } function getRegularTypeOfObjectLiteral(type) { if (type.flags & 1048576) { var regularType = type.regularType; @@ -15454,8 +16751,8 @@ var ts; regularType.properties = type.properties; regularType.callSignatures = type.callSignatures; regularType.constructSignatures = type.constructSignatures; - regularType.stringIndexType = type.stringIndexType; - regularType.numberIndexType = type.numberIndexType; + regularType.stringIndexInfo = type.stringIndexInfo; + regularType.numberIndexInfo = type.numberIndexInfo; type.regularType = regularType; } return regularType; @@ -15480,13 +16777,9 @@ var ts; } members[p.name] = p; }); - var stringIndexType = getIndexTypeOfType(type, 0); - var numberIndexType = getIndexTypeOfType(type, 1); - if (stringIndexType) - stringIndexType = getWidenedType(stringIndexType); - if (numberIndexType) - numberIndexType = getWidenedType(numberIndexType); - return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); + var stringIndexInfo = getIndexInfoOfType(type, 0); + var numberIndexInfo = getIndexInfoOfType(type, 1); + return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedType(type) { if (type.flags & 6291456) { @@ -15547,22 +16840,22 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 141: - case 140: + case 143: + case 142: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 138: + case 140: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 213: - case 143: - case 142: + case 217: case 145: - case 146: - case 173: - case 174: + case 144: + case 147: + case 148: + case 177: + case 178: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -15608,13 +16901,7 @@ var ts; } } function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var unused = typeParameters_1[_i]; - inferences.push({ - primary: undefined, secondary: undefined, isFixed: false - }); - } + var inferences = ts.map(typeParameters, createTypeInferencesObject); return { typeParameters: typeParameters, inferUnionTypes: inferUnionTypes, @@ -15622,11 +16909,19 @@ var ts; inferredTypes: new Array(typeParameters.length) }; } + function createTypeInferencesObject() { + return { + primary: undefined, + secondary: undefined, + isFixed: false + }; + } function inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; + var visited = {}; inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -15637,6 +16932,21 @@ var ts; return false; } function inferFromTypes(source, target) { + if (source.flags & 16384 && target.flags & 16384 || + source.flags & 32768 && target.flags & 32768) { + var matchingTypes; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (typeIdenticalToSomeType(t, source.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + } + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } if (target.flags & 512) { if (source.flags & 8388608) { return; @@ -15676,8 +16986,8 @@ var ts; var targetTypes = target.types; var typeParameterCount = 0; var typeParameter; - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var t = targetTypes_2[_i]; + for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { + var t = targetTypes_2[_b]; if (t.flags & 512 && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -15694,21 +17004,27 @@ var ts; } else if (source.flags & 49152) { var sourceTypes = source.types; - for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { - var sourceType = sourceTypes_3[_a]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 && (target.flags & (4096 | 8192) || - (target.flags & 65536) && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { + if (source.flags & 80896 && (target.flags & 4096 && target.typeArguments || + target.flags & 8192 || + target.flags & 65536 && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { if (isInProcess(source, target)) { return; } if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { return; } + var key = source.id + "," + target.id; + if (ts.hasProperty(visited, key)) { + return; + } + visited[key] = true; if (depth === 0) { sourceStack = []; targetStack = []; @@ -15719,9 +17035,7 @@ var ts; 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); + inferFromIndexTypes(source, target); depth--; } } @@ -15748,25 +17062,52 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - if (source.typePredicate && target.typePredicate) { - if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } } - function inferFromIndexTypes(source, target, sourceKind, targetKind) { - var targetIndexType = getIndexTypeOfType(target, targetKind); - if (targetIndexType) { - var sourceIndexType = getIndexTypeOfType(source, sourceKind); + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 0); if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetIndexType); + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1) || + getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 1); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); } } } } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 16384 ? getUnionType(reducedTypes, true) : getIntersectionType(reducedTypes); + } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; @@ -15785,14 +17126,19 @@ var ts; inferredType = emptyObjectType; inferenceSucceeded = true; } + context.inferredTypes[index] = inferredType; if (inferenceSucceeded) { var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + context.inferredTypes[index] = inferredType = instantiatedConstraint; + } + } } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { context.failedTypeParameterIndex = index; } - context.inferredTypes[index] = inferredType; } return inferredType; } @@ -15802,9 +17148,6 @@ var ts; } return context.inferredTypes; } - function hasAncestor(node, kind) { - return ts.getAncestor(node, kind) !== undefined; - } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { @@ -15815,10 +17158,10 @@ var ts; function isInTypeQuery(node) { while (node) { switch (node.kind) { - case 154: + case 156: return true; case 69: - case 135: + case 137: node = node.parent; continue; default: @@ -15827,21 +17170,6 @@ var ts; } ts.Debug.fail("should not get here"); } - function removeTypesFromUnionType(type, typeKind, isOfTypeKind, allowEmptyUnionResult) { - if (type.flags & 16384) { - var types = type.types; - if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { - var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); - if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { - return narrowedType; - } - } - } - else if (allowEmptyUnionResult && !!(type.flags & typeKind) === isOfTypeKind) { - return getUnionType(emptyArray); - } - return type; - } function hasInitializer(node) { return !!(node.initializer || ts.isBindingPattern(node.parent) && hasInitializer(node.parent.parent)); } @@ -15859,10 +17187,7 @@ var ts; return links.assignmentChecks[symbol.id] = isAssignedIn(node); function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 56 && node.operatorToken.kind <= 68) { - var n = node.left; - while (n.kind === 172) { - n = n.expression; - } + var n = skipParenthesizedNodes(node.left); if (n.kind === 69 && getResolvedSymbol(n) === symbol) { return true; } @@ -15877,55 +17202,55 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 181: + case 185: return isAssignedInBinaryExpression(node); - case 211: - case 163: + case 215: + case 167: return isAssignedInVariableDeclaration(node); - case 161: - case 162: - case 164: case 165: case 166: - case 167: case 168: case 169: + case 170: case 171: - case 189: case 172: - case 179: + case 173: case 175: - case 178: - case 176: - case 177: - case 180: - case 184: - case 182: - case 185: - case 192: case 193: - case 195: + case 176: + case 183: + case 179: + case 182: + case 180: + case 181: + case 184: + case 188: + case 186: + case 189: case 196: case 197: - case 198: case 199: case 200: case 201: + case 202: + case 203: case 204: case 205: - case 206: - case 241: - case 242: - case 207: case 208: case 209: - case 244: - case 233: - case 234: + case 210: + case 245: + case 246: + case 211: + case 212: + case 213: + case 248: + case 237: case 238: + case 242: + case 243: case 239: - case 235: - case 240: + case 244: return ts.forEachChild(node, isAssignedIn); } return false; @@ -15935,53 +17260,66 @@ var ts; var type = getTypeOfSymbol(symbol); if (node && symbol.flags & 3) { if (isTypeAny(type) || type.flags & (80896 | 16384 | 512)) { + var declaration = ts.getDeclarationOfKind(symbol, 215); + var top_1 = declaration && getDeclarationContainer(declaration); + var originalType = type; + var nodeStack = []; loop: while (node.parent) { var child = node; node = node.parent; - var narrowedType = type; switch (node.kind) { - case 196: - if (child !== node.expression) { - narrowedType = narrowType(type, node.expression, child === node.thenStatement); - } + case 200: + case 186: + case 185: + nodeStack.push({ node: node, child: child }); break; - case 182: - if (child !== node.condition) { - narrowedType = narrowType(type, node.condition, child === node.whenTrue); - } - break; - case 181: - if (child === node.right) { - if (node.operatorToken.kind === 51) { - narrowedType = narrowType(type, node.left, true); - } - else if (node.operatorToken.kind === 52) { - narrowedType = narrowType(type, node.left, false); - } - } - break; - case 248: - case 218: - case 213: - case 143: - case 142: - case 145: - case 146: - case 144: + case 252: + case 222: break loop; } - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; - } - type = narrowedType; + if (node === top_1) { + break; } } + var nodes; + while (nodes = nodeStack.pop()) { + var node_1 = nodes.node, child = nodes.child; + switch (node_1.kind) { + case 200: + if (child !== node_1.expression) { + type = narrowType(type, node_1.expression, child === node_1.thenStatement); + } + break; + case 186: + if (child !== node_1.condition) { + type = narrowType(type, node_1.condition, child === node_1.whenTrue); + } + break; + case 185: + if (child === node_1.right) { + if (node_1.operatorToken.kind === 51) { + type = narrowType(type, node_1.left, true); + } + else if (node_1.operatorToken.kind === 52) { + type = narrowType(type, node_1.left, false); + } + } + break; + default: + ts.Debug.fail("Unreachable!"); + } + if (type !== originalType && isVariableAssignedWithin(symbol, node_1)) { + type = originalType; + } + } + if (type === emptyUnionType) { + type = originalType; + } } } return type; function narrowTypeByEquality(type, expr, assumeTrue) { - if (expr.left.kind !== 176 || expr.right.kind !== 9) { + if (expr.left.kind !== 180 || expr.right.kind !== 9) { return type; } var left = expr.left; @@ -15989,24 +17327,30 @@ var ts; if (left.expression.kind !== 69 || getResolvedSymbol(left.expression) !== symbol) { return type; } - var typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === 33) { assumeTrue = !assumeTrue; } - if (assumeTrue) { - if (!typeInfo) { - return removeTypesFromUnionType(type, 258 | 132 | 8 | 16777216, true, false); - } - if (isTypeSubtypeOf(typeInfo.type, type)) { - return typeInfo.type; - } - return removeTypesFromUnionType(type, typeInfo.flags, false, false); + var typeInfo = primitiveTypeInfo[right.text]; + if (typeInfo && typeInfo.type === undefinedType) { + return type; + } + var flags; + if (typeInfo) { + flags = typeInfo.flags; } else { - if (typeInfo) { - return removeTypesFromUnionType(type, typeInfo.flags, true, false); + assumeTrue = !assumeTrue; + flags = 132 | 258 | 16777216 | 8; + } + if (!(type.flags & 16384)) { + if (assumeTrue && typeInfo && isTypeSubtypeOf(typeInfo.type, type)) { + return typeInfo.type; } - return type; + return filterUnion(type) ? type : emptyUnionType; + } + return getUnionType(ts.filter(type.types, filterUnion), true); + function filterUnion(type) { + return assumeTrue === !!(type.flags & flags); } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -16016,7 +17360,7 @@ var ts; else { return getUnionType([ narrowType(type, expr.left, false), - narrowType(narrowType(type, expr.left, true), expr.right, false) + narrowType(type, expr.right, false) ]); } } @@ -16024,7 +17368,7 @@ var ts; if (assumeTrue) { return getUnionType([ narrowType(type, expr.left, true), - narrowType(narrowType(type, expr.left, false), expr.right, true) + narrowType(type, expr.right, true) ]); } else { @@ -16032,7 +17376,7 @@ var ts; } } function narrowTypeByInstanceof(type, expr, assumeTrue) { - if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 69 || getResolvedSymbol(expr.left) !== symbol) { + if (isTypeAny(type) || expr.left.kind !== 69 || getResolvedSymbol(expr.left) !== symbol) { return type; } var rightType = checkExpression(expr.right); @@ -16060,11 +17404,17 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType); + return getNarrowedType(type, targetType, assumeTrue); } return type; } - function getNarrowedType(originalType, narrowedTypeCandidate) { + function getNarrowedType(originalType, narrowedTypeCandidate, assumeTrue) { + if (!assumeTrue) { + if (originalType.flags & 16384) { + return getUnionType(ts.filter(originalType.types, function (t) { return !isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } if (originalType.flags & 16384) { var assignableConstituents = ts.filter(originalType.types, function (t) { return isTypeAssignableTo(t, narrowedTypeCandidate); }); if (assignableConstituents.length) { @@ -16076,31 +17426,52 @@ var ts; } return originalType; } - function narrowTypeByTypePredicate(type, expr, assumeTrue) { + function narrowTypeByTypePredicate(type, callExpression, 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; + var signature = getResolvedSignature(callExpression); + var predicate = signature.typePredicate; + if (!predicate) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + if (callExpression.arguments[predicate.parameterIndex] && + getSymbolAtTypePredicatePosition(callExpression.arguments[predicate.parameterIndex]) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); } - return getNarrowedType(type, signature.typePredicate.type); + } + else { + var invokedExpression = skipParenthesizedNodes(callExpression.expression); + return narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue); } return type; } + function narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue) { + if (invokedExpression.kind === 171 || invokedExpression.kind === 170) { + var accessExpression = invokedExpression; + var possibleIdentifier = skipParenthesizedNodes(accessExpression.expression); + if (possibleIdentifier.kind === 69 && getSymbolAtTypePredicatePosition(possibleIdentifier) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); + } + } + return type; + } + function getSymbolAtTypePredicatePosition(expr) { + expr = skipParenthesizedNodes(expr); + switch (expr.kind) { + case 69: + case 170: + return getSymbolOfEntityNameOrPropertyAccessExpression(expr); + } + } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 168: - return narrowTypeByTypePredicate(type, expr, assumeTrue); case 172: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 176: return narrowType(type, expr.expression, assumeTrue); - case 181: + case 185: var operator = expr.operatorToken.kind; if (operator === 32 || operator === 33) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -16115,7 +17486,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 179: + case 183: if (expr.operator === 49) { return narrowType(type, expr.operand, !assumeTrue); } @@ -16124,27 +17495,47 @@ var ts; return type; } } + function skipParenthesizedNodes(expression) { + while (expression.kind === 176) { + expression = expression.expression; + } + return expression; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 174) { + if (container.kind === 178) { if (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 (node.parserContextFlags & 8) { - getNodeLinks(container).flags |= 4096; - getNodeLinks(node).flags |= 2048; + if (node.flags & 33554432) { + getNodeLinks(container).flags |= 8192; } } if (symbol.flags & 8388608 && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + if (languageVersion === 2 + && localOrExportSymbol.flags & 32 + && localOrExportSymbol.valueDeclaration.kind === 218 + && ts.nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { + getNodeLinks(container).flags |= 524288; + getNodeLinks(node).flags |= 1048576; + break; + } + container = ts.getContainingClass(container); + } + } checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); - checkBlockScopedBindingCapturedInLoop(node, symbol); - return getNarrowedTypeOfSymbol(getExportSymbolOfValueSymbolIfExported(symbol), node); + checkNestedBlockScopedBinding(node, symbol); + return getNarrowedTypeOfSymbol(localOrExportSymbol, node); } function isInsideFunction(node, threshold) { var current = node; @@ -16156,42 +17547,67 @@ var ts; } return false; } - function checkBlockScopedBindingCapturedInLoop(node, symbol) { + function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 244) { + symbol.valueDeclaration.parent.kind === 248) { return; } - var container; - if (symbol.flags & 32) { - container = getClassLikeDeclarationOfSymbol(symbol).parent; - } - else { - container = symbol.valueDeclaration; - while (container.kind !== 212) { - container = container.parent; - } - container = container.parent; - if (container.kind === 193) { - container = container.parent; - } - } - var inFunction = isInsideFunction(node.parent, container); + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); var current = container; + var containedInIterationStatement = false; while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { if (ts.isIterationStatement(current, false)) { - if (inFunction) { - getNodeLinks(current).flags |= 65536; - } - getNodeLinks(symbol.valueDeclaration).flags |= 16384; + containedInIterationStatement = true; break; } current = current.parent; } + if (containedInIterationStatement) { + if (usedInFunction) { + getNodeLinks(current).flags |= 65536; + } + if (container.kind === 203 && + ts.getAncestor(symbol.valueDeclaration, 216).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 2097152; + } + getNodeLinks(symbol.valueDeclaration).flags |= 262144; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 131072; + } + } + function isAssignedInBodyOfForStatement(node, container) { + var current = node; + while (current.parent.kind === 176) { + current = current.parent; + } + var isAssigned = false; + if (current.parent.kind === 185) { + isAssigned = current.parent.left === current && ts.isAssignmentOperator(current.parent.operatorToken.kind); + } + if ((current.parent.kind === 183 || current.parent.kind === 184)) { + var expr = current.parent; + isAssigned = expr.operator === 41 || expr.operator === 42; + } + if (!isAssigned) { + return false; + } + while (current !== container) { + if (current === container.statement) { + return true; + } + else { + current = current.parent; + } + } + return false; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2; - if (container.kind === 141 || container.kind === 144) { + if (container.kind === 143 || container.kind === 146) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } @@ -16199,32 +17615,65 @@ var ts; getNodeLinks(container).flags |= 4; } } + function findFirstSuperCall(n) { + if (ts.isSuperCallExpression(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullType; + } function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 174) { + if (container.kind === 146) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + } + } + if (container.kind === 178) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 218: + case 222: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 217: + case 221: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 144: + case 146: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 141: - case 140: - if (container.flags & 64) { + case 143: + case 142: + if (container.flags & 32) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 136: + case 138: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -16233,64 +17682,113 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - return container.flags & 64 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return container.flags & 32 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + } + if (ts.isInJavaScriptFile(node)) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + if (container.kind === 177) { + if (ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { + var className = container.parent + .left + .expression + .expression; + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { + return getInferredClassType(classSymbol); + } + } + } } return anyType; } + function getTypeForThisExpressionFromJSDoc(node) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === 265) { + var jsDocFunctionType = typeTag.typeExpression.type; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 268) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 138) { + if (n.kind === 140) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 168 && node.parent.expression === node; - var classDeclaration = ts.getContainingClass(node); - var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; + var isCallExpression = node.parent.kind === 172 && node.parent.expression === node; var container = ts.getSuperContainer(node, true); var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 174) { + while (container && container.kind === 178) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; - if (canUseSuperExpression) { - if ((container.flags & 64) || isCallExpression) { - nodeCheckFlag = 512; - } - else { - nodeCheckFlag = 256; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (needToCaptureLexicalThis) { - captureLexicalThis(node.parent, container); - } - } - if (!baseClassType) { - if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } if (!canUseSuperExpression) { - if (container && container.kind === 136) { + var current = node; + while (current && current !== container && current.kind !== 138) { + current = current.parent; + } + if (current && current.kind === 138) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 169)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } else { error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } return unknownType; } - if (container.kind === 144 && isInConstructorArgumentInitializer(node, container)) { + if ((container.flags & 32) || isCallExpression) { + nodeCheckFlag = 512; + } + else { + nodeCheckFlag = 256; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (container.kind === 145 && container.flags & 256) { + if (ts.isSuperPropertyOrElementAccess(node.parent) && isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096; + } + else { + getNodeLinks(container).flags |= 2048; + } + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 169) { + if (languageVersion < 2) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + return anyType; + } + } + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } + if (container.kind === 146 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; } @@ -16302,24 +17800,24 @@ var ts; return false; } if (isCallExpression) { - return container.kind === 144; + return container.kind === 146; } else { - if (container && ts.isClassLike(container.parent)) { - if (container.flags & 64) { - return container.kind === 143 || - container.kind === 142 || - container.kind === 145 || - container.kind === 146; + if (ts.isClassLike(container.parent) || container.parent.kind === 169) { + if (container.flags & 32) { + return container.kind === 145 || + container.kind === 144 || + container.kind === 147 || + container.kind === 148; } else { - return container.kind === 143 || + return container.kind === 145 || + container.kind === 144 || + container.kind === 147 || + container.kind === 148 || + container.kind === 143 || container.kind === 142 || - container.kind === 145 || - container.kind === 146 || - container.kind === 141 || - container.kind === 140 || - container.kind === 144; + container.kind === 146; } } } @@ -16354,7 +17852,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 138) { + if (declaration.kind === 140) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -16387,7 +17885,7 @@ var ts; } function isInParameterInitializerBeforeContainingFunction(node) { while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 138 && node.parent.initializer === node) { + if (node.parent.kind === 140 && node.parent.initializer === node) { return true; } node = node.parent; @@ -16396,8 +17894,8 @@ var ts; } function getContextualReturnType(functionDecl) { if (functionDecl.type || - functionDecl.kind === 144 || - functionDecl.kind === 145 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 146))) { + functionDecl.kind === 146 || + functionDecl.kind === 147 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 148))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); @@ -16416,7 +17914,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 170) { + if (template.parent.kind === 174) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -16436,6 +17934,11 @@ var ts; } return type; } + else if (operator === 51 || operator === 24) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } return undefined; } function applyToContextualType(type, mapper) { @@ -16445,8 +17948,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var current = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -16471,12 +17974,12 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } + function contextualTypeIsStringLiteralType(type) { + return !!(type.flags & 16384 ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); + } function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } - function contextualTypeHasIndexSignature(type, kind) { - return !!(type.flags & 16384 ? ts.forEach(type.types, function (t) { return getIndexTypeOfStructuredType(t, kind); }) : getIndexTypeOfStructuredType(type, kind)); - } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); if (isInsideWithStatementBody(node)) { @@ -16486,7 +17989,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element) { var objectLiteral = element.parent; - var type = getContextualType(objectLiteral); + var type = getApparentTypeOfContextualType(objectLiteral); if (type) { if (!ts.hasDynamicName(element)) { var symbolName = getSymbolOfNode(element).name; @@ -16502,7 +18005,7 @@ var ts; } function getContextualTypeForElementExpression(node) { var arrayLiteral = node.parent; - var type = getContextualType(arrayLiteral); + var type = getApparentTypeOfContextualType(arrayLiteral); if (type) { var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) @@ -16515,27 +18018,26 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForJsxExpression(expr) { - if (expr.parent.kind === 238) { - var attrib = expr.parent; - var attrsType = getJsxElementAttributesType(attrib.parent); + function getContextualTypeForJsxAttribute(attribute) { + var kind = attribute.kind; + var jsxElement = attribute.parent; + var attrsType = getJsxElementAttributesType(jsxElement); + if (attribute.kind === 242) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } - else { - return getTypeOfPropertyOfType(attrsType, attrib.name.text); - } + return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - if (expr.kind === 239) { - return getJsxElementAttributesType(expr.parent); + else if (attribute.kind === 243) { + return attrsType; } - return undefined; + ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); } - function getContextualType(node) { - var type = getContextualTypeWorker(node); + function getApparentTypeOfContextualType(node) { + var type = getContextualType(node); return type && getApparentType(type); } - function getContextualTypeWorker(node) { + function getContextualType(node) { if (isInsideWithStatementBody(node)) { return undefined; } @@ -16544,39 +18046,41 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 211: - case 138: - case 141: + case 215: case 140: - case 163: + case 143: + case 142: + case 167: return getContextualTypeForInitializerExpression(node); - case 174: - case 204: + case 178: + case 208: return getContextualTypeForReturnExpression(node); - case 184: + case 188: return getContextualTypeForYieldOperand(parent); - case 168: - case 169: - return getContextualTypeForArgument(parent, node); - case 171: - case 189: - return getTypeFromTypeNode(parent.type); - case 181: - return getContextualTypeForBinaryOperand(node); - case 245: - return getContextualTypeForObjectLiteralElement(parent); - case 164: - return getContextualTypeForElementExpression(node); - case 182: - return getContextualTypeForConditionalOperand(node); - case 190: - ts.Debug.assert(parent.parent.kind === 183); - return getContextualTypeForSubstitutionExpression(parent.parent, node); case 172: + case 173: + return getContextualTypeForArgument(parent, node); + case 175: + case 193: + return getTypeFromTypeNode(parent.type); + case 185: + return getContextualTypeForBinaryOperand(node); + case 249: + return getContextualTypeForObjectLiteralElement(parent); + case 168: + return getContextualTypeForElementExpression(node); + case 186: + return getContextualTypeForConditionalOperand(node); + case 194: + ts.Debug.assert(parent.parent.kind === 187); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 176: return getContextualType(parent); - case 240: - case 239: - return getContextualTypeForJsxExpression(parent); + case 244: + return getContextualType(parent); + case 242: + case 243: + return getContextualTypeForJsxAttribute(parent); } return undefined; } @@ -16590,7 +18094,7 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 173 || node.kind === 174; + return node.kind === 177 || node.kind === 178; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -16598,10 +18102,10 @@ var ts; : undefined; } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 || ts.isObjectLiteralMethod(node)); var type = ts.isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) - : getContextualType(node); + : getApparentTypeOfContextualType(node); if (!type) { return undefined; } @@ -16610,14 +18114,14 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { signatureList = [signature]; } - else if (!compareSignatures(signatureList[0], signature, false, true, compareTypes)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, compareTypesIdentical)) { return undefined; } else { @@ -16638,13 +18142,13 @@ var ts; } function isAssignmentTarget(node) { var parent = node.parent; - if (parent.kind === 181 && parent.operatorToken.kind === 56 && parent.left === node) { + if (parent.kind === 185 && parent.operatorToken.kind === 56 && parent.left === node) { return true; } - if (parent.kind === 245) { + if (parent.kind === 249) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 164) { + if (parent.kind === 168) { return isAssignmentTarget(parent); } return false; @@ -16654,8 +18158,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false); } function hasDefaultValue(node) { - return (node.kind === 163 && !!node.initializer) || - (node.kind === 181 && node.operatorToken.kind === 56); + return (node.kind === 167 && !!node.initializer) || + (node.kind === 185 && node.operatorToken.kind === 56); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -16664,7 +18168,7 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 185) { + if (inDestructuringPattern && e.kind === 189) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || (languageVersion >= 2 ? getElementTypeOfIterable(restArrayType, undefined) : undefined); @@ -16676,7 +18180,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 185; + hasSpreadElement = hasSpreadElement || e.kind === 189; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { @@ -16684,10 +18188,10 @@ var ts; type.pattern = node; return type; } - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { var pattern = contextualType.pattern; - if (pattern && (pattern.kind === 162 || pattern.kind === 164)) { + if (pattern && (pattern.kind === 166 || pattern.kind === 168)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -16695,7 +18199,7 @@ var ts; elementTypes.push(contextualType.elementTypes[i]); } else { - if (patternElement.kind !== 187) { + if (patternElement.kind !== 191) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -16710,13 +18214,13 @@ var ts; return createArrayType(elementTypes.length ? getUnionType(elementTypes) : undefinedType); } function isNumericName(name) { - return name.kind === 136 ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 138 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); + return isTypeAny(type) || isTypeOfKind(type, kind); } function isNumericLiteralName(name) { return (+name).toString() === name; @@ -16734,42 +18238,58 @@ var ts; } return links.resolvedType; } + function getObjectLiteralIndexInfo(node, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 || isNumericName(node.properties[i].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; + return createIndexInfo(unionType, false); + } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = {}; var propertiesArray = []; - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 161 || contextualType.pattern.kind === 165); + (contextualType.pattern.kind === 165 || contextualType.pattern.kind === 169); var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 245 || - memberDecl.kind === 246 || + if (memberDecl.kind === 249 || + memberDecl.kind === 250 || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 245) { + if (memberDecl.kind === 249) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 143) { + else if (memberDecl.kind === 145) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 246); + ts.Debug.assert(memberDecl.kind === 250); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 | 67108864 | member.flags, member.name); if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 245 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 246 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 249 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 250 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912; } + if (ts.hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } } - else if (contextualTypeHasPattern) { + else if (contextualTypeHasPattern && !(contextualType.flags & 67108864)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -16788,10 +18308,18 @@ var ts; member = prop; } else { - ts.Debug.assert(memberDecl.kind === 145 || memberDecl.kind === 146); + ts.Debug.assert(memberDecl.kind === 147 || memberDecl.kind === 148); checkAccessorDeclaration(memberDecl); } - if (!ts.hasDynamicName(memberDecl)) { + if (ts.hasDynamicName(memberDecl)) { + if (isNumericName(memberDecl.name)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + } + else { propertiesTable[member.name] = member; } propertiesArray.push(member); @@ -16808,66 +18336,33 @@ var ts; } } } - var stringIndexType = getIndexType(0); - var numberIndexType = getIndexType(1); - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); + result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064) | (patternWithComputedProperties ? 67108864 : 0); if (inDestructuringPattern) { result.pattern = node; } return result; - function getIndexType(kind) { - if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { - var propTypes = []; - for (var i = 0; i < propertiesArray.length; i++) { - var propertyDecl = node.properties[i]; - if (kind === 0 || isNumericName(propertyDecl.name)) { - var type = getTypeOfSymbol(propertiesArray[i]); - if (!ts.contains(propTypes, type)) { - propTypes.push(type); - } - } - } - var result_1 = propTypes.length ? getUnionType(propTypes) : undefinedType; - typeFlags |= result_1.flags; - return result_1; - } - return undefined; - } } function checkJsxSelfClosingElement(node) { checkJsxOpeningLikeElement(node); return jsxElementType || anyType; } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 69) { - return lhs.text === rhs.text; - } - return lhs.right.text === rhs.right.text && - tagNamesAreEquivalent(lhs.left, rhs.left); - } function checkJsxElement(node) { checkJsxOpeningLikeElement(node.openingElement); - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - error(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNode(node.openingElement.tagName)); - } - else { - getJsxElementTagSymbol(node.closingElement); - } + getJsxTagSymbol(node.closingElement); for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 240: + case 244: checkJsxExpression(child); break; - case 233: + case 237: checkJsxElement(child); break; - case 234: + case 238: checkJsxSelfClosingElement(child); break; } @@ -16878,7 +18373,7 @@ var ts; return name.indexOf("-") < 0; } function isJsxIntrinsicIdentifier(tagName) { - if (tagName.kind === 135) { + if (tagName.kind === 137) { return false; } else { @@ -16935,74 +18430,49 @@ var ts; } return type; } - function getJsxIntrinsicElementsType() { - if (!jsxIntrinsicElementsType) { - jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType; + function getJsxType(name) { + if (jsxTypes[name] === undefined) { + return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType; } - return jsxIntrinsicElementsType; + return jsxTypes[name]; } - function getJsxElementTagSymbol(node) { - var flags = 8; + function getJsxTagSymbol(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicTagSymbol(node); + } + else { + return checkExpression(node.tagName).symbol; + } + } + function getIntrinsicTagSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - links.resolvedSymbol = lookupIntrinsicTag(node); - } - else { - links.resolvedSymbol = lookupClassTag(node); - } - } - return links.resolvedSymbol; - function lookupIntrinsicTag(node) { - var intrinsicElementsType = getJsxIntrinsicElementsType(); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); if (intrinsicProp) { links.jsxFlags |= 1; - return intrinsicProp; + return links.resolvedSymbol = intrinsicProp; } var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); if (indexSignatureType) { links.jsxFlags |= 2; - return intrinsicElementsType.symbol; + return links.resolvedSymbol = intrinsicElementsType.symbol; } error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.tagName.text, "JSX." + JsxNames.IntrinsicElements); - return unknownSymbol; + return links.resolvedSymbol = unknownSymbol; } else { if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); } + return links.resolvedSymbol = unknownSymbol; } } - function lookupClassTag(node) { - var valueSymbol = resolveJsxTagName(node); - if (valueSymbol && valueSymbol !== unknownSymbol) { - links.jsxFlags |= 4; - if (valueSymbol.flags & 8388608) { - markAliasSymbolAsReferenced(valueSymbol); - } - } - return valueSymbol || unknownSymbol; - } - function resolveJsxTagName(node) { - if (node.tagName.kind === 69) { - var tag = node.tagName; - var sym = getResolvedSymbol(tag); - return sym.exportSymbol || sym; - } - else { - return checkQualifiedName(node.tagName).symbol; - } - } + return links.resolvedSymbol; } function getJsxElementInstanceType(node) { - ts.Debug.assert(!!(getNodeLinks(node).jsxFlags & 4), "Should not call getJsxElementInstanceType on non-class Element"); - var classSymbol = getJsxElementTagSymbol(node); - if (classSymbol === unknownSymbol) { - return anyType; - } - var valueType = getTypeOfSymbol(classSymbol); + var valueType = checkExpression(node.tagName); if (isTypeAny(valueType)) { return anyType; } @@ -17014,12 +18484,7 @@ var ts; return unknownType; } } - var returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); - var elemClassType = getJsxGlobalElementClassType(); - if (elemClassType) { - checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - return returnType; + return getUnionType(signatures.map(getReturnTypeOfSignature)); } function getJsxElementPropertiesName() { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536, undefined); @@ -17045,9 +18510,35 @@ var ts; function getJsxElementAttributesType(node) { var links = getNodeLinks(node); if (!links.resolvedJsxType) { - var sym = getJsxElementTagSymbol(node); - if (links.jsxFlags & 4) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1) { + return links.resolvedJsxType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2) { + return links.resolvedJsxType = getIndexInfoOfSymbol(symbol, 0).type; + } + } + else { var elemInstanceType = getJsxElementInstanceType(node); + var elemClassType = getJsxGlobalElementClassType(); + if (!elemClassType || !isTypeAssignableTo(elemInstanceType, elemClassType)) { + var elemType = checkExpression(node.tagName); + var callSignatures = elemType && getSignaturesOfType(elemType, 0); + var callSignature = callSignatures && callSignatures.length > 0 && callSignatures[0]; + var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); + var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) { + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return links.resolvedJsxType = paramType; + } + } + if (elemClassType) { + checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } @@ -17066,24 +18557,33 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return links.resolvedJsxType = attributesType; } - else if (!(attributesType.flags & 80896)) { - error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType)); + else if (attributesType.flags & 16384) { + error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return links.resolvedJsxType = anyType; } else { - return links.resolvedJsxType = attributesType; + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return links.resolvedJsxType = apparentAttributesType; } } } - else if (links.jsxFlags & 1) { - return links.resolvedJsxType = getTypeOfSymbol(sym); - } - else if (links.jsxFlags & 2) { - return links.resolvedJsxType = getIndexTypeOfSymbol(sym, 0); - } - else { - return links.resolvedJsxType = anyType; - } + return links.resolvedJsxType = unknownType; } return links.resolvedJsxType; } @@ -17099,7 +18599,7 @@ var ts; return jsxElementClassType; } function getJsxIntrinsicTagNames() { - var intrinsics = getJsxIntrinsicElementsType(); + var intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } function checkJsxPreconditions(errorNode) { @@ -17115,21 +18615,21 @@ var ts; function checkJsxOpeningLikeElement(node) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - if (compilerOptions.jsx === 2) { - var reactSym = resolveName(node.tagName, "React", 107455, ts.Diagnostics.Cannot_find_name_0, "React"); - if (reactSym) { - getSymbolLinks(reactSym).referenced = true; - } + var reactRefErr = compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = {}; var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 238) { + if (node.attributes[i].kind === 242) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 239); + ts.Debug.assert(node.attributes[i].kind === 243); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -17155,19 +18655,19 @@ var ts; } } function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 141; + return s.valueDeclaration ? s.valueDeclaration.kind : 143; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 8 | 64 : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; } function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationFlagsFromSymbol(prop); - var declaringClass = getDeclaredTypeOfSymbol(prop.parent); + var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); if (left.kind === 95) { - var errorNode = node.kind === 166 ? + var errorNode = node.kind === 170 ? node.name : node.right; - if (getDeclarationKindFromSymbol(prop) !== 143) { + if (languageVersion < 2 && getDeclarationKindFromSymbol(prop) !== 145) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -17176,12 +18676,12 @@ var ts; return false; } } - if (!(flags & (16 | 32))) { + if (!(flags & (8 | 16))) { return true; } var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; - if (flags & 16) { + if (flags & 8) { if (declaringClass !== enclosingClass) { error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; @@ -17195,7 +18695,7 @@ var ts; error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); return false; } - if (flags & 64) { + if (flags & 32) { return true; } if (type.flags & 33554432) { @@ -17236,7 +18736,7 @@ var ts; return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 166 + var left = node.kind === 170 ? node.expression : node.left; var type = checkExpression(left); @@ -17248,10 +18748,47 @@ var ts; } return true; } + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 216) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 69) { + return getResolvedSymbol(initializer); + } + return undefined; + } + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); + } + function isForInVariableForNumericPropertyNames(expr) { + var e = skipParenthesizedNodes(expr); + if (e.kind === 69) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 204 && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(checkExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } function checkIndexedAccess(node) { if (!node.argumentExpression) { - var sourceFile = getSourceFile(node); - if (node.parent.kind === 169 && node.parent.expression === node) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 173 && 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); @@ -17288,18 +18825,22 @@ var ts; } } if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 | 132 | 16777216)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132)) { - var numberIndexType = getIndexTypeOfType(objectType, 1); - if (numberIndexType) { - return numberIndexType; + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + var numberIndexInfo = getIndexInfoOfType(objectType, 1); + if (numberIndexInfo) { + getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; + return numberIndexInfo.type; } } - var stringIndexType = getIndexTypeOfType(objectType, 0); - if (stringIndexType) { - return stringIndexType; + var stringIndexInfo = getIndexInfoOfType(objectType, 0); + if (stringIndexInfo) { + getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; + return stringIndexInfo.type; } if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); + error(node, getIndexTypeOfType(objectType, 1) ? + ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : + ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } return anyType; } @@ -17310,7 +18851,7 @@ var ts; if (indexArgumentExpression.kind === 9 || indexArgumentExpression.kind === 8) { return indexArgumentExpression.text; } - if (indexArgumentExpression.kind === 167 || indexArgumentExpression.kind === 166) { + if (indexArgumentExpression.kind === 171 || indexArgumentExpression.kind === 170) { var value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); @@ -17353,10 +18894,10 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 170) { + if (node.kind === 174) { checkExpression(node.template); } - else if (node.kind !== 139) { + else if (node.kind !== 141) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -17378,19 +18919,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_5 = signature.declaration && signature.declaration.parent; + var parent_6 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_5 === lastParent) { + if (lastParent && parent_6 === lastParent) { index++; } else { - lastParent = parent_5; + lastParent = parent_6; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_5; + lastParent = parent_6; } lastSymbol = symbol; if (signature.hasStringLiterals) { @@ -17407,7 +18948,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 185) { + if (arg && arg.kind === 189) { return i; } } @@ -17419,11 +18960,11 @@ var ts; var callIsIncomplete; var isDecorator; var spreadArgIndex = -1; - if (node.kind === 170) { + if (node.kind === 174) { var tagExpression = node; adjustedArgCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 183) { + if (tagExpression.template.kind === 187) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -17435,7 +18976,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 139) { + else if (node.kind === 141) { isDecorator = true; typeArguments = undefined; adjustedArgCount = getEffectiveArgumentCount(node, undefined, signature); @@ -17443,7 +18984,7 @@ var ts; else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 169); + ts.Debug.assert(callExpression.kind === 173); return signature.minArgumentCount === 0; } adjustedArgCount = callExpression.arguments.hasTrailingComma ? args.length + 1 : args.length; @@ -17469,7 +19010,7 @@ var ts; if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && - resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) { + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { return resolved.callSignatures[0]; } } @@ -17484,7 +19025,7 @@ var ts; } function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; - var inferenceMapper = createInferenceMapper(context); + var inferenceMapper = getInferenceMapper(context); for (var i = 0; i < typeParameters.length; i++) { if (!context.inferences[i].isFixed) { context.inferredTypes[i] = undefined; @@ -17496,7 +19037,7 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 187) { + if (arg === undefined || arg.kind !== 191) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { @@ -17517,13 +19058,11 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; + var mapper; for (var i = 0; i < typeParameters.length; i++) { - var typeArgNode = typeArguments[i]; - var typeArgument = getTypeFromTypeNode(typeArgNode); - typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { @@ -17533,7 +19072,11 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); typeArgumentHeadMessage = headMessage; } - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); } } } @@ -17543,12 +19086,12 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 187) { + if (arg === undefined || arg.kind !== 191) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { argType = arg.kind === 9 && !reportErrors - ? getStringLiteralType(arg) + ? getStringLiteralTypeForText(arg.text) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; @@ -17562,16 +19105,16 @@ var ts; } function getEffectiveCallArguments(node) { var args; - if (node.kind === 170) { + if (node.kind === 174) { var template = node.template; args = [undefined]; - if (template.kind === 183) { + if (template.kind === 187) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } - else if (node.kind === 139) { + else if (node.kind === 141) { return undefined; } else { @@ -17580,21 +19123,21 @@ var ts; return args; } function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 139) { + if (node.kind === 141) { switch (node.parent.kind) { - case 214: - case 186: + case 218: + case 190: return 1; - case 141: - return 2; case 143: + return 2; case 145: - case 146: + case 147: + case 148: if (languageVersion === 0) { return 2; } return signature.parameters.length >= 3 ? 3 : 2; - case 138: + case 140: return 3; } } @@ -17603,50 +19146,50 @@ var ts; } } function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 218) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 138) { + if (node.kind === 140) { node = node.parent; - if (node.kind === 144) { + if (node.kind === 146) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 141 || - node.kind === 143 || + if (node.kind === 143 || node.kind === 145 || - node.kind === 146) { + node.kind === 147 || + node.kind === 148) { return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); return unknownType; } function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 218) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 138) { + if (node.kind === 140) { node = node.parent; - if (node.kind === 144) { + if (node.kind === 146) { return anyType; } } - if (node.kind === 141 || - node.kind === 143 || + if (node.kind === 143 || node.kind === 145 || - node.kind === 146) { + node.kind === 147 || + node.kind === 148) { var element = node; switch (element.name.kind) { case 69: case 8: case 9: - return getStringLiteralType(element.name); - case 136: + return getStringLiteralTypeForText(element.name.text); + case 138: var nameType = checkComputedPropertyName(element.name); - if (allConstituentTypesHaveKind(nameType, 16777216)) { + if (isTypeOfKind(nameType, 16777216)) { return nameType; } else { @@ -17661,20 +19204,20 @@ var ts; return unknownType; } function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 218) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 138) { + if (node.kind === 140) { return numberType; } - if (node.kind === 141) { + if (node.kind === 143) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 143 || - node.kind === 145 || - node.kind === 146) { + if (node.kind === 145 || + node.kind === 147 || + node.kind === 148) { var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } @@ -17695,26 +19238,26 @@ var ts; return unknownType; } function getEffectiveArgumentType(node, argIndex, arg) { - if (node.kind === 139) { + if (node.kind === 141) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 170) { + else if (argIndex === 0 && node.kind === 174) { return globalTemplateStringsArrayType; } return undefined; } function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 139 || - (argIndex === 0 && node.kind === 170)) { + if (node.kind === 141 || + (argIndex === 0 && node.kind === 174)) { return undefined; } return args[argIndex]; } function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 139) { + if (node.kind === 141) { return node.expression; } - else if (argIndex === 0 && node.kind === 170) { + else if (argIndex === 0 && node.kind === 174) { return node.template; } else { @@ -17722,8 +19265,8 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 170; - var isDecorator = node.kind === 139; + var isTaggedTemplate = node.kind === 174; + var isDecorator = node.kind === 141; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; @@ -17770,7 +19313,8 @@ var ts; } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true, headMessage); + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -17822,7 +19366,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { @@ -17869,8 +19413,10 @@ var ts; var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); - var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); - return resolveCall(node, baseConstructors, candidatesOutArray); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); + } } return resolveUntypedCall(node); } @@ -17923,6 +19469,9 @@ var ts; } var constructSignatures = getSignaturesOfType(expressionType, 1); if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } return resolveCall(node, constructSignatures, candidatesOutArray); } var callSignatures = getSignaturesOfType(expressionType, 0); @@ -17936,6 +19485,28 @@ var ts; error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); return resolveErrorCall(node); } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var flags = declaration.flags; + if (!(flags & (8 | 16))) { + return true; + } + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + if (flags & 8) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (flags & 16) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -17954,16 +19525,16 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 214: - case 186: + case 218: + case 190: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 138: + case 140: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 141: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 143: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 145: - case 146: + case 147: + case 148: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -17991,16 +19562,16 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 168) { + if (node.kind === 172) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 169) { + else if (node.kind === 173) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 170) { + else if (node.kind === 174) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } - else if (node.kind === 139) { + else if (node.kind === 141) { links.resolvedSignature = resolveDecorator(node, candidatesOutArray); } else { @@ -18009,24 +19580,39 @@ var ts; } return links.resolvedSignature; } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined); + } + return links.inferredClassType; + } function checkCallExpression(node) { checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 95) { return voidType; } - if (node.kind === 169) { + if (node.kind === 173) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 144 && - declaration.kind !== 148 && - declaration.kind !== 153) { - if (compilerOptions.noImplicitAny) { + declaration.kind !== 146 && + declaration.kind !== 150 && + declaration.kind !== 155 && + !ts.isJSDocConstructSignature(declaration)) { + var funcSymbol = checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16)) { + return getInferredClassType(funcSymbol); + } + else if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; } } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, true)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } return getReturnTypeOfSignature(signature); } function checkTaggedTemplateExpression(node) { @@ -18037,7 +19623,9 @@ var ts; var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); - if (!(isTypeAssignableTo(targetType, widenedType))) { + var bothAreStringLike = maybeTypeOfKind(targetType, 258) && + maybeTypeOfKind(widenedType, 258); + if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } } @@ -18065,7 +19653,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187) { + if (element.kind !== 191) { if (element.name.kind === 69) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -18084,6 +19672,13 @@ var ts; inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); } } + function getReturnTypeFromJSDocComment(func) { + var returnTag = ts.getJSDocReturnTag(func); + if (returnTag && returnTag.typeExpression) { + return getTypeFromTypeNode(returnTag.typeExpression.type); + } + return undefined; + } function createPromiseType(promisedType) { var globalPromiseType = getGlobalPromiseType(); if (globalPromiseType !== emptyGenericType) { @@ -18099,7 +19694,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 192) { + if (func.body.kind !== 196) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -18142,7 +19737,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + return getUnionType(types); } } if (funcIsGenerator) { @@ -18201,34 +19796,37 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType === voidType || isTypeAny(returnType)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 || !(func.flags & 524288)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 196 || !(func.flags & 32768)) { return; } - if (func.flags & 1048576) { - if (compilerOptions.noImplicitReturns) { - error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { + var hasExplicitReturn = func.flags & 65536; + if (returnType && !hasExplicitReturn) { error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + var inferredReturnType = hasExplicitReturn + ? getReturnTypeOfSignature(getSignatureFromDeclaration(func)) + : voidType; + if (inferredReturnType === voidType || isTypeAny(inferredReturnType)) { + return; + } + } + error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 || ts.isObjectLiteralMethod(node)); var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 173) { + if (!hasGrammarError && node.kind === 177) { checkGrammarForGenerator(node); } if (contextualMapper === identityMapper && isContextSensitive(node)) { return anyFunctionType; } - var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } var links = getNodeLinks(node); var type = getTypeOfSymbol(node.symbol); var contextSensitive = isContextSensitive(node); @@ -18252,48 +19850,41 @@ var ts; } if (!contextChecked) { checkSignatureDeclaration(node); + checkNodeDeferred(node); } } } - if (produceDiagnostics && node.kind !== 143 && node.kind !== 142) { + if (produceDiagnostics && node.kind !== 145 && node.kind !== 144) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } - function checkFunctionExpressionOrObjectLiteralMethodBody(node) { - ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 145 || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } - var returnType = node.type && getTypeFromTypeNode(node.type); - var promisedType; - if (returnType && isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - if (returnType && !node.asteriskToken) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + if (!node.asteriskToken) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { if (!node.type) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 192) { + if (node.body.kind === 196) { checkSourceElement(node.body); } else { var exprType = checkExpression(node.body); - if (returnType) { + if (returnOrPromisedType) { if (isAsync) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); - checkTypeAssignableTo(awaitedType, promisedType, node.body); + checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } else { - checkTypeAssignableTo(exprType, returnType, node.body); + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } - checkFunctionAndClassExpressionBodies(node.body); } } } @@ -18304,59 +19895,62 @@ var ts; } return true; } - function checkReferenceExpression(n, invalidReferenceMessage, constantVariableMessage) { - function findSymbol(n) { - var symbol = getNodeLinks(n).resolvedSymbol; - return symbol && getExportSymbolOfValueSymbolIfExported(symbol); + function isReadonlySymbol(symbol) { + return symbol.flags & 4 && (getDeclarationFlagsFromSymbol(symbol) & 64) !== 0 || + symbol.flags & 3 && (getDeclarationFlagsFromSymbol(symbol) & 2048) !== 0 || + symbol.flags & 98304 && !(symbol.flags & 65536) || + (symbol.flags & 8) !== 0; + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + if (symbol.flags & 4 && + (expr.kind === 170 || expr.kind === 171) && + expr.expression.kind === 97) { + var func = ts.getContainingFunction(expr); + return !(func && func.kind === 146 && func.parent === symbol.valueDeclaration.parent); + } + return true; } - function isReferenceOrErrorExpression(n) { - switch (n.kind) { - case 69: { - var symbol = findSymbol(n); - return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3) !== 0; + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 170 || expr.kind === 171) { + var node = skipParenthesizedNodes(expr.expression); + if (node.kind === 69) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 8388608) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return declaration && declaration.kind === 228; } - case 166: { - var symbol = findSymbol(n); - return !symbol || symbol === unknownSymbol || (symbol.flags & ~8) !== 0; - } - case 167: - return true; - case 172: - return isReferenceOrErrorExpression(n.expression); - default: - return false; } } - function isConstVariableReference(n) { - switch (n.kind) { - case 69: - case 166: { - var symbol = findSymbol(n); - return symbol && (symbol.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384) !== 0; - } - case 167: { - var index = n.argumentExpression; - var symbol = findSymbol(n.expression); - if (symbol && index && index.kind === 9) { - var name_12 = index.text; - var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_12); - return prop && (prop.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 16384) !== 0; - } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage, constantVariableMessage) { + var node = skipParenthesizedNodes(expr); + if (node.kind !== 69 && node.kind !== 170 && node.kind !== 171) { + error(expr, invalidReferenceMessage); + return false; + } + var links = getNodeLinks(node); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol) { + if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { + if (node.kind === 69 && !(symbol.flags & 3)) { + error(expr, invalidReferenceMessage); return false; } - case 172: - return isConstVariableReference(n.expression); - default: + if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { + error(expr, constantVariableMessage); return false; + } } } - if (!isReferenceOrErrorExpression(n)) { - error(n, invalidReferenceMessage); - return false; - } - if (isConstVariableReference(n)) { - error(n, constantVariableMessage); - return false; + else if (node.kind === 171) { + if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { + error(expr, constantVariableMessage); + return false; + } } return true; } @@ -18374,7 +19968,7 @@ var ts; } function checkAwaitExpression(node) { if (produceDiagnostics) { - if (!(node.parserContextFlags & 8)) { + if (!(node.flags & 33554432)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -18390,7 +19984,7 @@ var ts; case 35: case 36: case 50: - if (someConstituentTypeHasKind(operandType, 16777216)) { + if (maybeTypeOfKind(operandType, 16777216)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -18400,7 +19994,7 @@ var ts; case 42: var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); } return numberType; } @@ -18410,40 +20004,48 @@ var ts; 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) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); } return numberType; } - function someConstituentTypeHasKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 49152) { - var types = type.types; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var current = types_9[_i]; - if (current.flags & kind) { - return true; - } - } - return false; - } - return false; - } - function allConstituentTypesHaveKind(type, kind) { + function maybeTypeOfKind(type, kind) { if (type.flags & kind) { return true; } if (type.flags & 49152) { var types = type.types; for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var current = types_10[_i]; - if (!(current.flags & kind)) { + var t = types_10[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 16384) { + var types = type.types; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + if (!isTypeOfKind(t, kind)) { return false; } } return true; } + if (type.flags & 32768) { + var types = type.types; + for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { + var t = types_12[_a]; + if (isTypeOfKind(t, kind)) { + return true; + } + } + } return false; } function isConstEnumObjectType(type) { @@ -18453,7 +20055,7 @@ var ts; return (symbol.flags & 128) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { - if (allConstituentTypesHaveKind(leftType, 16777726)) { + if (isTypeOfKind(leftType, 16777726)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -18474,23 +20076,30 @@ var ts; var properties = node.properties; for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var p = properties_3[_i]; - if (p.kind === 245 || p.kind === 246) { - var name_13 = p.name; + if (p.kind === 249 || p.kind === 250) { + var name_12 = p.name; + if (name_12.kind === 138) { + checkComputedPropertyName(name_12); + } + if (isComputedNonLiteralName(name_12)) { + continue; + } + var text = getTextOfPropertyName(name_12); var type = isTypeAny(sourceType) ? sourceType - : getTypeOfPropertyOfType(sourceType, name_13.text) || - isNumericLiteralName(name_13.text) && getIndexTypeOfType(sourceType, 1) || + : getTypeOfPropertyOfType(sourceType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1) || getIndexTypeOfType(sourceType, 0); if (type) { - if (p.kind === 246) { + if (p.kind === 250) { checkDestructuringAssignment(p, type); } else { - checkDestructuringAssignment(p.initializer || name_13, type); + checkDestructuringAssignment(p.initializer, type); } } else { - error(name_13, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_13)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_12)); } } else { @@ -18504,8 +20113,8 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187) { - if (e.kind !== 185) { + if (e.kind !== 191) { + if (e.kind !== 189) { var propName = "" + i; var type = isTypeAny(sourceType) ? sourceType @@ -18530,7 +20139,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 181 && restExpression.operatorToken.kind === 56) { + if (restExpression.kind === 185 && restExpression.operatorToken.kind === 56) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -18544,7 +20153,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 246) { + if (exprOrAssignment.kind === 250) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -18554,21 +20163,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 181 && target.operatorToken.kind === 56) { + if (target.kind === 185 && target.operatorToken.kind === 56) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 165) { + if (target.kind === 169) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 164) { + if (target.kind === 168) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); } function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant)) { + if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { checkTypeAssignableTo(sourceType, targetType, target, undefined); } return sourceType; @@ -18578,7 +20187,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 && (left.kind === 165 || left.kind === 164)) { + if (operator === 56 && (left.kind === 169 || left.kind === 168)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); @@ -18631,11 +20240,11 @@ var ts; if (rightType.flags & (32 | 64)) rightType = leftType; var resultType; - if (allConstituentTypesHaveKind(leftType, 132) && allConstituentTypesHaveKind(rightType, 132)) { + if (isTypeOfKind(leftType, 132) && isTypeOfKind(rightType, 132)) { resultType = numberType; } else { - if (allConstituentTypesHaveKind(leftType, 258) || allConstituentTypesHaveKind(rightType, 258)) { + if (isTypeOfKind(leftType, 258) || isTypeOfKind(rightType, 258)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -18664,6 +20273,9 @@ var ts; case 31: case 32: case 33: + if (maybeTypeOfKind(leftType, 258) && maybeTypeOfKind(rightType, 258)) { + return booleanType; + } if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) { reportOperatorError(); } @@ -18683,8 +20295,8 @@ var ts; return rightType; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 16777216) ? left : - someConstituentTypeHasKind(rightType, 16777216) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216) ? left : + maybeTypeOfKind(rightType, 16777216) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -18709,7 +20321,7 @@ var ts; } function checkAssignmentOperator(valueType) { if (produceDiagnostics && operator >= 56 && operator <= 68) { - var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); if (ok) { checkTypeAssignableTo(valueType, leftType, left, undefined); } @@ -18736,7 +20348,7 @@ var ts; } function checkYieldExpression(node) { if (produceDiagnostics) { - if (!(node.parserContextFlags & 2) || isYieldExpressionInClass(node)) { + if (!(node.flags & 8388608) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -18771,6 +20383,13 @@ var ts; var type2 = checkExpression(node.whenFalse, contextualMapper); return getUnionType([type1, type2]); } + function checkStringLiteralExpression(node) { + var contextualType = getContextualType(node); + if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + return getStringLiteralTypeForText(node.text); + } + return stringType; + } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { checkExpression(templateSpan.expression); @@ -18792,14 +20411,14 @@ var ts; return links.resolvedType; } function checkPropertyAssignment(node, contextualMapper) { - if (node.name.kind === 136) { + if (node.name.kind === 138) { checkComputedPropertyName(node.name); } return checkExpression(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); - if (node.name.kind === 136) { + if (node.name.kind === 138) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -18809,7 +20428,7 @@ var ts; if (isInferentialContext(contextualMapper)) { var signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); if (contextualType) { var contextualSignature = getSingleCallSignature(contextualType); if (contextualSignature && !contextualSignature.typeParameters) { @@ -18822,7 +20441,7 @@ var ts; } function checkExpression(node, contextualMapper) { var type; - if (node.kind === 135) { + if (node.kind === 137) { type = checkQualifiedName(node); } else { @@ -18830,9 +20449,9 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 166 && node.parent.expression === node) || - (node.parent.kind === 167 && node.parent.expression === node) || - ((node.kind === 69 || node.kind === 135) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 170 && node.parent.expression === node) || + (node.parent.kind === 171 && node.parent.expression === node) || + ((node.kind === 69 || node.kind === 137) && 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); } @@ -18858,65 +20477,66 @@ var ts; return booleanType; case 8: return checkNumericLiteral(node); - case 183: + case 187: return checkTemplateExpression(node); case 9: + return checkStringLiteralExpression(node); case 11: return stringType; case 10: return globalRegExpType; - case 164: - return checkArrayLiteral(node, contextualMapper); - case 165: - return checkObjectLiteral(node, contextualMapper); - case 166: - return checkPropertyAccessExpression(node); - case 167: - return checkIndexedAccess(node); case 168: + return checkArrayLiteral(node, contextualMapper); case 169: - return checkCallExpression(node); + return checkObjectLiteral(node, contextualMapper); case 170: - return checkTaggedTemplateExpression(node); - case 172: - return checkExpression(node.expression, contextualMapper); - case 186: - return checkClassExpression(node); - case 173: - case 174: - return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 176: - return checkTypeOfExpression(node); + return checkPropertyAccessExpression(node); case 171: - case 189: - return checkAssertion(node); - case 175: - return checkDeleteExpression(node); + return checkIndexedAccess(node); + case 172: + case 173: + return checkCallExpression(node); + case 174: + return checkTaggedTemplateExpression(node); + case 176: + return checkExpression(node.expression, contextualMapper); + case 190: + return checkClassExpression(node); case 177: - return checkVoidExpression(node); case 178: - return checkAwaitExpression(node); - case 179: - return checkPrefixUnaryExpression(node); + return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); case 180: - return checkPostfixUnaryExpression(node); + return checkTypeOfExpression(node); + case 175: + case 193: + return checkAssertion(node); + case 179: + return checkDeleteExpression(node); case 181: - return checkBinaryExpression(node, contextualMapper); + return checkVoidExpression(node); case 182: - return checkConditionalExpression(node, contextualMapper); - case 185: - return checkSpreadElementExpression(node, contextualMapper); - case 187: - return undefinedType; + return checkAwaitExpression(node); + case 183: + return checkPrefixUnaryExpression(node); case 184: + return checkPostfixUnaryExpression(node); + case 185: + return checkBinaryExpression(node, contextualMapper); + case 186: + return checkConditionalExpression(node, contextualMapper); + case 189: + return checkSpreadElementExpression(node, contextualMapper); + case 191: + return undefinedType; + case 188: return checkYieldExpression(node); - case 240: + case 244: return checkJsxExpression(node); - case 233: + case 237: return checkJsxElement(node); - case 234: + case 238: return checkJsxSelfClosingElement(node); - case 235: + case 239: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -18926,8 +20546,8 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); + getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node))); if (produceDiagnostics) { - checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } @@ -18935,9 +20555,9 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 56) { + if (node.flags & 28) { func = ts.getContainingFunction(node); - if (!(func.kind === 144 && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 146 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -18952,9 +20572,9 @@ var ts; if (!node.asteriskToken || !node.body) { return false; } - return node.kind === 143 || - node.kind === 213 || - node.kind === 173; + return node.kind === 145 || + node.kind === 217 || + node.kind === 177; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { @@ -18968,90 +20588,98 @@ var ts; } return -1; } - function isInLegalTypePredicatePosition(node) { + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name_13 = _a[_i].name; + if (ts.isBindingPattern(name_13) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_13, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { switch (node.parent.kind) { - case 174: - case 147: - case 213: - case 173: - case 152: - case 143: - case 142: - return node === node.parent.type; + case 178: + case 149: + case 217: + case 177: + case 154: + case 145: + case 144: + var parent_7 = node.parent; + if (node === parent_7.type) { + return parent_7; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var name_14 = _a[_i].name; + if (name_14.kind === 69 && + name_14.text === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name_14.kind === 166 || + name_14.kind === 165) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_14, predicateVariableNode, predicateVariableName)) { + return true; + } + } } - return false; } function checkSignatureDeclaration(node) { - if (node.kind === 149) { + if (node.kind === 151) { checkGrammarIndexSignature(node); } - else if (node.kind === 152 || node.kind === 213 || node.kind === 153 || - node.kind === 147 || node.kind === 144 || - node.kind === 148) { + else if (node.kind === 154 || node.kind === 217 || node.kind === 155 || + node.kind === 149 || node.kind === 146 || + node.kind === 150) { checkGrammarFunctionLikeDeclaration(node); } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { - if (node.type.kind === 150) { - 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, getTypeOfNode(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 === 161 || - param.name.kind === 162) { - (function checkBindingPattern(pattern) { - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (element.name.kind === 69 && - 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 === 162 || - element.name.kind === 161) { - 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); - } + checkSourceElement(node.type); } if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 148: + case 150: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 147: + case 149: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -19068,12 +20696,14 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } + else if (ts.isAsyncFunctionLike(node)) { + checkAsyncFunctionReturnType(node); + } } } - checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 215) { + if (node.kind === 219) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -19088,7 +20718,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 130: + case 131: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -19096,7 +20726,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 128: + case 129: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -19115,7 +20745,7 @@ var ts; } function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); - checkFunctionLikeDeclaration(node); + checkFunctionOrMethodDeclaration(node); if (node.flags & 128 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } @@ -19135,14 +20765,11 @@ var ts; if (!produceDiagnostics) { return; } - function isSuperCallExpression(n) { - return n.kind === 168 && n.expression.kind === 95; - } function containsSuperCallAsComputedPropertyName(n) { return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (isSuperCallExpression(n)) { + if (ts.isSuperCallExpression(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -19157,32 +20784,31 @@ var ts; if (n.kind === 97) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 173 && n.kind !== 213) { + else if (n.kind !== 177 && n.kind !== 217) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 141 && - !(n.flags & 64) && + return n.kind === 143 && + !(n.flags & 32) && !!n.initializer; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { - var containingClassSymbol = getSymbolOfNode(containingClassDecl); - var containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); - var baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); - if (containsSuperCall(node.body)) { - if (baseConstructorType === nullType) { - error(node, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & (8 | 16 | 32); }); + ts.forEach(node.parameters, function (p) { return p.flags & (4 | 8 | 16); }); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 195 && isSuperCallExpression(statement.expression)) { + if (statement.kind === 199 && ts.isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; } @@ -19193,12 +20819,9 @@ var ts; if (!superCallStatement) { error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); } - else { - markThisReferencesAsErrors(superCallStatement.expression); - } } } - else if (baseConstructorType !== nullType) { + else if (!classExtendsNull) { error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); } } @@ -19206,9 +20829,11 @@ var ts; function checkAccessorDeclaration(node) { if (produceDiagnostics) { checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (node.kind === 145) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288)) { - if (node.flags & 1048576) { + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 147) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768)) { + if (node.flags & 65536) { if (compilerOptions.noImplicitReturns) { error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -19218,13 +20843,19 @@ var ts; } } } + if (node.name.kind === 138) { + checkComputedPropertyName(node.name); + } if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 145 ? 146 : 145; + var otherKind = node.kind === 147 ? 148 : 147; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 56) !== (otherAccessor.flags & 56))) { + if (((node.flags & 28) !== (otherAccessor.flags & 28))) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } + if (((node.flags & 128) !== (otherAccessor.flags & 128))) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } var currentAccessorType = getAnnotatedAccessorType(node); var otherAccessorType = getAnnotatedAccessorType(otherAccessor); if (currentAccessorType && otherAccessorType) { @@ -19236,18 +20867,32 @@ var ts; } getTypeOfAccessors(getSymbolOfNode(node)); } - checkFunctionLikeDeclaration(node); + if (node.parent.kind !== 169) { + checkSourceElement(node.body); + } + else { + checkNodeDeferred(node); + } + } + function checkAccessorDeferred(node) { + checkSourceElement(node.body); } function checkMissingDeclaration(node) { checkDecorators(node); } - function checkTypeArgumentConstraints(typeParameters, typeArguments) { + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var typeArguments; + var mapper; var result = true; for (var i = 0; i < typeParameters.length; i++) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { + if (!typeArguments) { + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + mapper = createTypeMapper(typeParameters, typeArguments); + } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -19289,49 +20934,18 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 16) && ts.isInAmbientContext(node); - } - function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { - if (!produceDiagnostics) { - return; - } - var signature = getSignatureFromDeclaration(signatureDeclarationNode); - if (!signature.hasStringLiterals) { - return; - } - if (ts.nodeIsPresent(signatureDeclarationNode.body)) { - error(signatureDeclarationNode, ts.Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type); - return; - } - var signaturesToCheck; - if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 215) { - ts.Debug.assert(signatureDeclarationNode.kind === 147 || signatureDeclarationNode.kind === 148); - var signatureKind = signatureDeclarationNode.kind === 147 ? 0 : 1; - var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); - var containingType = getDeclaredTypeOfSymbol(containingSymbol); - signaturesToCheck = getSignaturesOfType(containingType, signatureKind); - } - else { - signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); - } - for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { - var otherSignature = signaturesToCheck_1[_i]; - if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { - return; - } - } - error(signatureDeclarationNode, ts.Diagnostics.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature); + return (node.flags & 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedNodeFlags(n); - if (n.parent.kind !== 215 && - n.parent.kind !== 214 && - n.parent.kind !== 186 && + if (n.parent.kind !== 219 && + n.parent.kind !== 218 && + n.parent.kind !== 190 && ts.isInAmbientContext(n)) { - if (!(flags & 4)) { - flags |= 2; + if (!(flags & 2)) { + flags |= 1; } - flags |= 4; + flags |= 2; } return flags & flagsToCheck; } @@ -19349,17 +20963,17 @@ var ts; var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); + if (deviation & 1) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } - else if (deviation & 4) { + else if (deviation & 2) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (16 | 32)) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + else if (deviation & (8 | 16)) { + error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -19375,7 +20989,7 @@ var ts; }); } } - var flagsToCheck = 2 | 4 | 16 | 32 | 128; + var flagsToCheck = 1 | 2 | 8 | 16 | 128; var someNodeFlags = 0; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; @@ -19399,14 +21013,16 @@ var ts; seen = c === node; } }); - if (subsequentNode) { + if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - ts.Debug.assert(node.kind === 143 || node.kind === 142); - ts.Debug.assert((node.flags & 64) !== (subsequentNode.flags & 64)); - var diagnostic = node.flags & 64 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); + var reportError = (node.kind === 145 || node.kind === 144) && + (node.flags & 32) !== (subsequentNode.flags & 32); + if (reportError) { + var diagnostic = node.flags & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } return; } else if (ts.nodeIsPresent(subsequentNode.body)) { @@ -19435,11 +21051,11 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 215 || node.parent.kind === 155 || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 219 || node.parent.kind === 157 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 213 || node.kind === 143 || node.kind === 142 || node.kind === 144) { + if (node.kind === 217 || node.kind === 145 || node.kind === 144 || node.kind === 146) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -19490,13 +21106,11 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - if (!bodySignature.hasStringLiterals) { - for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { - var signature = signatures_3[_a]; - if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { - error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); - break; - } + for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { + var signature = signatures_3[_a]; + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; } } } @@ -19522,8 +21136,8 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var d = _a[_i]; var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 2 | 512); - if (effectiveDeclarationFlags & 2) { + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 512); + if (effectiveDeclarationFlags & 1) { if (effectiveDeclarationFlags & 512) { defaultExportedDeclarationSpaces |= declarationSpaces; } @@ -19552,16 +21166,16 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 215: + case 219: return 2097152; - case 218: - return d.name.kind === 9 || ts.getModuleInstanceState(d) !== 0 + case 222: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 ? 4194304 | 1048576 : 4194304; - case 214: - case 217: - return 2097152 | 1048576; + case 218: case 221: + return 2097152 | 1048576; + case 225: var result = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); @@ -19651,7 +21265,23 @@ var ts; } } } + function checkCorrectPromiseType(returnType, location) { + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType === emptyGenericType + || globalPromiseType === getTargetType(returnType)) { + return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + } + error(location, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } function checkAsyncFunctionReturnType(node) { + if (languageVersion >= 2) { + var returnType = getTypeFromTypeNode(node.type); + return checkCorrectPromiseType(returnType, node.type); + } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { return unknownType; @@ -19668,15 +21298,16 @@ var ts; error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } + checkReturnTypeAnnotationAsExpression(node); var promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } var promiseName = ts.getEntityNameFromTypeNode(node.type); - var root = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, root.text, 107455); + var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); + var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455); if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, getFullyQualifiedName(promiseConstructor)); + error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); @@ -19691,22 +21322,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 214: + case 218: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 138: + case 140: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 141: + case 143: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 143: case 145: - case 146: + case 147: + case 148: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -19715,9 +21346,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function checkTypeNodeAsExpression(node) { - if (node && node.kind === 151) { + if (node && node.kind === 153) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 151 ? 793056 : 1536; + var meaning = root.parent.kind === 153 ? 793056 : 1536; var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); if (rootSymbol && rootSymbol.flags & 8388608) { var aliasTarget = resolveAlias(rootSymbol); @@ -19728,23 +21359,10 @@ var ts; } } function checkTypeAnnotationAsExpression(node) { - switch (node.kind) { - case 141: - checkTypeNodeAsExpression(node.type); - break; - case 138: - checkTypeNodeAsExpression(node.type); - break; - case 143: - checkTypeNodeAsExpression(node.type); - break; - case 145: - checkTypeNodeAsExpression(node.type); - break; - case 146: - checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node)); - break; - } + checkTypeNodeAsExpression(node.type); + } + function checkReturnTypeAnnotationAsExpression(node) { + checkTypeNodeAsExpression(node.type); } function checkParameterTypeAnnotationsAsExpressions(node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -19760,54 +21378,51 @@ var ts; 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); + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } if (compilerOptions.emitDecoratorMetadata) { switch (node.kind) { - case 214: + case 218: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; - case 143: - checkParameterTypeAnnotationsAsExpressions(node); - case 146: case 145: - case 141: - case 138: + case 147: + case 148: + checkParameterTypeAnnotationsAsExpressions(node); + checkReturnTypeAnnotationAsExpression(node); + break; + case 143: + case 140: checkTypeAnnotationAsExpression(node); break; } } - emitDecorate = true; - if (node.kind === 138) { - emitParam = true; - } ts.forEach(node.decorators, checkDecorator); } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); + checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkFunctionLikeDeclaration(node) { + function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } - if (node.name && node.name.kind === 136) { + if (node.name && node.name.kind === 138) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); + var firstDeclaration = ts.forEach(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)) ? + declaration : undefined; }); if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); } @@ -19818,13 +21433,9 @@ var ts; } } checkSourceElement(node.body); - if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - var returnType = getTypeFromTypeNode(node.type); - var promisedType; - if (isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + if (!node.asteriskToken) { + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !node.type) { if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { @@ -19836,13 +21447,10 @@ var ts; } } function checkBlock(node) { - if (node.kind === 192) { + if (node.kind === 196) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 219) { - checkFunctionAndClassExpressionBodies(node); - } } function checkCollisionWithArgumentsInGeneratedCode(node) { if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { @@ -19858,19 +21466,19 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 141 || - node.kind === 140 || - node.kind === 143 || + if (node.kind === 143 || node.kind === 142 || node.kind === 145 || - node.kind === 146) { + node.kind === 144 || + node.kind === 147 || + node.kind === 148) { return false; } if (ts.isInAmbientContext(node)) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 138 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 140 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -19918,19 +21526,31 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 218 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 222 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 248 && ts.isExternalModule(parent)) { + if (parent.kind === 252 && ts.isExternalOrCommonJsModule(parent)) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } - function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 24576) !== 0 || ts.isParameterDeclaration(node)) { + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "Promise")) { return; } - if (node.kind === 211 && !node.initializer) { + if (node.kind === 222 && ts.getModuleInstanceState(node) !== 1) { + return; + } + var parent = getDeclarationContainer(node); + if (parent.kind === 252 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2097152) { + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + if ((ts.getCombinedNodeFlags(node) & 3072) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + if (node.kind === 215 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -19939,26 +21559,26 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212); - var container = varDeclList.parent.kind === 193 && varDeclList.parent.parent + if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 3072) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 216); + var container = varDeclList.parent.kind === 197 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 192 && ts.isFunctionLike(container.parent) || - container.kind === 219 || - container.kind === 218 || - container.kind === 248); + (container.kind === 196 && ts.isFunctionLike(container.parent) || + container.kind === 223 || + container.kind === 222 || + container.kind === 252); if (!namesShareScope) { - var name_14 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_14, name_14); + var name_15 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_15, name_15); } } } } } function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 138) { + if (ts.getRootDeclaration(node).kind !== 140) { return; } var func = ts.getContainingFunction(node); @@ -19967,7 +21587,7 @@ var ts; if (n.kind === 69) { var referencedSymbol = getNodeLinks(n).resolvedSymbol; if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, 107455) === referencedSymbol) { - if (referencedSymbol.valueDeclaration.kind === 138) { + if (referencedSymbol.valueDeclaration.kind === 140) { if (referencedSymbol.valueDeclaration === node) { error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); return; @@ -19987,21 +21607,26 @@ var ts; function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); - if (node.name.kind === 136) { + if (node.name.kind === 138) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } + if (node.kind === 167) { + if (node.propertyName && node.propertyName.kind === 138) { + checkComputedPropertyName(node.propertyName); + } + } if (ts.isBindingPattern(node.name)) { ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 138 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 140 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } if (ts.isBindingPattern(node.name)) { - if (node.initializer) { + if (node.initializer && node.parent.parent.kind !== 204) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); checkParameterInitializer(node); } @@ -20010,7 +21635,7 @@ var ts; var symbol = getSymbolOfNode(node); var type = getTypeOfVariableOrParameterOrProperty(symbol); if (node === symbol.valueDeclaration) { - if (node.initializer) { + if (node.initializer && node.parent.parent.kind !== 204) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); checkParameterInitializer(node); } @@ -20024,14 +21649,15 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } } - if (node.kind !== 141 && node.kind !== 140) { + if (node.kind !== 143 && node.kind !== 142) { checkExportsOnMergedDeclarations(node); - if (node.kind === 211 || node.kind === 163) { + if (node.kind === 215 || node.kind === 167) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } function checkVariableDeclaration(node) { @@ -20047,7 +21673,7 @@ var ts; ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 165) { + if (node.modifiers && node.parent.kind === 169) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -20066,7 +21692,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 194) { + if (node.thenStatement.kind === 198) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -20083,12 +21709,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 212) { + if (node.initializer && node.initializer.kind === 216) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 212) { + if (node.initializer.kind === 216) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -20103,18 +21729,18 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 216) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); - if (varExpr.kind === 164 || varExpr.kind === 165) { + if (varExpr.kind === 168 || varExpr.kind === 169) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant); + checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); if (iteratedType) { checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); } @@ -20124,7 +21750,7 @@ var ts; } function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 216) { 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); @@ -20134,14 +21760,14 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 164 || varExpr.kind === 165) { + if (varExpr.kind === 168 || varExpr.kind === 169) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } 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 { - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant); + checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); } } var rightType = checkExpression(node.expression); @@ -20262,7 +21888,13 @@ var ts; } function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); - var arrayType = removeTypesFromUnionType(arrayOrStringType, 258, true, true); + var arrayType = arrayOrStringType; + if (arrayOrStringType.flags & 16384) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258); })); + } + else if (arrayOrStringType.flags & 258) { + arrayType = emptyUnionType; + } var hasStringConstituent = arrayOrStringType !== arrayType; var reportedError = false; if (hasStringConstituent) { @@ -20295,8 +21927,8 @@ var ts; function checkBreakOrContinueStatement(node) { checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); } - function isGetAccessorWithAnnotatatedSetAccessor(node) { - return !!(node.kind === 145 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 146))); + function isGetAccessorWithAnnotatedSetAccessor(node) { + return !!(node.kind === 147 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 148))); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -20314,15 +21946,15 @@ var ts; if (func.asteriskToken) { return; } - if (func.kind === 146) { + if (func.kind === 148) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === 144) { + else if (func.kind === 146) { if (!checkTypeAssignableTo(exprType, returnType, node.expression)) { 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) { + else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { if (ts.isAsyncFunctionLike(func)) { var promisedType = getPromisedType(returnType); var awaitedType = checkAwaitedType(exprType, node.expression, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -20339,7 +21971,7 @@ var ts; } function checkWithStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.parserContextFlags & 8) { + if (node.flags & 33554432) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -20351,8 +21983,9 @@ var ts; var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); + var expressionTypeIsStringLike = maybeTypeOfKind(expressionType, 258); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 242 && !hasDuplicateDefaultClause) { + if (clause.kind === 246 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -20364,10 +21997,12 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 241) { + if (produceDiagnostics && clause.kind === 245) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); - if (!isTypeAssignableTo(expressionType, caseType)) { + var expressionTypeIsAssignableToCaseType = (expressionTypeIsStringLike && maybeTypeOfKind(caseType, 258)) || + isTypeAssignableTo(expressionType, caseType); + if (!expressionTypeIsAssignableToCaseType) { checkTypeAssignableTo(caseType, expressionType, caseClause.expression, undefined); } } @@ -20381,7 +22016,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 207 && current.label.text === node.label.text) { + if (current.kind === 211 && 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; @@ -20448,7 +22083,7 @@ var ts; var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!(member.flags & 64) && ts.hasDynamicName(member)) { + if (!(member.flags & 32) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); @@ -20475,7 +22110,7 @@ var ts; return; } var errorNode; - if (prop.valueDeclaration.name.kind === 136 || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 138 || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { @@ -20519,10 +22154,31 @@ var ts; } } } + function checkTypeParameterListsIdentical(node, symbol) { + if (symbol.declarations.length === 1) { + return; + } + var firstDecl; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 218 || declaration.kind === 219) { + if (!firstDecl) { + firstDecl = declaration; + } + else if (!areTypeParametersIdentical(firstDecl.typeParameters, node.typeParameters)) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, node.name.text); + } + } + } + } function checkClassExpression(node) { checkClassLikeDeclaration(node); + checkNodeDeferred(node); return getTypeOfSymbol(getSymbolOfNode(node)); } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + } function checkClassDeclaration(node) { if (!node.name && !(node.flags & 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -20537,6 +22193,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } checkTypeParameters(node.typeParameters); checkExportsOnMergedDeclarations(node); @@ -20544,13 +22201,14 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(node, symbol); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - emitExtends = emitExtends || !ts.isInAmbientContext(node); var baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { var baseType = baseTypes[0]; var staticBaseType = getBaseConstructorTypeOfClass(type); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); if (baseTypeNode.typeArguments) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); @@ -20599,6 +22257,18 @@ var ts; checkTypeForDuplicateIndexSignatures(node); } } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && declaration.flags & 8) { + var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); + } + } + } + } function getTargetSymbol(s) { return s.flags & 16777216 ? getSymbolLinks(s).target : s; } @@ -20620,7 +22290,7 @@ var ts; if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(derivedClassDecl.flags & 128))) { - if (derivedClassDecl.kind === 186) { + if (derivedClassDecl.kind === 190) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -20630,10 +22300,10 @@ var ts; } else { var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); - if ((baseDeclarationFlags & 16) || (derivedDeclarationFlags & 16)) { + if ((baseDeclarationFlags & 8) || (derivedDeclarationFlags & 8)) { continue; } - if ((baseDeclarationFlags & 64) !== (derivedDeclarationFlags & 64)) { + if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { continue; } if ((base.flags & derived.flags & 8192) || ((base.flags & 98308) && (derived.flags & 98308))) { @@ -20664,7 +22334,7 @@ var ts; } } function isAccessor(kind) { - return kind === 145 || kind === 146; + return kind === 147 || kind === 148; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -20730,12 +22400,8 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 215); - 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); - } - } + checkTypeParameterListsIdentical(node, symbol); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 219); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -20766,7 +22432,7 @@ var ts; } function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 8192)) { + if (!(nodeLinks.flags & 16384)) { var enumSymbol = getSymbolOfNode(node); var enumType = getDeclaredTypeOfSymbol(enumSymbol); var autoValue = 0; @@ -20774,11 +22440,14 @@ var ts; var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.name.kind === 136) { + if (isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } - else if (isNumericLiteralName(member.name.text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + else { + var text = getTextOfPropertyName(member.name); + if (isNumericLiteralName(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } } var previousEnumMemberIsNonConstant = autoValue === undefined; var initializer = member.initializer; @@ -20792,10 +22461,11 @@ var ts; error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); } if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue++; + getNodeLinks(member).enumMemberValue = autoValue; + autoValue++; } } - nodeLinks.flags |= 8192; + nodeLinks.flags |= 16384; } function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { var reportError = true; @@ -20824,7 +22494,7 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 179: + case 183: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; @@ -20835,7 +22505,7 @@ var ts; case 50: return ~value_1; } return undefined; - case 181: + case 185: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -20860,11 +22530,11 @@ var ts; return undefined; case 8: return +e.text; - case 172: + case 176: return evalConstant(e.expression); case 69: - case 167: - case 166: + case 171: + case 170: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; @@ -20875,7 +22545,7 @@ var ts; } else { var expression; - if (e.kind === 167) { + if (e.kind === 171) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9) { return undefined; @@ -20892,7 +22562,7 @@ var ts; if (current.kind === 69) { break; } - else if (current.kind === 166) { + else if (current.kind === 170) { current = current.expression; } else { @@ -20933,6 +22603,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); @@ -20951,7 +22622,7 @@ var ts; } var seenEnumMissingInitialInitializer = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 217) { + if (declaration.kind !== 221) { return false; } var enumDeclaration = declaration; @@ -20974,8 +22645,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 214 || - (declaration.kind === 213 && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 218 || + (declaration.kind === 217 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -20997,7 +22668,12 @@ var ts; } function checkModuleDeclaration(node) { if (produceDiagnostics) { - var isAmbientExternalModule = node.name.kind === 9; + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = ts.isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); var contextErrorMessage = isAmbientExternalModule ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; @@ -21005,17 +22681,18 @@ var ts; return; } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!ts.isInAmbientContext(node) && node.name.kind === 9) { + if (!inAmbientContext && node.name.kind === 9) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 && symbol.declarations.length > 1 - && !ts.isInAmbientContext(node) + && !inAmbientContext && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -21026,29 +22703,102 @@ 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, 214); + var mergedClass = ts.getDeclarationOfKind(symbol, 218); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; } } if (isAmbientExternalModule) { - if (!isGlobalSourceFile(node.parent)) { - error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + if (ts.isExternalModuleAugmentation(node)) { + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); + if (checkBody) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } } - if (ts.isExternalModuleNameRelative(node.name.text)) { - error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(node.name.text)) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } } } } checkSourceElement(node.body); } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 197: + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 231: + case 232: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 225: + if (node.moduleReference.kind !== 9) { + error(node.name, ts.Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + break; + } + case 226: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 167: + case 215: + var name_16 = node.name; + if (ts.isBindingPattern(name_16)) { + for (var _b = 0, _c = name_16.elements; _b < _c.length; _b++) { + var el = _c[_b]; + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + case 218: + case 221: + case 217: + case 219: + case 222: + case 220: + var symbol = getSymbolOfNode(node); + if (symbol) { + var reportError = !(symbol.flags & 33554432); + if (!reportError) { + if (isGlobalAugmentation) { + reportError = symbol.parent !== undefined; + } + else { + reportError = ts.isExternalModuleAugmentation(symbol.parent.valueDeclaration); + } + } + if (reportError) { + error(node, ts.Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + } + } + break; + } + } function getFirstIdentifier(node) { while (true) { - if (node.kind === 135) { + if (node.kind === 137) { node = node.left; } - else if (node.kind === 166) { + else if (node.kind === 170) { node = node.expression; } else { @@ -21064,16 +22814,18 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 219 && node.parent.parent.name.kind === 9; - if (node.parent.kind !== 248 && !inAmbientExternalModule) { - error(moduleName, node.kind === 228 ? + var inAmbientExternalModule = node.parent.kind === 223 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 252 && !inAmbientExternalModule) { + error(moduleName, node.kind === 232 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); - return false; + if (!isTopLevelInExternalModuleAugmentation(node)) { + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } } return true; } @@ -21085,7 +22837,7 @@ var ts; (symbol.flags & 793056 ? 793056 : 0) | (symbol.flags & 1536 ? 1536 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 230 ? + var message = node.kind === 234 ? 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)); @@ -21095,13 +22847,14 @@ var ts; function checkImportBinding(node) { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); } function checkImportDeclaration(node) { if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -21111,7 +22864,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224) { + if (importClause.namedBindings.kind === 228) { checkImportBinding(importClause.namedBindings); } else { @@ -21128,7 +22881,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 2) { + if (node.flags & 1) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -21146,7 +22899,7 @@ var ts; } } else { - if (modulekind === 5 && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES6 && !ts.isInAmbientContext(node)) { grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } @@ -21156,46 +22909,53 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959)) { 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 === 219 && node.parent.parent.name.kind === 9; - if (node.parent.kind !== 248 && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 223 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 252 && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } else { var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && moduleSymbol.exports["export="]) { + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } } } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 248 && node.parent.kind !== 219 && node.parent.kind !== 218) { + if (node.parent.kind !== 252 && node.parent.kind !== 223 && node.parent.kind !== 222) { return grammarErrorOnFirstToken(node, errorMessage); } } function checkExportSpecifier(node) { checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { - markExportAsReferenced(node); + var exportedName = node.propertyName || node.name; + var symbol = resolveName(exportedName, exportedName.text, 107455 | 793056 | 1536 | 8388608, undefined, undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_re_export_name_that_is_not_defined_in_the_module); + } + else { + markExportAsReferenced(node); + } } } function checkExportAssignment(node) { if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { return; } - var container = node.parent.kind === 248 ? node.parent : node.parent.parent; - if (container.kind === 218 && container.name.kind === 69) { + var container = node.parent.kind === 252 ? node.parent : node.parent.parent; + if (container.kind === 222 && !ts.isAmbientModule(container)) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69) { @@ -21206,23 +22966,14 @@ var ts; } checkExternalModuleExports(container); if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === 5) { + if (modulekind === ts.ModuleKind.ES6) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_export_default_or_another_module_format_instead); } - else if (modulekind === 4) { + else if (modulekind === ts.ModuleKind.System) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); } } } - function getModuleStatements(node) { - if (node.kind === 248) { - return node.statements; - } - if (node.kind === 218 && node.body.kind === 219) { - return node.body.statements; - } - return emptyArray; - } function hasExportedMembers(moduleSymbol) { for (var id in moduleSymbol.exports) { if (id !== "export=") { @@ -21238,14 +22989,36 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports["export="]; if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + var exports = getExportsOfModule(moduleSymbol); + for (var id in exports) { + if (id === "__export") { + continue; + } + var _a = exports[id], declarations = _a.declarations, flags = _a.flags; + if (flags & (1536 | 64 | 384)) { + continue; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + if (flags & 524288 && exportedDeclarationsCount <= 2) { + continue; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); + } + } + } } 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 isNotOverload(declaration) { + return declaration.kind !== 217 || !!declaration.body; } } function checkSourceElement(node) { @@ -21255,217 +23028,144 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { + case 222: case 218: - case 214: - case 215: - case 213: + case 219: + case 217: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 137: + case 139: return checkTypeParameter(node); - case 138: - return checkParameter(node); - case 141: case 140: - return checkPropertyDeclaration(node); - case 152: - case 153: - case 147: - case 148: - return checkSignatureDeclaration(node); - case 149: - return checkSignatureDeclaration(node); + return checkParameter(node); case 143: case 142: - return checkMethodDeclaration(node); - case 144: - return checkConstructorDeclaration(node); - case 145: - case 146: - return checkAccessorDeclaration(node); - case 151: - return checkTypeReferenceNode(node); - case 150: - return checkTypePredicate(node); + return checkPropertyDeclaration(node); case 154: - return checkTypeQuery(node); case 155: - return checkTypeLiteral(node); + case 149: + case 150: + return checkSignatureDeclaration(node); + case 151: + return checkSignatureDeclaration(node); + case 145: + case 144: + return checkMethodDeclaration(node); + case 146: + return checkConstructorDeclaration(node); + case 147: + case 148: + return checkAccessorDeclaration(node); + case 153: + return checkTypeReferenceNode(node); + case 152: + return checkTypePredicate(node); case 156: - return checkArrayType(node); + return checkTypeQuery(node); case 157: - return checkTupleType(node); + return checkTypeLiteral(node); case 158: + return checkArrayType(node); case 159: - return checkUnionOrIntersectionType(node); + return checkTupleType(node); case 160: + case 161: + return checkUnionOrIntersectionType(node); + case 162: return checkSourceElement(node.type); - case 213: - return checkFunctionDeclaration(node); - case 192: - case 219: - return checkBlock(node); - case 193: - return checkVariableStatement(node); - case 195: - return checkExpressionStatement(node); - case 196: - return checkIfStatement(node); - case 197: - return checkDoStatement(node); - case 198: - return checkWhileStatement(node); - case 199: - return checkForStatement(node); - case 200: - return checkForInStatement(node); - case 201: - return checkForOfStatement(node); - case 202: - case 203: - return checkBreakOrContinueStatement(node); - case 204: - return checkReturnStatement(node); - case 205: - return checkWithStatement(node); - case 206: - return checkSwitchStatement(node); - case 207: - return checkLabeledStatement(node); - case 208: - return checkThrowStatement(node); - case 209: - return checkTryStatement(node); - case 211: - return checkVariableDeclaration(node); - case 163: - return checkBindingElement(node); - case 214: - return checkClassDeclaration(node); - case 215: - return checkInterfaceDeclaration(node); - case 216: - return checkTypeAliasDeclaration(node); case 217: - return checkEnumDeclaration(node); - case 218: - return checkModuleDeclaration(node); - case 222: - return checkImportDeclaration(node); - case 221: - return checkImportEqualsDeclaration(node); - case 228: - return checkExportDeclaration(node); - case 227: - return checkExportAssignment(node); - case 194: - checkGrammarStatementInAmbientContext(node); - return; + return checkFunctionDeclaration(node); + case 196: + case 223: + return checkBlock(node); + case 197: + return checkVariableStatement(node); + case 199: + return checkExpressionStatement(node); + case 200: + return checkIfStatement(node); + case 201: + return checkDoStatement(node); + case 202: + return checkWhileStatement(node); + case 203: + return checkForStatement(node); + case 204: + return checkForInStatement(node); + case 205: + return checkForOfStatement(node); + case 206: + case 207: + return checkBreakOrContinueStatement(node); + case 208: + return checkReturnStatement(node); + case 209: + return checkWithStatement(node); case 210: + return checkSwitchStatement(node); + case 211: + return checkLabeledStatement(node); + case 212: + return checkThrowStatement(node); + case 213: + return checkTryStatement(node); + case 215: + return checkVariableDeclaration(node); + case 167: + return checkBindingElement(node); + case 218: + return checkClassDeclaration(node); + case 219: + return checkInterfaceDeclaration(node); + case 220: + return checkTypeAliasDeclaration(node); + case 221: + return checkEnumDeclaration(node); + case 222: + return checkModuleDeclaration(node); + case 226: + return checkImportDeclaration(node); + case 225: + return checkImportEqualsDeclaration(node); + case 232: + return checkExportDeclaration(node); + case 231: + return checkExportAssignment(node); + case 198: checkGrammarStatementInAmbientContext(node); return; - case 231: + case 214: + checkGrammarStatementInAmbientContext(node); + return; + case 235: return checkMissingDeclaration(node); } } - function checkFunctionAndClassExpressionBodies(node) { - switch (node.kind) { - case 173: - case 174: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - checkFunctionExpressionOrObjectLiteralMethodBody(node); - break; - case 186: - ts.forEach(node.members, checkSourceElement); - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; - case 143: - case 142: - ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - if (ts.isObjectLiteralMethod(node)) { - checkFunctionExpressionOrObjectLiteralMethodBody(node); - } - break; - case 144: - case 145: - case 146: - case 213: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - break; - case 205: - checkFunctionAndClassExpressionBodies(node.expression); - break; - case 139: - case 138: - case 141: - case 140: - case 161: - case 162: - case 163: - case 164: - case 165: - case 245: - case 166: - case 167: - case 168: - case 169: - case 170: - case 183: - case 190: - case 171: - case 189: - case 172: - case 176: - case 177: - case 178: - case 175: - case 179: - case 180: - case 181: - case 182: - case 185: - case 184: - case 192: - case 219: - case 193: - case 195: - case 196: - case 197: - case 198: - case 199: - case 200: - case 201: - case 202: - case 203: - case 204: - case 206: - case 220: - case 241: - case 242: - case 207: - case 208: - case 209: - case 244: - case 211: - case 212: - case 214: - case 243: - case 188: - case 217: - case 247: - case 227: - case 248: - case 240: - case 233: - case 234: - case 238: - case 239: - case 235: - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 177: + case 178: + case 145: + case 144: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 147: + case 148: + checkAccessorDeferred(node); + break; + case 190: + checkClassExpressionDeferred(node); + break; + } } } function checkSourceFile(node) { @@ -21476,38 +23176,24 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1)) { - if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) { - return; + if (compilerOptions.skipDefaultLibCheck) { + if (node.hasNoDefaultLib) { + return; + } } checkGrammarSourceFile(node); - emitExtends = false; - emitDecorate = false; - emitParam = false; potentialThisCollisions.length = 0; + deferredNodes = []; ts.forEach(node.statements, checkSourceElement); - checkFunctionAndClassExpressionBodies(node); - if (ts.isExternalModule(node)) { + checkDeferredNodes(); + deferredNodes = undefined; + if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } if (potentialThisCollisions.length) { ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); potentialThisCollisions.length = 0; } - if (emitExtends) { - links.flags |= 8; - } - if (emitDecorate) { - links.flags |= 16; - } - if (emitParam) { - links.flags |= 32; - } - if (emitAwaiter) { - links.flags |= 64; - } - if (emitGenerator || (emitAwaiter && languageVersion < 2)) { - links.flags |= 128; - } links.flags |= 1; } } @@ -21541,7 +23227,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 205 && node.parent.statement === node) { + if (node.parent.kind === 209 && node.parent.statement === node) { return true; } node = node.parent; @@ -21563,28 +23249,28 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 248: - if (!ts.isExternalModule(location)) { + case 252: + if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 218: + case 222: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 217: + case 221: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 186: + case 190: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 214: - case 215: - if (!(memberFlags & 64)) { + case 218: + case 219: + if (!(memberFlags & 32)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; - case 173: + case 177: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -21623,36 +23309,47 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 137: - case 214: - case 215: - case 216: - case 217: + case 139: + case 218: + case 219: + case 220: + case 221: return true; } } function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 135) { + while (node.parent && node.parent.kind === 137) { node = node.parent; } - return node.parent && node.parent.kind === 151; + return node.parent && node.parent.kind === 153; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 166) { + while (node.parent && node.parent.kind === 170) { node = node.parent; } - return node.parent && node.parent.kind === 188; + return node.parent && node.parent.kind === 192; + } + function isNodeWithinClass(node, classDeclaration) { + while (true) { + node = ts.getContainingClass(node); + if (!node) { + return false; + } + if (node === classDeclaration) { + return true; + } + } } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 135) { + while (nodeOnRightSide.parent.kind === 137) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 221) { + if (nodeOnRightSide.parent.kind === 225) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 227) { + if (nodeOnRightSide.parent.kind === 231) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -21664,10 +23361,22 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 227) { + if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 170) { + var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1: + case 3: + return getSymbolOfNode(entityName.parent); + case 4: + case 2: + return getSymbolOfNode(entityName.parent.parent); + default: + } + } + if (entityName.parent.kind === 231) { return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); } - if (entityName.kind !== 166) { + if (entityName.kind !== 170) { if (isInRightSideOfImportOrExportAssignment(entityName)) { return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); } @@ -21677,7 +23386,7 @@ var ts; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; - if (entityName.parent.kind === 188) { + if (entityName.parent.kind === 192) { meaning = 793056; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; @@ -21689,10 +23398,10 @@ var ts; meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if ((entityName.parent.kind === 235) || - (entityName.parent.kind === 234) || - (entityName.parent.kind === 237)) { - return getJsxElementTagSymbol(entityName.parent); + else if ((entityName.parent.kind === 239) || + (entityName.parent.kind === 238) || + (entityName.parent.kind === 241)) { + return getJsxTagSymbol(entityName.parent); } else if (ts.isExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { @@ -21702,14 +23411,14 @@ var ts; var meaning = 107455 | 8388608; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 166) { + else if (entityName.kind === 170) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 135) { + else if (entityName.kind === 137) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -21718,14 +23427,14 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 151 ? 793056 : 1536; + var meaning = entityName.parent.kind === 153 ? 793056 : 1536; meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if (entityName.parent.kind === 238) { + else if (entityName.parent.kind === 242) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 150) { + if (entityName.parent.kind === 152) { return resolveEntityName(entityName, 1); } return undefined; @@ -21739,12 +23448,12 @@ var ts; } if (node.kind === 69) { if (isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 227 + return node.parent.kind === 231 ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } - else if (node.parent.kind === 163 && - node.parent.parent.kind === 161 && + else if (node.parent.kind === 167 && + node.parent.parent.kind === 165 && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -21755,28 +23464,30 @@ var ts; } switch (node.kind) { case 69: - case 166: - case 135: + case 170: + case 137: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 97: case 95: var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; + case 163: + return getTypeFromTypeNode(node).symbol; case 121: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 144) { + if (constructorDeclaration && constructorDeclaration.kind === 146) { return constructorDeclaration.parent.symbol; } return undefined; case 9: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 222 || node.parent.kind === 228) && + ((node.parent.kind === 226 || node.parent.kind === 232) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } case 8: - if (node.parent.kind === 167 && node.parent.argumentExpression === node) { + if (node.parent.kind === 171 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -21790,11 +23501,16 @@ var ts; return undefined; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 246) { - return resolveEntityName(location.name, 107455); + if (location && location.kind === 250) { + return resolveEntityName(location.name, 107455 | 8388608); } return undefined; } + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536 | 8388608); + } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { return unknownType; @@ -21842,7 +23558,7 @@ var ts; } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 64 + return node.flags & 32 ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -21861,9 +23577,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols = []; - var name_15 = symbol.name; + var name_17 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_15); + var symbol = getPropertyOfType(t, name_17); if (symbol) { symbols.push(symbol); } @@ -21881,6 +23597,25 @@ var ts; function isArgumentsLocalBinding(node) { return getReferencedValueSymbol(node) === argumentsSymbol; } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol) { + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455) + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455); + } + } function getReferencedExportContainer(node) { var symbol = getReferencedValueSymbol(node); if (symbol) { @@ -21893,11 +23628,11 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 248) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 252) { return parentSymbol.valueDeclaration; } for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 218 || n.kind === 217) && getSymbolOfNode(n) === parentSymbol) { + if ((n.kind === 222 || n.kind === 221) && getSymbolOfNode(n) === parentSymbol) { return n; } } @@ -21908,54 +23643,56 @@ var ts; var symbol = getReferencedValueSymbol(node); return symbol && symbol.flags & 8388608 ? getDeclarationOfAliasSymbol(symbol) : undefined; } - function isStatementWithLocals(node) { - switch (node.kind) { - case 192: - case 220: - case 199: - case 200: - case 201: - return true; - } - return false; - } - function isNestedRedeclarationSymbol(symbol) { + function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418) { var links = getSymbolLinks(symbol); - if (links.isNestedRedeclaration === undefined) { + if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - links.isNestedRedeclaration = isStatementWithLocals(container) && - !!resolveName(container.parent, symbol.name, 107455, undefined, undefined); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.name, 107455, undefined, undefined)) { + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 131072) { + var isDeclaredInLoop = nodeLinks_1.flags & 262144; + var inLoopInitializer = ts.isIterationStatement(container, false); + var inLoopBodyBlock = container.kind === 196 && ts.isIterationStatement(container.parent, false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } } - return links.isNestedRedeclaration; + return links.isDeclarationWithCollidingName; } return false; } - function getReferencedNestedRedeclaration(node) { + function getReferencedDeclarationWithCollidingName(node) { var symbol = getReferencedValueSymbol(node); - return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + return symbol && isSymbolOfDeclarationWithCollidingName(symbol) ? symbol.valueDeclaration : undefined; } - function isNestedRedeclaration(node) { - return isNestedRedeclarationSymbol(getSymbolOfNode(node)); + function isDeclarationWithCollidingName(node) { + return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); } function isValueAliasDeclaration(node) { switch (node.kind) { - case 221: - case 223: - case 224: - case 226: - case 230: - return isAliasResolvedToValue(getSymbolOfNode(node)); + case 225: + case 227: case 228: + case 230: + case 234: + return isAliasResolvedToValue(getSymbolOfNode(node)); + case 232: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 227: + case 231: return node.expression && node.expression.kind === 69 ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 248 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 252 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -22003,7 +23740,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 247) { + if (node.kind === 251) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -22034,22 +23771,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (allConstituentTypesHaveKind(type, 16)) { + else if (isTypeOfKind(type, 16)) { return ts.TypeReferenceSerializationKind.VoidType; } - else if (allConstituentTypesHaveKind(type, 8)) { + else if (isTypeOfKind(type, 8)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (allConstituentTypesHaveKind(type, 132)) { + else if (isTypeOfKind(type, 132)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (allConstituentTypesHaveKind(type, 258)) { + else if (isTypeOfKind(type, 258)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (allConstituentTypesHaveKind(type, 8192)) { + else if (isTypeOfKind(type, 8192)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (allConstituentTypesHaveKind(type, 16777216)) { + else if (isTypeOfKind(type, 16777216)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -22089,23 +23826,12 @@ var ts; var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } - function instantiateSingleCallFunctionType(functionType, typeArguments) { - if (functionType === unknownType) { - return unknownType; - } - var signature = getSingleCallSignature(functionType); - if (!signature) { - return unknownType; - } - var instantiatedSignature = getSignatureInstantiation(signature, typeArguments); - return getOrCreateTypeFromSignature(instantiatedSignature); - } function createResolver() { return { getReferencedExportContainer: getReferencedExportContainer, getReferencedImportDeclaration: getReferencedImportDeclaration, - getReferencedNestedRedeclaration: getReferencedNestedRedeclaration, - isNestedRedeclaration: isNestedRedeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, isValueAliasDeclaration: isValueAliasDeclaration, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: isReferencedAliasDeclaration, @@ -22123,22 +23849,45 @@ var ts; getReferencedValueDeclaration: getReferencedValueDeclaration, getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, isOptionalParameter: isOptionalParameter, - isArgumentsLocalBinding: isArgumentsLocalBinding + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration }; } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 252); + } function initializeTypeChecker() { ts.forEach(host.getSourceFiles(), function (file) { ts.bindSourceFile(file, compilerOptions); }); + var augmentations; ts.forEach(host.getSourceFiles(), function (file) { - if (!ts.isExternalModule(file)) { + if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } }); + if (augmentations) { + for (var _i = 0, augmentations_1 = augmentations; _i < augmentations_1.length; _i++) { + var list = augmentations_1[_i]; + for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { + var augmentation = list_2[_a]; + mergeModuleAugmentation(augmentation); + } + } + } + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; - globals[undefinedSymbol.name] = undefinedSymbol; globalArrayType = getGlobalType("Array", 1); globalObjectType = getGlobalType("Object"); globalFunctionType = getGlobalType("Function"); @@ -22176,6 +23925,9 @@ var ts; globalIterableIteratorType = emptyGenericType; } anyArrayType = createArrayType(anyType); + var symbol = getGlobalSymbol("ReadonlyArray", 793056, undefined); + globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); @@ -22199,9 +23951,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + if (node.kind === 145 && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } } - else if (node.kind === 145 || node.kind === 146) { + else if (node.kind === 147 || node.kind === 148) { 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); @@ -22211,38 +23968,38 @@ var ts; } function checkGrammarModifiers(node) { switch (node.kind) { - case 145: + case 147: + case 148: case 146: - case 144: - case 141: - case 140: case 143: case 142: - case 149: - case 218: + case 145: + case 144: + case 151: case 222: - case 221: - case 228: - case 227: - case 138: - break; - case 213: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && - node.parent.kind !== 219 && node.parent.kind !== 248) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 214: - case 215: - case 193: - case 216: - if (node.modifiers && node.parent.kind !== 219 && node.parent.kind !== 248) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } + case 226: + case 225: + case 232: + case 231: + case 140: break; case 217: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && + node.parent.kind !== 223 && node.parent.kind !== 252) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 218: + case 219: + case 197: + case 220: + if (node.modifiers && node.parent.kind !== 223 && node.parent.kind !== 252) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 221: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74) && - node.parent.kind !== 219 && node.parent.kind !== 248) { + node.parent.kind !== 223 && node.parent.kind !== 252) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; @@ -22252,37 +24009,48 @@ var ts; if (!node.modifiers) { return; } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync; + var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (modifier.kind !== 127) { + if (node.kind === 142 || node.kind === 144) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 151) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } switch (modifier.kind) { + case 74: + if (node.kind !== 221 && node.parent.kind === 218) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74)); + } + break; case 112: case 111: case 110: - var text = void 0; - if (modifier.kind === 112) { - text = "public"; - } - else if (modifier.kind === 111) { - text = "protected"; + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (modifier.kind === 111) { lastProtected = modifier; } - else { - text = "private"; + else if (modifier.kind === 110) { lastPrivate = modifier; } - if (flags & 56) { + if (flags & 28) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & 64) { + else if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 219 || node.parent.kind === 248) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); + else if (node.parent.kind === 223 || node.parent.kind === 252) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128) { if (modifier.kind === 110) { @@ -22295,29 +24063,42 @@ var ts; flags |= ts.modifierToFlag(modifier.kind); break; case 113: - if (flags & 64) { + if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 219 || node.parent.kind === 248) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); + else if (node.parent.kind === 223 || node.parent.kind === 252) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 138) { + else if (node.kind === 140) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= 64; + flags |= 32; lastStatic = modifier; break; + case 127: + if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 143 && node.kind !== 142 && node.kind !== 151) { + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64; + lastReadonly = modifier; + break; case 82: - if (flags & 2) { + if (flags & 1) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & 4) { + else if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } else if (flags & 128) { @@ -22326,48 +24107,51 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 218) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 138) { + else if (node.kind === 140) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= 2; + flags |= 1; break; case 122: - if (flags & 4) { + if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 218) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 138) { + else if (node.kind === 140) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 223) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= 4; + flags |= 2; lastDeclare = modifier; break; case 115: if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 214) { - if (node.kind !== 143) { - return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); + if (node.kind !== 218) { + if (node.kind !== 145 && + node.kind !== 143 && + node.kind !== 147 && + node.kind !== 148) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 214 && node.parent.flags & 128)) { + if (!(node.parent.kind === 218 && node.parent.flags & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & 64) { + if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 16) { + if (flags & 8) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } @@ -22377,10 +24161,10 @@ var ts; if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 4 || ts.isInAmbientContext(node.parent)) { + else if (flags & 2 || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 138) { + else if (node.kind === 140) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256; @@ -22388,28 +24172,25 @@ var ts; break; } } - if (node.kind === 144) { - if (flags & 64) { + if (node.kind === 146) { + if (flags & 32) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & 32) { - return grammarErrorOnNode(lastProtected, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); - } - else if (flags & 16) { - return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); - } else if (flags & 256) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } + else if (flags & 64) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } return; } - else if ((node.kind === 222 || node.kind === 221) && flags & 4) { + else if ((node.kind === 226 || node.kind === 225) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 138 && (flags & 56) && ts.isBindingPattern(node.name)) { + else if (node.kind === 140 && (flags & 28) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } if (flags & 256) { @@ -22421,10 +24202,10 @@ var ts; return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher); } switch (node.kind) { - case 143: - case 213: - case 173: - case 174: + case 145: + case 217: + case 177: + case 178: if (!node.asteriskToken) { return false; } @@ -22489,7 +24270,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 174) { + if (node.kind === 178) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -22512,7 +24293,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 1022) { + if (parameter.flags & 959) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -22524,20 +24305,15 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 130 && parameter.type.kind !== 128) { + if (parameter.type.kind !== 131 && parameter.type.kind !== 129) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } } - function checkGrammarForIndexSignatureModifier(node) { - if (node.flags & 1022) { - grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); - } - } function checkGrammarIndexSignature(node) { - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node) || checkGrammarForIndexSignatureModifier(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); } function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { if (typeArguments && typeArguments.length === 0) { @@ -22556,7 +24332,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { var arg = args_1[_i]; - if (arg.kind === 187) { + if (arg.kind === 191) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -22627,19 +24403,19 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 136) { + if (node.kind !== 138) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 181 && computedPropertyName.expression.operatorToken.kind === 24) { + if (computedPropertyName.expression.kind === 185 && computedPropertyName.expression.operatorToken.kind === 24) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 213 || - node.kind === 173 || - node.kind === 143); + ts.Debug.assert(node.kind === 217 || + node.kind === 177 || + node.kind === 145); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -22660,78 +24436,88 @@ var ts; var seen = {}; var Property = 1; var GetAccessor = 2; - var SetAccesor = 4; - var GetOrSetAccessor = GetAccessor | SetAccesor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - var name_16 = prop.name; - if (prop.kind === 187 || - name_16.kind === 136) { - checkGrammarComputedPropertyName(name_16); - continue; + var SetAccessor = 4; + var GetOrSetAccessor = GetAccessor | SetAccessor; + var _loop_1 = function(prop) { + var name_18 = prop.name; + if (prop.kind === 191 || + name_18.kind === 138) { + checkGrammarComputedPropertyName(name_18); + return "continue"; } - if (prop.kind === 246 && !inDestructuring && prop.objectAssignmentInitializer) { - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + if (prop.kind === 250 && !inDestructuring && prop.objectAssignmentInitializer) { + return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; } + ts.forEach(prop.modifiers, function (mod) { + if (mod.kind !== 118 || prop.kind !== 145) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + }); var currentKind = void 0; - if (prop.kind === 245 || prop.kind === 246) { + if (prop.kind === 249 || prop.kind === 250) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_16.kind === 8) { - checkGrammarNumericLiteral(name_16); + if (name_18.kind === 8) { + checkGrammarNumericLiteral(name_18); } currentKind = Property; } - else if (prop.kind === 143) { + else if (prop.kind === 145) { currentKind = Property; } - else if (prop.kind === 145) { + else if (prop.kind === 147) { currentKind = GetAccessor; } - else if (prop.kind === 146) { - currentKind = SetAccesor; + else if (prop.kind === 148) { + currentKind = SetAccessor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_16.text)) { - seen[name_16.text] = currentKind; + if (!ts.hasProperty(seen, name_18.text)) { + seen[name_18.text] = currentKind; } else { - var existingKind = seen[name_16.text]; + var existingKind = seen[name_18.text]; if (currentKind === Property && existingKind === Property) { - continue; + return "continue"; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_16.text] = currentKind | existingKind; + seen[name_18.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return { value: grammarErrorOnNode(name_18, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return { value: grammarErrorOnNode(name_18, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } + }; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var state_1 = _loop_1(prop); + if (typeof state_1 === "object") return state_1.value + if (state_1 === "continue") continue; } } function checkGrammarJsxElement(node) { var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 239) { + if (attr.kind === 243) { continue; } var jsxAttr = attr; - var name_17 = jsxAttr.name; - if (!ts.hasProperty(seen, name_17.text)) { - seen[name_17.text] = true; + var name_19 = jsxAttr.name; + if (!ts.hasProperty(seen, name_19.text)) { + seen[name_19.text] = true; } else { - return grammarErrorOnNode(name_17, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_19, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 240 && !initializer.expression) { + if (initializer && initializer.kind === 244 && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -22740,24 +24526,28 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 212) { + if (forInOrOfStatement.initializer.kind === 216) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { - if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 200 + var declarations = variableList.declarations; + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 204 ? 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]; + var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 200 + var diagnostic = forInOrOfStatement.kind === 204 ? 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 === 200 + var diagnostic = forInOrOfStatement.kind === 204 ? 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); @@ -22774,16 +24564,16 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined) { + else if (accessor.body === undefined && !(accessor.flags & 128)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } - else if (kind === 145 && accessor.parameters.length) { + else if (kind === 147 && accessor.parameters.length) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); } - else if (kind === 146) { + else if (kind === 148) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -22795,7 +24585,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); } - else if (parameter.flags & 1022) { + else if (parameter.flags & 959) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } else if (parameter.questionToken) { @@ -22808,7 +24598,7 @@ var ts; } } function checkGrammarForNonSymbolComputedProperty(node, message) { - if (node.kind === 136 && !ts.isWellKnownSymbolSyntactically(node.expression)) { + if (ts.isDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -22818,12 +24608,12 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 165) { + if (node.parent.kind === 169) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } else if (node.body === undefined) { - return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (ts.isClassLike(node.parent)) { @@ -22837,10 +24627,10 @@ 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 === 215) { + else if (node.parent.kind === 219) { 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 === 155) { + else if (node.parent.kind === 157) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } @@ -22851,9 +24641,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 207: + case 211: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 202 + var isMisplacedContinueLabel = node.kind === 206 && !ts.isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -22861,8 +24651,8 @@ var ts; return false; } break; - case 206: - if (node.kind === 203 && !node.label) { + case 210: + if (node.kind === 207 && !node.label) { return false; } break; @@ -22875,13 +24665,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 203 + var message = node.kind === 207 ? 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 === 203 + var message = node.kind === 207 ? 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); @@ -22893,7 +24683,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 === 162 || node.name.kind === 161) { + if (node.name.kind === 166 || node.name.kind === 165) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -22902,7 +24692,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 200 && node.parent.parent.kind !== 201) { + if (node.parent.parent.kind !== 204 && node.parent.parent.kind !== 205) { if (ts.isInAmbientContext(node)) { if (node.initializer) { var equalsTokenLength = "=".length; @@ -22918,12 +24708,12 @@ var ts; } } } - var checkLetConstNames = languageVersion >= 2 && (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 69) { - if (name.text === "let") { + if (name.originalKeywordKind === 108) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -22931,7 +24721,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 187) { + if (element.kind !== 191) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -22948,15 +24738,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 196: - case 197: - case 198: - case 205: - case 199: case 200: case 201: + case 202: + case 209: + case 203: + case 204: + case 205: return false; - case 207: + case 211: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -22971,18 +24761,6 @@ var ts; } } } - function isIntegerLiteral(expression) { - if (expression.kind === 179) { - var unaryExpression = expression; - if (unaryExpression.operator === 35 || unaryExpression.operator === 36) { - expression = unaryExpression.operand; - } - } - if (expression.kind === 8) { - return /^[0-9]+([eE]\+?[0-9]+)?$/.test(expression.text); - } - return false; - } function hasParseDiagnostics(sourceFile) { return sourceFile.parseDiagnostics.length > 0; } @@ -23007,10 +24785,6 @@ var ts; return true; } } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 && - (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); @@ -23028,29 +24802,35 @@ var ts; return true; } } - else if (node.parent.kind === 215) { + else if (node.parent.kind === 219) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } } - else if (node.parent.kind === 155) { + else if (node.parent.kind === 157) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } } if (ts.isInAmbientContext(node) && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 215 || - node.kind === 216 || - node.kind === 222 || - node.kind === 221 || - node.kind === 228 || - node.kind === 227 || - (node.flags & 4) || - (node.flags & (2 | 512))) { + if (node.kind === 219 || + node.kind === 220 || + node.kind === 226 || + node.kind === 225 || + node.kind === 232 || + node.kind === 231 || + (node.flags & 2) || + (node.flags & (1 | 512))) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -23058,7 +24838,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 === 193) { + if (ts.isDeclaration(decl) || decl.kind === 197) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -23077,7 +24857,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 === 192 || node.parent.kind === 219 || node.parent.kind === 248) { + if (node.parent.kind === 196 || node.parent.kind === 223 || node.parent.kind === 252) { 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); @@ -23088,7 +24868,7 @@ var ts; } } function checkGrammarNumericLiteral(node) { - if (node.flags & 32768 && languageVersion >= 1) { + if (node.isOctalLiteral && languageVersion >= 1) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -23100,19 +24880,287 @@ var ts; return true; } } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); var ts; +(function (ts) { + var nullSourceMapWriter; + var defaultLastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitStart: function (range) { }, + emitEnd: function (range, stopOverridingSpan) { }, + emitPos: function (pos) { }, + changeEmitSourcePos: function () { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; }, + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var currentSourceFile; + var sourceMapDir; + var stopOverridingSpan = false; + var modifyLastSourcePos = false; + var sourceMapSourceIndex; + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + var sourceMapData; + return { + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + changeEmitSourcePos: changeEmitSourcePos, + getText: getText, + getSourceMappingURL: getSourceMappingURL, + initialize: initialize, + reset: reset + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + sourceMapSourceIndex = -1; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; + lastEncodedNameIndex = 0; + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, + sourceMapDecodedMappings: [] + }; + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + } + function updateLastEncodedAndRecordedSpans() { + if (modifyLastSourcePos) { + modifyLastSourcePos = false; + lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; + lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; + sourceMapData.sourceMapDecodedMappings.pop(); + lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? + sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : + defaultLastEncodedSourceMapSpan; + var sourceMapMappings = sourceMapData.sourceMapMappings; + var lenthToSet = sourceMapMappings.length - 1; + for (; lenthToSet >= 0; lenthToSet--) { + var currentChar = sourceMapMappings.charAt(lenthToSet); + if (currentChar === ",") { + break; + } + if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { + break; + } + } + sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); + } + } + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this"); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (pos === -1) { + return; + } + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + if (!lastRecordedSourceMapSpan || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || + (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + sourceIndex: sourceMapSourceIndex + }; + stopOverridingSpan = false; + } + else if (!stopOverridingSpan) { + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + updateLastEncodedAndRecordedSpans(); + } + function getStartPos(range) { + var rangeHasDecorators = !!range.decorators; + return range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1; + } + function emitStart(range) { + emitPos(getStartPos(range)); + } + function emitEnd(range, stopOverridingEnd) { + emitPos(range.end); + stopOverridingSpan = stopOverridingEnd; + } + function changeEmitSourcePos() { + ts.Debug.assert(!modifyLastSourcePos); + modifyLastSourcePos = true; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + ts.createSourceMapWriter = createSourceMapWriter; + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } +})(ts || (ts = {})); +var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var diagnostics = []; - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); - emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; + var declarationDiagnostics = ts.createDiagnosticCollection(); + ts.forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); + return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName); + function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { + var declarationFilePath = _a.declarationFilePath; + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -23120,78 +25168,94 @@ var ts; var increaseIndent; var decreaseIndent; var writeTextOfNode; - var writer = createAndSetNewTextWriterWithSymbolWriter(); + var writer; + createAndSetNewTextWriterWithSymbolWriter(); var enclosingDeclaration; - var currentSourceFile; + var resultHasExternalModuleIndicator; + var currentText; + var currentLineMap; + var currentIdentifiers; + var isCurrentFileExternalModule; var reportedDeclarationError = false; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; + var noDeclare; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencePathsOutput = ""; - if (root) { + var emittedReferencedFiles = []; + var addedGlobalFileReference = false; + var allSourcesModuleElementDeclarationEmitInfo = []; + ts.forEach(sourceFiles, function (sourceFile) { + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; - ts.forEach(root.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); - if (referencedFile && ((referencedFile.flags & 4096) || - ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || - !addedGlobalFileReference)) { - writeReferencePath(referencedFile); - if (!ts.isExternalModuleOrDeclarationFile(referencedFile)) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } + emittedReferencedFiles.push(referencedFile); } }); } - emitSourceFile(root); + resultHasExternalModuleIndicator = false; + if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { + noDeclare = false; + emitSourceFile(sourceFile); + } + else if (ts.isExternalModule(sourceFile)) { + noDeclare = true; + write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); + writeLine(); + increaseIndent(); + emitSourceFile(sourceFile); + decreaseIndent(); + write("}"); + writeLine(); + } if (moduleElementDeclarationEmitInfo.length) { var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222); + if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { + ts.Debug.assert(aliasEmitInfo.node.kind === 226); createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0); + ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + increaseIndent(); + } writeImportDeclaration(aliasEmitInfo.node); aliasEmitInfo.asynchronousOutput = writer.getText(); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + decreaseIndent(); + } } }); setWriter(oldWriter); + allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); + moduleElementDeclarationEmitInfo = []; } - } - else { - var emittedReferencedFiles = []; - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) { - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - if (referencedFile && (ts.isExternalModuleOrDeclarationFile(referencedFile) && - !ts.contains(emittedReferencedFiles, referencedFile))) { - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - emitSourceFile(sourceFile); - } - }); - } + if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + write("export {};"); + writeLine(); + } + }); return { reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: moduleElementDeclarationEmitInfo, + moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput: referencePathsOutput }; function hasInternalAnnotation(range) { - var text = currentSourceFile.text; - var comment = text.substring(range.pos, range.end); + var comment = currentText.substring(range.pos, range.end); return comment.indexOf("@internal") >= 0; } function stripInternal(node) { if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { return; } @@ -23210,7 +25274,6 @@ var ts; writer.writeParameter = writer.write; writer.writeSymbol = writer.write; setWriter(writer); - return writer; } function setWriter(newWriter) { writer = newWriter; @@ -23224,10 +25287,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 211) { + if (declaration.kind === 215) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 225 || declaration.kind === 226 || declaration.kind === 223) { + else if (declaration.kind === 229 || declaration.kind === 230 || declaration.kind === 227) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -23238,7 +25301,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 222) { + if (moduleElementEmitInfo.node.kind === 226) { moduleElementEmitInfo.isVisible = true; } else { @@ -23246,12 +25309,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 218) { + if (nodeToCheck.kind === 222) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 218) { + if (nodeToCheck.kind === 222) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -23261,21 +25324,21 @@ var ts; }); setWriter(oldWriter); } - function handleSymbolAccessibilityError(symbolAccesibilityResult) { - if (symbolAccesibilityResult.accessibility === 0) { - if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccesibilityResult.aliasesToMakeVisible); + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0) { + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); } } else { reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); if (errorInfo) { if (errorInfo.typeName) { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); } else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); } } } @@ -23285,7 +25348,8 @@ var ts; } function reportInaccessibleThisError() { if (errorNameNode) { - diagnostics.push(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { @@ -23336,9 +25400,9 @@ var ts; } function writeJsDocComments(declaration) { if (declaration) { - var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile); - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); - ts.emitComments(currentSourceFile, writer, jsDocComments, true, newLine, ts.writeCommentRange); + var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -23348,62 +25412,62 @@ var ts; function emitType(type) { switch (type.kind) { case 117: - case 130: - case 128: - case 120: case 131: + case 129: + case 120: + case 132: case 103: - case 97: - case 9: - return writeTextOfNode(currentSourceFile, type); - case 188: + case 163: + case 164: + return writeTextOfNode(currentText, type); + case 192: return emitExpressionWithTypeArguments(type); - case 151: - return emitTypeReference(type); - case 154: - return emitTypeQuery(type); - case 156: - return emitArrayType(type); - case 157: - return emitTupleType(type); - case 158: - return emitUnionType(type); - case 159: - return emitIntersectionType(type); - case 160: - return emitParenType(type); - case 152: case 153: - return emitSignatureDeclarationWithJsDocComments(type); + return emitTypeReference(type); + case 156: + return emitTypeQuery(type); + case 158: + return emitArrayType(type); + case 159: + return emitTupleType(type); + case 160: + return emitUnionType(type); + case 161: + return emitIntersectionType(type); + case 162: + return emitParenType(type); + case 154: case 155: + return emitSignatureDeclarationWithJsDocComments(type); + case 157: return emitTypeLiteral(type); case 69: return emitEntityName(type); - case 135: + case 137: return emitEntityName(type); - case 150: + case 152: return emitTypePredicate(type); } function writeEntityName(entityName) { if (entityName.kind === 69) { - writeTextOfNode(currentSourceFile, entityName); + writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 135 ? entityName.left : entityName.expression; - var right = entityName.kind === 135 ? entityName.right : entityName.name; + var left = entityName.kind === 137 ? entityName.left : entityName.expression; + var right = entityName.kind === 137 ? entityName.right : entityName.name; writeEntityName(left); write("."); - writeTextOfNode(currentSourceFile, right); + writeTextOfNode(currentText, right); } } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 221 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 225 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 166); + ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 170); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -23421,7 +25485,7 @@ var ts; } } function emitTypePredicate(type) { - writeTextOfNode(currentSourceFile, type.parameterName); + writeTextOfNode(currentText, type.parameterName); write(" is "); emitType(type.type); } @@ -23461,28 +25525,32 @@ var ts; } } function emitSourceFile(node) { - currentSourceFile = node; + currentText = node.text; + currentLineMap = ts.getLineStarts(node); + currentIdentifiers = node.identifiers; + isCurrentFileExternalModule = ts.isExternalModule(node); enclosingDeclaration = node; - ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true); + ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) { + if (!ts.hasProperty(currentIdentifiers, baseName)) { return baseName; } var count = 0; while (true) { - var name_18 = baseName + "_" + (++count); - if (!ts.hasProperty(currentSourceFile.identifiers, name_18)) { - return name_18; + count++; + var name_20 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_20)) { + return name_20; } } } function emitExportAssignment(node) { if (node.expression.kind === 69) { write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentSourceFile, node.expression); + writeTextOfNode(currentText, node.expression); } else { var tempVarName = getExportDefaultTempVariableName(); @@ -23516,10 +25584,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 221 || - (node.parent.kind === 248 && ts.isExternalModule(currentSourceFile))) { + else if (node.kind === 225 || + (node.parent.kind === 252 && isCurrentFileExternalModule)) { var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248) { + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 252) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -23528,7 +25596,7 @@ var ts; }); } else { - if (node.kind === 222) { + if (node.kind === 226) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -23546,62 +25614,65 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 213: - return writeFunctionDeclaration(node); - case 193: - return writeVariableStatement(node); - case 215: - return writeInterfaceDeclaration(node); - case 214: - return writeClassDeclaration(node); - case 216: - return writeTypeAliasDeclaration(node); case 217: - return writeEnumDeclaration(node); + return writeFunctionDeclaration(node); + case 197: + return writeVariableStatement(node); + case 219: + return writeInterfaceDeclaration(node); case 218: - return writeModuleDeclaration(node); + return writeClassDeclaration(node); + case 220: + return writeTypeAliasDeclaration(node); case 221: - return writeImportEqualsDeclaration(node); + return writeEnumDeclaration(node); case 222: + return writeModuleDeclaration(node); + case 225: + return writeImportEqualsDeclaration(node); + case 226: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); } } function emitModuleElementDeclarationFlags(node) { - if (node.parent === currentSourceFile) { - if (node.flags & 2) { + if (node.parent.kind === 252) { + if (node.flags & 1) { write("export "); } if (node.flags & 512) { write("default "); } - else if (node.kind !== 215) { + else if (node.kind !== 219 && !noDeclare) { write("declare "); } } } - function emitClassMemberDeclarationFlags(node) { - if (node.flags & 16) { + function emitClassMemberDeclarationFlags(flags) { + if (flags & 8) { write("private "); } - else if (node.flags & 32) { + else if (flags & 16) { write("protected "); } - if (node.flags & 64) { + if (flags & 32) { write("static "); } - if (node.flags & 128) { + if (flags & 64) { + write("readonly "); + } + if (flags & 128) { write("abstract "); } } function writeImportEqualsDeclaration(node) { emitJsDocComments(node); - if (node.flags & 2) { + if (node.flags & 1) { write("export "); } write("import "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" = "); if (ts.isInternalModuleImportEqualsDeclaration(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); @@ -23609,11 +25680,11 @@ var ts; } else { write("require("); - writeTextOfNode(currentSourceFile, ts.getExternalModuleImportEqualsDeclarationExpression(node)); + emitExternalModuleSpecifier(node); write(");"); } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccesibilityResult) { + function getImportEntityNameVisibilityError(symbolAccessibilityResult) { return { diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -23623,7 +25694,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 224) { + if (namedBindings.kind === 228) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -23632,26 +25703,23 @@ var ts; } } function writeImportDeclaration(node) { - if (!node.importClause && !(node.flags & 2)) { - return; - } emitJsDocComments(node); - if (node.flags & 2) { + if (node.flags & 1) { write("export "); } write("import "); if (node.importClause) { var currentWriterPos = writer.getTextPos(); if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentSourceFile, node.importClause.name); + writeTextOfNode(currentText, node.importClause.name); } if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 224) { + if (node.importClause.namedBindings.kind === 228) { write("* as "); - writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name); + writeTextOfNode(currentText, node.importClause.namedBindings.name); } else { write("{ "); @@ -23661,16 +25729,41 @@ var ts; } write(" from "); } - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); write(";"); writer.writeLine(); } + function emitExternalModuleSpecifier(parent) { + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 222; + var moduleSpecifier; + if (parent.kind === 225) { + var node = parent; + moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); + } + else if (parent.kind === 222) { + moduleSpecifier = parent.name; + } + else { + var node = parent; + moduleSpecifier = node.moduleSpecifier; + } + if (moduleSpecifier.kind === 9 && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); + if (moduleName) { + write("\""); + write(moduleName); + write("\""); + return; + } + } + writeTextOfNode(currentText, moduleSpecifier); + } function emitImportOrExportSpecifier(node) { if (node.propertyName) { - writeTextOfNode(currentSourceFile, node.propertyName); + writeTextOfNode(currentText, node.propertyName); write(" as "); } - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } function emitExportSpecifier(node) { emitImportOrExportSpecifier(node); @@ -23690,7 +25783,7 @@ var ts; } if (node.moduleSpecifier) { write(" from "); - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); } write(";"); writer.writeLine(); @@ -23698,17 +25791,27 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 65536) { - write("namespace "); + if (ts.isGlobalScopeAugmentation(node)) { + write("global "); } else { - write("module "); + if (node.flags & 4096) { + write("namespace "); + } + else { + write("module "); + } + if (ts.isExternalModuleAugmentation(node)) { + emitExternalModuleSpecifier(node); + } + else { + writeTextOfNode(currentText, node.name); + } } - writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 219) { + while (node.body.kind !== 223) { node = node.body; write("."); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; @@ -23727,14 +25830,14 @@ var ts; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("type "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); emitTypeParameters(node.typeParameters); write(" = "); emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); write(";"); writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult) { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -23749,7 +25852,7 @@ var ts; write("const "); } write("enum "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" {"); writeLine(); increaseIndent(); @@ -23760,7 +25863,7 @@ var ts; } function emitEnumMemberDeclaration(node) { emitJsDocComments(node); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); @@ -23770,59 +25873,59 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 143 && (node.parent.flags & 16); + return node.parent.kind === 145 && (node.parent.flags & 8); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { increaseIndent(); emitJsDocComments(node); decreaseIndent(); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 152 || - node.parent.kind === 153 || - (node.parent.parent && node.parent.parent.kind === 155)) { - ts.Debug.assert(node.parent.kind === 143 || - node.parent.kind === 142 || - node.parent.kind === 152 || - node.parent.kind === 153 || - node.parent.kind === 147 || - node.parent.kind === 148); + if (node.parent.kind === 154 || + node.parent.kind === 155 || + (node.parent.parent && node.parent.parent.kind === 157)) { + ts.Debug.assert(node.parent.kind === 145 || + node.parent.kind === 144 || + node.parent.kind === 154 || + node.parent.kind === 155 || + node.parent.kind === 149 || + node.parent.kind === 150); emitType(node.constraint); } else { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); } } - function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { + function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.parent.kind) { - case 214: + case 218: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 215: + case 219: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 148: + case 150: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 147: + case 149: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 143: - case 142: - if (node.parent.flags & 64) { + case 145: + case 144: + if (node.parent.flags & 32) { 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 === 214) { + else if (node.parent.parent.kind === 218) { 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 213: + case 217: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -23853,9 +25956,9 @@ var ts; else if (!isImplementsList && node.expression.kind === 93) { write("null"); } - function getHeritageClauseVisibilityError(symbolAccesibilityResult) { + function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.parent.parent.kind === 214) { + if (node.parent.parent.kind === 218) { 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; @@ -23875,7 +25978,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 56) { + if (param.flags & 28) { emitPropertyDeclaration(param); } }); @@ -23887,7 +25990,7 @@ var ts; write("abstract "); } write("class "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -23910,7 +26013,7 @@ var ts; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("interface "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -23929,61 +26032,61 @@ var ts; return; } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node); + emitClassMemberDeclarationFlags(node.flags); emitVariableDeclaration(node); write(";"); writeLine(); } function emitVariableDeclaration(node) { - if (node.kind !== 211 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 215 || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { - writeTextOfNode(currentSourceFile, node.name); - if ((node.kind === 141 || node.kind === 140) && ts.hasQuestionToken(node)) { + writeTextOfNode(currentText, node.name); + if ((node.kind === 143 || node.kind === 142) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 141 || node.kind === 140) && node.parent.kind === 155) { + if ((node.kind === 143 || node.kind === 142) && node.parent.kind === 157) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 16)) { + else if (!(node.flags & 8)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 211) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 215) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 === 141 || node.kind === 140) { - if (node.flags & 64) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + else if (node.kind === 143 || node.kind === 142) { + if (node.flags & 32) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : 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 === 214) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + else if (node.parent.kind === 218) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; } else { - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; } } } - function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: node, @@ -23994,15 +26097,15 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187) { + if (element.kind !== 191) { elements.push(element); } } emitCommaList(elements, emitBindingElement); } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: bindingElement, @@ -24014,7 +26117,7 @@ var ts; emitBindingPattern(bindingElement.name); } else { - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); writeTypeOfDeclaration(bindingElement, undefined, getBindingElementTypeVisibilityError); } } @@ -24054,13 +26157,13 @@ var ts; if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node); - writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 16)) { + emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : 64)); + writeTextOfNode(currentText, node.name); + if (!(node.flags & 8)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { - var anotherAccessor = node.kind === 145 ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 147 ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -24073,23 +26176,23 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 145 + return accessor.kind === 147 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type : undefined; } } - function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 146) { - if (accessorWithTypeAnnotation.parent.flags & 64) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + if (accessorWithTypeAnnotation.kind === 148) { + if (accessorWithTypeAnnotation.parent.flags & 32) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; } @@ -24100,16 +26203,16 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 64) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + if (accessorWithTypeAnnotation.flags & 32) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; @@ -24128,21 +26231,21 @@ var ts; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 213) { + if (node.kind === 217) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 143) { - emitClassMemberDeclarationFlags(node); + else if (node.kind === 145 || node.kind === 146) { + emitClassMemberDeclarationFlags(node.flags); } - if (node.kind === 213) { + if (node.kind === 217) { write("function "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } - else if (node.kind === 144) { + else if (node.kind === 146) { write("constructor"); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); if (ts.hasQuestionToken(node)) { write("?"); } @@ -24155,33 +26258,34 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { - if (node.kind === 148 || node.kind === 153) { - write("new "); - } - emitTypeParameters(node.typeParameters); - if (node.kind === 149) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + if (node.kind === 151) { + emitClassMemberDeclarationFlags(node.flags); write("["); } else { + if (node.kind === 150 || node.kind === 155) { + write("new "); + } + emitTypeParameters(node.typeParameters); write("("); } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 149) { + if (node.kind === 151) { write("]"); } else { write(")"); } - var isFunctionTypeOrConstructorType = node.kind === 152 || node.kind === 153; - if (isFunctionTypeOrConstructorType || node.parent.kind === 155) { + var isFunctionTypeOrConstructorType = node.kind === 154 || node.kind === 155; + if (isFunctionTypeOrConstructorType || node.parent.kind === 157) { if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 144 && !(node.flags & 16)) { + else if (node.kind !== 146 && !(node.flags & 8)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -24189,49 +26293,49 @@ var ts; write(";"); writeLine(); } - function getReturnTypeVisibilityError(symbolAccesibilityResult) { + function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 148: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + case 150: + diagnosticMessage = symbolAccessibilityResult.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 147: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + case 149: + diagnosticMessage = symbolAccessibilityResult.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 149: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + case 151: + diagnosticMessage = symbolAccessibilityResult.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 143: - case 142: - if (node.flags & 64) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + case 145: + case 144: + if (node.flags & 32) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : 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 === 214) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + else if (node.parent.kind === 218) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 213: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + case 217: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; @@ -24255,68 +26359,68 @@ var ts; emitBindingPattern(node.name); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } if (resolver.isOptionalParameter(node)) { write("?"); } decreaseIndent(); - if (node.parent.kind === 152 || - node.parent.kind === 153 || - node.parent.parent.kind === 155) { + if (node.parent.kind === 154 || + node.parent.kind === 155 || + node.parent.parent.kind === 157) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 16)) { + else if (!(node.parent.flags & 8)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } - function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: node, typeName: node.name } : undefined; } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 144: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + case 146: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 148: - return symbolAccesibilityResult.errorModuleName ? + case 150: + return symbolAccessibilityResult.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 147: - return symbolAccesibilityResult.errorModuleName ? + case 149: + return symbolAccessibilityResult.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 143: - case 142: - if (node.parent.flags & 64) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + case 145: + case 144: + if (node.parent.flags & 32) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : 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 === 214) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + else if (node.parent.parent.kind === 218) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? 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 213: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + case 217: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; @@ -24325,12 +26429,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 161) { + if (bindingPattern.kind === 165) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 162) { + else if (bindingPattern.kind === 166) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -24341,20 +26445,12 @@ var ts; } } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.kind === 187) { + if (bindingElement.kind === 191) { write(" "); } - else if (bindingElement.kind === 163) { + else if (bindingElement.kind === 167) { if (bindingElement.propertyName) { - writeTextOfNode(currentSourceFile, bindingElement.propertyName); + writeTextOfNode(currentText, bindingElement.propertyName); write(": "); } if (bindingElement.name) { @@ -24366,7 +26462,7 @@ var ts; if (bindingElement.dotDotDotToken) { write("..."); } - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); } } } @@ -24374,59 +26470,75 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 213: - case 218: - case 221: - case 215: - case 214: - case 216: case 217: - return emitModuleElement(node, isModuleElementVisible(node)); - case 193: - return emitModuleElement(node, isVariableStatementVisible(node)); case 222: + case 225: + case 219: + case 218: + case 220: + case 221: + return emitModuleElement(node, isModuleElementVisible(node)); + case 197: + return emitModuleElement(node, isVariableStatementVisible(node)); + case 226: return emitModuleElement(node, !node.importClause); - case 228: + case 232: return emitExportDeclaration(node); + case 146: + case 145: case 144: + return writeFunctionDeclaration(node); + case 150: + case 149: + case 151: + return emitSignatureDeclarationWithJsDocComments(node); + case 147: + case 148: + return emitAccessorDeclaration(node); case 143: case 142: - return writeFunctionDeclaration(node); - case 148: - case 147: - case 149: - return emitSignatureDeclarationWithJsDocComments(node); - case 145: - case 146: - return emitAccessorDeclaration(node); - case 141: - case 140: return emitPropertyDeclaration(node); - case 247: + case 251: return emitEnumMemberDeclaration(node); - case 227: + case 231: return emitExportAssignment(node); - case 248: + case 252: return emitSourceFile(node); } } - function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 4096 - ? referencedFile.fileName - : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) - ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") - : ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); - referencePathsOutput += "/// " + newLine; + function writeReferencePath(referencedFile, addBundledFileReference) { + var declFileName; + var addedBundledEmitReference = false; + if (ts.isDeclarationFile(referencedFile)) { + declFileName = referencedFile.fileName; + } + else { + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + } + if (declFileName) { + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); + referencePathsOutput += "/// " + newLine; + } + return addedBundledEmitReference; + function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + if (isBundledEmit && !addBundledFileReference) { + return; + } + ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); + declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; + addedBundledEmitReference = isBundledEmit; + } } } - function writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); - if (!emitDeclarationResult.reportedDeclarationError) { + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; + if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } + return emitSkipped; function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { var appliedSyncOutputPos = 0; var declarationOutput = ""; @@ -24445,10 +26557,18 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); + function getResolvedExternalModuleName(host, file) { + return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || ts.isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; var entities = { "quot": 0x0022, "amp": 0x0026, @@ -24709,39 +26829,19 @@ var ts; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\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};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\n return new Promise(function (resolve, reject) {\n generator = generator.call(thisArg, _arguments);\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\n function onfulfill(value) { try { step(\"next\", value); } catch (e) { reject(e); } }\n function onreject(value) { try { step(\"throw\", value); } catch (e) { reject(e); } }\n function step(verb, value) {\n var result = generator[verb](value);\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\n }\n step(\"next\", void 0);\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || 0; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 ? 5 : 0; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - var diagnostics = []; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emitSkipped = false; var newLine = host.getNewLine(); - var jsxDesugaring = host.getCompilerOptions().jsx !== 1; - var shouldEmitJsx = function (s) { return (s.languageVariant === 1 && !jsxDesugaring); }; - if (targetSourceFile === undefined) { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - if (compilerOptions.outFile || compilerOptions.out) { - emitFile(compilerOptions.outFile || compilerOptions.out); - } - } - else { - if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) { - emitFile(compilerOptions.outFile || compilerOptions.out); - } - } - diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics); + var emitJavaScript = createFileEmitter(); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { - emitSkipped: false, - diagnostics: diagnostics, + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), sourceMaps: sourceMapDataList }; function isUniqueLocalName(name, container) { @@ -24785,86 +26885,136 @@ var ts; } } } - function emitJavaScript(jsFilePath, root) { + function createFileEmitter() { var writer = ts.createTextWriter(newLine); var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); + var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; var currentSourceFile; + var currentText; + var currentLineMap; + var currentFileIdentifiers; + var renamedDependencies; + var isEs6Module; + var isCurrentFileExternalModule; var exportFunctionForFile; - var generatedNameSet = {}; - var nodeToGeneratedName = []; + var contextObjectForFile; + var generatedNameSet; + var nodeToGeneratedName; var computedPropertyNamesToGeneratedNames; + var decoratedClassAliases; var convertedLoopState; - var extendsEmitted = false; - var decorateEmitted = false; - var paramEmitted = false; - var awaiterEmitted = false; + var extendsEmitted; + var decorateEmitted; + var paramEmitted; + var awaiterEmitted; var tempFlags = 0; var tempVariables; var tempParameters; var externalImports; var exportSpecifiers; var exportEquals; - var hasExportStars; - var writeEmittedFiles = writeJavaScriptFile; + var hasExportStarsToExportValues; var detachedCommentsInfo; - var writeComment = ts.writeCommentRange; - var emit = emitNodeWithCommentsAndWithoutSourcemap; - var emitStart = function (node) { }; - var emitEnd = function (node) { }; - var emitToken = emitTokenText; - var scopeEmitStart = function (scopeDeclaration, scopeName) { }; - var scopeEmitEnd = function () { }; var sourceMapData; + var isOwnFileEmit; var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; + var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; var moduleEmitDelegates = (_a = {}, - _a[5] = emitES6Module, - _a[2] = emitAMDModule, - _a[4] = emitSystemModule, - _a[3] = emitUMDModule, - _a[1] = emitCommonJSModule, + _a[ts.ModuleKind.ES6] = emitES6Module, + _a[ts.ModuleKind.AMD] = emitAMDModule, + _a[ts.ModuleKind.System] = emitSystemModule, + _a[ts.ModuleKind.UMD] = emitUMDModule, + _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, _a ); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - initializeEmitterWithSourceMaps(); + var bundleEmitDelegates = (_b = {}, + _b[ts.ModuleKind.ES6] = function () { }, + _b[ts.ModuleKind.AMD] = emitAMDModule, + _b[ts.ModuleKind.System] = emitSystemModule, + _b[ts.ModuleKind.UMD] = function () { }, + _b[ts.ModuleKind.CommonJS] = function () { }, + _b + ); + return doEmit; + function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + generatedNameSet = {}; + nodeToGeneratedName = []; + decoratedClassAliases = []; + isOwnFileEmit = !isBundledEmit; + if (isBundledEmit && modulekind) { + ts.forEach(sourceFiles, emitEmitHelpers); + } + ts.forEach(sourceFiles, emitSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# sourceMappingURL=" + sourceMappingURL); + } + writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM); + sourceMap.reset(); + writer.reset(); + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + exportFunctionForFile = undefined; + contextObjectForFile = undefined; + generatedNameSet = undefined; + nodeToGeneratedName = undefined; + decoratedClassAliases = undefined; + computedPropertyNamesToGeneratedNames = undefined; + convertedLoopState = undefined; + extendsEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + tempFlags = 0; + tempVariables = undefined; + tempParameters = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = undefined; + detachedCommentsInfo = undefined; + sourceMapData = undefined; + isEs6Module = false; + renamedDependencies = undefined; + isCurrentFileExternalModule = false; } - if (root) { - emitSourceFile(root); - } - else { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!isExternalModuleOrDeclarationFile(sourceFile)) { - emitSourceFile(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), compilerOptions.emitBOM); - return; function emitSourceFile(sourceFile) { currentSourceFile = sourceFile; + currentText = sourceFile.text; + currentLineMap = ts.getLineStarts(sourceFile); exportFunctionForFile = undefined; - emit(sourceFile); + contextObjectForFile = undefined; + isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"]; + renamedDependencies = sourceFile.renamedDependencies; + currentFileIdentifiers = sourceFile.identifiers; + isCurrentFileExternalModule = ts.isExternalModule(sourceFile); + setSourceFile(sourceFile); + emitNodeWithCommentsAndWithoutSourcemap(sourceFile); } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentSourceFile.identifiers, name) && + !ts.hasProperty(currentFileIdentifiers, name) && !ts.hasProperty(generatedNameSet, name); } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_19 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_19)) { + var name_21 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_21)) { tempFlags |= flags; - return name_19; + return name_21; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_20 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_20)) { - return name_20; + var name_22 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_22)) { + return name_22; } } } @@ -24902,17 +27052,17 @@ var ts; switch (node.kind) { case 69: return makeUniqueName(node.text); - case 218: - case 217: - return generateNameForModuleOrEnum(node); case 222: - case 228: + case 221: + return generateNameForModuleOrEnum(node); + case 226: + case 232: return generateNameForImportOrExportDeclaration(node); - case 213: - case 214: - case 227: + case 217: + case 218: + case 231: return generateNameForExportDefault(); - case 186: + case 190: return generateNameForClassExpression(); } } @@ -24920,289 +27070,14 @@ var ts; var id = ts.getNodeId(node); return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); } - function initializeEmitterWithSourceMaps() { - var sourceMapDir; - var sourceMapSourceIndex = -1; - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; + function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark) { + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false); } - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - var encodedStr = ""; - do { - var currentDigit = inValue & 31; - inValue = inValue >> 5; - if (inValue > 0) { - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); } - function recordSourceMapSpan(pos) { - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine !== emittedLine || - lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || - (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - sourceMapData.inputSourceFileNames.push(node.fileName); - if (compilerOptions.inlineSources) { - if (!sourceMapData.sourceMapSourcesContent) { - sourceMapData.sourceMapSourcesContent = []; - } - sourceMapData.sourceMapSourcesContent.push(node.text); - } - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - var name_21 = node.name; - if (!name_21 || name_21.kind !== 136) { - scopeName = "." + scopeName; - } - scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - recordScopeNameStart(scopeName); - } - else if (node.kind === 213 || - node.kind === 173 || - node.kind === 143 || - node.kind === 142 || - node.kind === 145 || - node.kind === 146 || - node.kind === 218 || - node.kind === 214 || - node.kind === 217) { - if (node.name) { - var name_22 = node.name; - scopeName = name_22.kind === 136 - ? ts.getTextOfNode(name_22) - : node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - ts.writeCommentRange(currentSourceFile, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) { - if (typeof JSON !== "undefined") { - var map_1 = { - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }; - if (sourcesContent !== undefined) { - map_1.sourcesContent = sourcesContent; - } - return JSON.stringify(map_1); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\" " + (sourcesContent !== undefined ? ",\"sourcesContent\":[" + serializeStringArray(sourcesContent) + "]" : "") + "}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) { - encodeLastRecordedSourceMapSpan(); - var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent); - sourceMapDataList.push(sourceMapData); - var sourceMapUrl; - if (compilerOptions.inlineSourceMap) { - var base64SourceMapText = ts.convertToBase64(sourceMapText); - sourceMapUrl = "//# sourceMappingURL=data:application/json;base64," + base64SourceMapText; - } - else { - ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, false); - sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL; - } - writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark); - } - var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: undefined, - sourceMapDecodedMappings: [] - }; - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithSourceMap(node) { - if (node) { - if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node); - } - if (node.kind !== 248) { - recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node); - } - } - } - function emitNodeWithCommentsAndWithSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithCommentsAndWithSourcemap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, writeByteOrderMark) { - ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark); } function createTempVariable(flags) { var result = ts.createSynthesizedNode(69); @@ -25233,7 +27108,9 @@ var ts; write(";"); } } - function emitTokenText(tokenKind, startPos, emitFn) { + function emitToken(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentText, startPos); + emitPos(tokenStartPos); var tokenString = ts.tokenToString(tokenKind); if (emitFn) { emitFn(); @@ -25241,7 +27118,9 @@ var ts; else { write(tokenString); } - return startPos + tokenString.length; + var tokenEndPos = tokenStartPos + tokenString.length; + emitPos(tokenEndPos); + return tokenEndPos; } function emitOptional(prefix, node) { if (node) { @@ -25258,11 +27137,6 @@ var ts; write(")"); } } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { ts.Debug.assert(nodes.length > 0); increaseIndent(); @@ -25371,7 +27245,7 @@ var ts; return getQuotedEscapedLiteralText("\"", node.text, "\""); } if (node.parent) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + return ts.getTextOfNodeFromSourceText(currentText, node); } switch (node.kind) { case 9: @@ -25393,7 +27267,7 @@ var ts; return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote; } function emitDownlevelRawTemplateLiteral(node) { - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + var text = ts.getTextOfNodeFromSourceText(currentText, node); var isLast = node.kind === 11 || node.kind === 14; text = text.substring(1, text.length - (isLast ? 1 : 2)); text = text.replace(/\r\n?/g, "\n"); @@ -25428,10 +27302,10 @@ var ts; emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); write("("); emit(tempVariable); - if (node.template.kind === 183) { + if (node.template.kind === 187) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 181 + var needsParens = templateSpan.expression.kind === 185 && templateSpan.expression.operatorToken.kind === 24; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -25455,7 +27329,7 @@ var ts; } for (var i = 0, n = node.templateSpans.length; i < n; i++) { var templateSpan = node.templateSpans[i]; - var needsParens = templateSpan.expression.kind !== 172 + var needsParens = templateSpan.expression.kind !== 176 && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1; if (i > 0 || headEmitted) { write(" + "); @@ -25475,11 +27349,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 168: - case 169: - return parent.expression === template; - case 170: case 172: + case 173: + return parent.expression === template; + case 174: + case 176: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1; @@ -25487,7 +27361,7 @@ var ts; } function comparePrecedenceToBinaryPlus(expression) { switch (expression.kind) { - case 181: + case 185: switch (expression.operatorToken.kind) { case 37: case 39: @@ -25499,8 +27373,8 @@ var ts; default: return -1; } - case 184: - case 182: + case 188: + case 186: return -1; default: return 1; @@ -25523,13 +27397,13 @@ var ts; } } function emitAttributeName(name) { - if (/[A-Za-z_]+[\w*]/.test(name.text)) { - write("\""); + if (/^[A-Za-z_]\w*$/.test(name.text)) { emit(name); - write("\""); } else { + write("\""); emit(name); + write("\""); } } function emitJsxAttribute(node) { @@ -25544,7 +27418,7 @@ var ts; } function emitJsxElement(openingNode, children) { var syntheticReactRef = ts.createSynthesizedNode(69); - syntheticReactRef.text = "React"; + syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; syntheticReactRef.parent = openingNode; emitLeadingComments(openingNode); emitExpressionIdentifier(syntheticReactRef); @@ -25556,37 +27430,37 @@ var ts; } else { var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 239; })) { + if (ts.forEach(attrs, function (attr) { return attr.kind === 243; })) { emitExpressionIdentifier(syntheticReactRef); write(".__spread("); var haveOpenedObjectLiteral = false; - for (var i_1 = 0; i_1 < attrs.length; i_1++) { - if (attrs[i_1].kind === 239) { - if (i_1 === 0) { + for (var i = 0; i < attrs.length; i++) { + if (attrs[i].kind === 243) { + if (i === 0) { write("{}, "); } if (haveOpenedObjectLiteral) { write("}"); haveOpenedObjectLiteral = false; } - if (i_1 > 0) { + if (i > 0) { write(", "); } - emit(attrs[i_1].expression); + emit(attrs[i].expression); } else { - ts.Debug.assert(attrs[i_1].kind === 238); + ts.Debug.assert(attrs[i].kind === 242); if (haveOpenedObjectLiteral) { write(", "); } else { haveOpenedObjectLiteral = true; - if (i_1 > 0) { + if (i > 0) { write(", "); } write("{"); } - emitJsxAttribute(attrs[i_1]); + emitJsxAttribute(attrs[i]); } } if (haveOpenedObjectLiteral) @@ -25595,7 +27469,7 @@ var ts; } else { write("{"); - for (var i = 0; i < attrs.length; i++) { + for (var i = 0, n = attrs.length; i < n; i++) { if (i > 0) { write(", "); } @@ -25605,32 +27479,52 @@ var ts; } } if (children) { - for (var i = 0; i < children.length; i++) { - if (children[i].kind === 240 && !(children[i].expression)) { - continue; - } - if (children[i].kind === 236) { - var text = getTextToEmit(children[i]); - if (text !== undefined) { - write(", \""); - write(text); - write("\""); + var firstChild; + var multipleEmittableChildren = false; + for (var i = 0, n = children.length; i < n; i++) { + var jsxChild = children[i]; + if (isJsxChildEmittable(jsxChild)) { + if (!firstChild) { + write(", "); + firstChild = jsxChild; + } + else { + if (!multipleEmittableChildren) { + multipleEmittableChildren = true; + increaseIndent(); + writeLine(); + emit(firstChild); + } + write(", "); + writeLine(); + emit(jsxChild); } } + } + if (multipleEmittableChildren) { + decreaseIndent(); + } + else if (firstChild) { + if (firstChild.kind !== 237 && firstChild.kind !== 238) { + emit(firstChild); + } else { - write(", "); - emit(children[i]); + increaseIndent(); + writeLine(); + emit(firstChild); + writeLine(); + decreaseIndent(); } } } write(")"); emitTrailingComments(openingNode); } - if (node.kind === 233) { + if (node.kind === 237) { emitJsxElement(node.openingElement, node.children); } else { - ts.Debug.assert(node.kind === 234); + ts.Debug.assert(node.kind === 238); emitJsxElement(node); } } @@ -25652,11 +27546,11 @@ var ts; if (i > 0) { write(" "); } - if (attribs[i].kind === 239) { + if (attribs[i].kind === 243) { emitJsxSpreadAttribute(attribs[i]); } else { - ts.Debug.assert(attribs[i].kind === 238); + ts.Debug.assert(attribs[i].kind === 242); emitJsxAttribute(attribs[i]); } } @@ -25664,11 +27558,11 @@ var ts; function emitJsxOpeningOrSelfClosingElement(node) { write("<"); emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 234)) { + if (node.attributes.length > 0 || (node.kind === 238)) { write(" "); } emitAttributes(node.attributes); - if (node.kind === 234) { + if (node.kind === 238) { write("/>"); } else { @@ -25687,20 +27581,20 @@ var ts; } emitJsxClosingElement(node.closingElement); } - if (node.kind === 233) { + if (node.kind === 237) { emitJsxElement(node); } else { - ts.Debug.assert(node.kind === 234); + ts.Debug.assert(node.kind === 238); emitJsxOpeningOrSelfClosingElement(node); } } function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 163); + ts.Debug.assert(node.kind !== 167); if (node.kind === 9) { emitLiteral(node); } - else if (node.kind === 136) { + else if (node.kind === 138) { if (ts.nodeIsDecorated(node.parent)) { if (!computedPropertyNamesToGeneratedNames) { computedPropertyNamesToGeneratedNames = []; @@ -25723,7 +27617,7 @@ var ts; write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } write("\""); } @@ -25731,74 +27625,71 @@ var ts; function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 164: - case 189: - case 181: case 168: - case 241: - case 136: - case 182: - case 139: - case 175: - case 197: - case 167: - case 227: - case 195: - case 188: - case 199: - case 200: - case 201: - case 196: - case 234: - case 235: - case 239: - case 240: - case 169: - case 172: - case 180: - case 179: - case 204: - case 246: + case 193: case 185: - case 206: - case 170: - case 190: - case 208: - case 171: - case 176: - case 177: - case 198: - case 205: - case 184: - return true; - case 163: - case 247: - case 138: + case 172: case 245: + case 138: + case 186: case 141: - case 211: - return parent.initializer === node; - case 166: - return parent.expression === node; - case 174: + case 179: + case 201: + case 171: + case 231: + case 199: + case 192: + case 203: + case 204: + case 205: + case 200: + case 241: + case 238: + case 239: + case 243: + case 244: case 173: + case 176: + case 184: + case 183: + case 208: + case 250: + case 189: + case 210: + case 174: + case 194: + case 212: + case 175: + case 180: + case 181: + case 202: + case 209: + case 188: + return true; + case 167: + case 251: + case 140: + case 249: + case 143: + case 215: + return parent.initializer === node; + case 170: + return parent.expression === node; + case 178: + case 177: return parent.body === node; - case 221: + case 225: return parent.moduleReference === node; - case 135: + case 137: return parent.left === node; } return false; } function emitExpressionIdentifier(node) { - if (resolver.getNodeCheckFlags(node) & 2048) { - write("_arguments"); - return; - } var container = resolver.getReferencedExportContainer(node); if (container) { - if (container.kind === 248) { - if (modulekind !== 5 && modulekind !== 4) { + if (container.kind === 252) { + if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { write("exports."); } } @@ -25808,18 +27699,18 @@ var ts; } } else { - if (modulekind !== 5) { + if (modulekind !== ts.ModuleKind.ES6) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { - if (declaration.kind === 223) { + if (declaration.kind === 227) { write(getGeneratedNameForNode(declaration.parent)); write(languageVersion === 0 ? "[\"default\"]" : ".default"); return; } - else if (declaration.kind === 226) { + else if (declaration.kind === 230) { write(getGeneratedNameForNode(declaration.parent.parent.parent)); var name_23 = declaration.propertyName || declaration.name; - var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_23); + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_23); if (languageVersion === 0 && identifier === "default") { write("[\"default\"]"); } @@ -25831,30 +27722,40 @@ var ts; } } } - if (languageVersion !== 2) { - var declaration = resolver.getReferencedNestedRedeclaration(node); + if (languageVersion < 2) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration) { write(getGeneratedNameForNode(declaration.name)); return; } } + else if (resolver.getNodeCheckFlags(node) & 1048576) { + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = decoratedClassAliases[ts.getNodeId(declaration)]; + if (classAlias !== undefined) { + write(classAlias); + return; + } + } + } } if (ts.nodeIsSynthesized(node)) { write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } } - function isNameOfNestedRedeclaration(node) { + function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node) { if (languageVersion < 2) { - var parent_6 = node.parent; - switch (parent_6.kind) { - case 163: - case 214: - case 217: - case 211: - return parent_6.name === node && resolver.isNestedRedeclaration(parent_6); + var parent_8 = node.parent; + switch (parent_8.kind) { + case 167: + case 218: + case 221: + case 215: + return parent_8.name === node && resolver.isDeclarationWithCollidingName(parent_8); } } return false; @@ -25873,20 +27774,23 @@ var ts; else if (isExpressionIdentifier(node)) { emitExpressionIdentifier(node); } - else if (isNameOfNestedRedeclaration(node)) { + else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { write(getGeneratedNameForNode(node)); } else if (ts.nodeIsSynthesized(node)) { write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } } function emitThis(node) { if (resolver.getNodeCheckFlags(node) & 2) { write("_this"); } + else if (convertedLoopState) { + write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); + } else { write("this"); } @@ -25960,10 +27864,10 @@ var ts; } } function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 181 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { + if (node.parent.kind === 185 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { return true; } - else if (node.parent.kind === 182 && node.parent.condition === node) { + else if (node.parent.kind === 186 && node.parent.condition === node) { return true; } return false; @@ -25971,11 +27875,11 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 69: - case 164: - case 166: - case 167: case 168: + case 170: + case 171: case 172: + case 176: return false; } return true; @@ -25992,17 +27896,17 @@ var ts; write(", "); } var e = elements[pos]; - if (e.kind === 185) { + if (e.kind === 189) { e = e.expression; emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 168) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 185) { + while (i < length && elements[i].kind !== 189) { i++; } write("["); @@ -26025,7 +27929,7 @@ var ts; } } function isSpreadElementExpression(node) { - return node.kind === 185; + return node.kind === 189; } function emitArrayLiteral(node) { var elements = node.elements; @@ -26038,7 +27942,7 @@ var ts; write("]"); } else { - emitListWithSpread(elements, true, (node.flags & 1024) !== 0, elements.hasTrailingComma, true); + emitListWithSpread(elements, true, node.multiLine, elements.hasTrailingComma, true); } } function emitObjectLiteralBody(node, numElements) { @@ -26053,7 +27957,7 @@ var ts; emitLinePreservingList(node, properties, languageVersion >= 1, true); } else { - var multiLine = (node.flags & 1024) !== 0; + var multiLine = node.multiLine; if (!multiLine) { write(" "); } @@ -26072,7 +27976,7 @@ var ts; write("}"); } function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = (node.flags & 1024) !== 0; + var multiLine = node.multiLine; var properties = node.properties; write("("); if (multiLine) { @@ -26086,7 +27990,7 @@ var ts; writeComma(); var property = properties[i]; emitStart(property); - if (property.kind === 145 || property.kind === 146) { + if (property.kind === 147 || property.kind === 148) { var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; @@ -26137,13 +28041,13 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 245) { + if (property.kind === 249) { emit(property.initializer); } - else if (property.kind === 246) { + else if (property.kind === 250) { emitExpressionIdentifier(property.name); } - else if (property.kind === 143) { + else if (property.kind === 145) { emitFunctionDeclaration(property); } else { @@ -26175,7 +28079,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 === 136) { + if (properties[i].name.kind === 138) { numInitialNonComputedProperties = i; break; } @@ -26189,35 +28093,35 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(181, startsOnNewLine); + var result = ts.createSynthesizedNode(185, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(166); + var result = ts.createSynthesizedNode(170); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(21); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(167); + var result = ts.createSynthesizedNode(171); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; } function parenthesizeForAccess(expr) { - while (expr.kind === 171 || expr.kind === 189) { + while (expr.kind === 175 || expr.kind === 193) { expr = expr.expression; } if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 169 && + expr.kind !== 173 && expr.kind !== 8) { return expr; } - var node = ts.createSynthesizedNode(172); + var node = ts.createSynthesizedNode(176); node.expression = expr; return node; } @@ -26244,11 +28148,11 @@ var ts; } function isNamespaceExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 248; + return container && container.kind !== 252; } function emitShorthandPropertyAssignment(node) { - writeTextOfNode(currentSourceFile, node.name); - if (languageVersion < 2 || isNamespaceExportReference(node.name)) { + writeTextOfNode(currentText, node.name); + if (modulekind !== ts.ModuleKind.ES6 || isNamespaceExportReference(node.name)) { write(": "); emit(node.name); } @@ -26262,7 +28166,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 166 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 170 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -26273,7 +28177,7 @@ var ts; if (compilerOptions.isolatedModules) { return undefined; } - return node.kind === 166 || node.kind === 167 + return node.kind === 170 || node.kind === 171 ? resolver.getConstantValue(node) : undefined; } @@ -26296,12 +28200,20 @@ var ts; if (tryEmitConstantValue(node)) { return; } + if (languageVersion === 2 && + node.expression.kind === 95 && + isInAsyncMethodWithSuperInES6(node)) { + var name_25 = ts.createSynthesizedNode(9); + name_25.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_25); + return; + } emit(node.expression); var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); - var shouldEmitSpace; + var shouldEmitSpace = false; if (!indentedBeforeDot) { if (node.expression.kind === 8) { - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); + var text = ts.getTextOfNodeFromSourceText(currentText, node.expression); shouldEmitSpace = text.indexOf(ts.tokenToString(21)) < 0; } else { @@ -26353,25 +28265,34 @@ var ts; } emitExpressionIdentifier(node); break; - case 135: + case 137: emitQualifiedNameAsExpression(node, useFallback); break; + default: + emitNodeWithoutSourceMap(node); + break; } } function emitIndexedAccess(node) { if (tryEmitConstantValue(node)) { return; } + if (languageVersion === 2 && + node.expression.kind === 95 && + isInAsyncMethodWithSuperInES6(node)) { + emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression); + return; + } emit(node.expression); write("["); emit(node.argumentExpression); write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 185; }); + return ts.forEach(elements, function (e) { return e.kind === 189; }); } function skipParentheses(node) { - while (node.kind === 172 || node.kind === 171 || node.kind === 189) { + while (node.kind === 176 || node.kind === 175 || node.kind === 193) { node = node.expression; } return node; @@ -26392,12 +28313,12 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 166) { + if (expr.kind === 170) { target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 167) { + else if (expr.kind === 171) { target = emitCallTarget(expr.expression); write("["); emit(expr.argumentExpression); @@ -26426,23 +28347,42 @@ var ts; emitListWithSpread(node.arguments, false, false, false, true); write(")"); } + function isInAsyncMethodWithSuperInES6(node) { + if (languageVersion === 2) { + var container = ts.getSuperContainer(node, false); + if (container && resolver.getNodeCheckFlags(container) & (2048 | 4096)) { + return true; + } + } + return false; + } + function emitSuperAccessInAsyncMethod(superNode, argumentExpression) { + var container = ts.getSuperContainer(superNode, false); + var isSuperBinding = resolver.getNodeCheckFlags(container) & 4096; + write("_super("); + emit(argumentExpression); + write(isSuperBinding ? ").value" : ")"); + } function emitCallExpression(node) { if (languageVersion < 2 && hasSpreadElement(node.arguments)) { emitCallWithSpread(node); return; } + var expression = node.expression; var superCall = false; - if (node.expression.kind === 95) { - emitSuper(node.expression); + var isAsyncMethodWithSuper = false; + if (expression.kind === 95) { + emitSuper(expression); superCall = true; } else { - emit(node.expression); - superCall = node.expression.kind === 166 && node.expression.expression.kind === 95; + superCall = ts.isSuperPropertyOrElementAccess(expression); + isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node); + emit(expression); } - if (superCall && languageVersion < 2) { + if (superCall && (languageVersion < 2 || isAsyncMethodWithSuper)) { write(".call("); - emitThis(node.expression); + emitThis(expression); if (node.arguments.length) { write(", "); emitCommaList(node.arguments); @@ -26489,21 +28429,21 @@ var ts; } } function emitParenExpression(node) { - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 174) { - if (node.expression.kind === 171 || node.expression.kind === 189) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 178) { + if (node.expression.kind === 175 || node.expression.kind === 193) { var operand = node.expression.expression; - while (operand.kind === 171 || operand.kind === 189) { + while (operand.kind === 175 || operand.kind === 193) { operand = operand.expression; } - if (operand.kind !== 179 && - operand.kind !== 177 && - operand.kind !== 176 && - operand.kind !== 175 && + if (operand.kind !== 183 && + operand.kind !== 181 && operand.kind !== 180 && - operand.kind !== 169 && - !(operand.kind === 168 && node.parent.kind === 169) && - !(operand.kind === 173 && node.parent.kind === 168) && - !(operand.kind === 8 && node.parent.kind === 166)) { + operand.kind !== 179 && + operand.kind !== 184 && + operand.kind !== 173 && + !(operand.kind === 172 && node.parent.kind === 173) && + !(operand.kind === 177 && node.parent.kind === 172) && + !(operand.kind === 8 && node.parent.kind === 170)) { emit(operand); return; } @@ -26532,21 +28472,22 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 || node.parent.kind === 163); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 215 || node.parent.kind === 167); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, true); } function emitPrefixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + var exportChanged = (node.operator === 41 || node.operator === 42) && + isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); if (exportChanged) { write(exportFunctionForFile + "(\""); emitNodeWithoutSourceMap(node.operand); write("\", "); } write(ts.tokenToString(node.operator)); - if (node.operand.kind === 179) { + if (node.operand.kind === 183) { var operand = node.operand; if (node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) { write(" "); @@ -26587,12 +28528,12 @@ var ts; if (!node || !isCurrentFileSystemExternalModule()) { return false; } - var current = node; + var current = ts.getRootDeclaration(node).parent; while (current) { - if (current.kind === 248) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 2) !== 0); + if (current.kind === 252) { + return !isExported || ((ts.getCombinedNodeFlags(node) & 1) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 219) { + else if (ts.isDeclaration(current)) { return false; } else { @@ -26608,14 +28549,14 @@ var ts; if (ts.isElementAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(167, false); + synthesizedLHS = ts.createSynthesizedNode(171, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; if (leftHandSideExpression.argumentExpression.kind !== 8 && leftHandSideExpression.argumentExpression.kind !== 9) { var tempArgumentExpression = createAndRecordTempVariable(268435456); synthesizedLHS.argumentExpression = tempArgumentExpression; - emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, true); + emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, true, leftHandSideExpression.expression); } else { synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; @@ -26625,7 +28566,7 @@ var ts; else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(166, false); + synthesizedLHS = ts.createSynthesizedNode(170, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; synthesizedLHS.dotToken = leftHandSideExpression.dotToken; @@ -26653,8 +28594,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 && node.operatorToken.kind === 56 && - (node.left.kind === 165 || node.left.kind === 164)) { - emitDestructuring(node, node.parent.kind === 195); + (node.left.kind === 169 || node.left.kind === 168)) { + emitDestructuring(node, node.parent.kind === 199); } else { var exportChanged = node.operatorToken.kind >= 56 && @@ -26706,7 +28647,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 192) { + if (node && node.kind === 196) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -26720,22 +28661,20 @@ var ts; } emitToken(15, node.pos); increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 219) { - ts.Debug.assert(node.parent.kind === 218); + if (node.kind === 223) { + ts.Debug.assert(node.parent.kind === 222); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 219) { + if (node.kind === 223) { emitTempDeclarations(true); } decreaseIndent(); writeLine(); emitToken(16, node.statements.end); - scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 192) { + if (node.kind === 196) { write(" "); emit(node); } @@ -26747,7 +28686,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 174); + emitParenthesizedIf(node.expression, node.expression.kind === 178); write(";"); } function emitIfStatement(node) { @@ -26760,7 +28699,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(80, node.thenStatement.end); - if (node.elseStatement.kind === 196) { + if (node.elseStatement.kind === 200) { write(" "); emit(node.elseStatement); } @@ -26780,7 +28719,7 @@ var ts; else { emitNormalLoopBody(node, true); } - if (node.statement.kind === 192) { + if (node.statement.kind === 196) { write(" "); } else { @@ -26804,42 +28743,31 @@ var ts; emitNormalLoopBody(node, true); } } - function tryEmitStartOfVariableDeclarationList(decl, startPos) { + function tryEmitStartOfVariableDeclarationList(decl) { if (shouldHoistVariable(decl, true)) { return false; } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576) === 0) { + if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 3072) === 0) { for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { var varDecl = _b[_a]; hoistVariableDeclarationFromLoop(convertedLoopState, varDecl); } return false; } - var tokenKind = 102; + emitStart(decl); if (decl && languageVersion >= 2) { if (ts.isLet(decl)) { - tokenKind = 108; + write("let "); } else if (ts.isConst(decl)) { - tokenKind = 74; + write("const "); + } + else { + write("var "); } - } - if (startPos !== undefined) { - emitToken(tokenKind, startPos); - write(" "); } else { - switch (tokenKind) { - case 102: - write("var "); - break; - case 108: - write("let "); - break; - case 74: - write("const "); - break; - } + write("var "); } return true; } @@ -26871,7 +28799,7 @@ var ts; } else { var loop = convertLoopBody(node); - if (node.parent.kind === 207) { + if (node.parent.kind === 211) { emitLabelAndColon(node.parent); } loopEmitter(node, loop); @@ -26881,49 +28809,67 @@ var ts; var functionName = makeUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 199: - case 200: - case 201: - if (node.initializer.kind === 212) { + case 203: + case 204: + case 205: + var initializer = node.initializer; + if (initializer && initializer.kind === 216) { loopInitializer = node.initializer; } break; } var loopParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 24576)) { + var loopOutParameters; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3072)) { loopParameters = []; for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { var varDeclaration = _b[_a]; - collectNames(varDeclaration.name); + processVariableDeclaration(varDeclaration.name); } } - var bodyIsBlock = node.statement.kind === 192; + var bodyIsBlock = node.statement.kind === 196; var paramList = loopParameters ? loopParameters.join(", ") : ""; writeLine(); write("var " + functionName + " = function(" + paramList + ")"); - if (!bodyIsBlock) { - write(" {"); - writeLine(); - increaseIndent(); - } var convertedOuterLoopState = convertedLoopState; - convertedLoopState = {}; + convertedLoopState = { loopOutParameters: loopOutParameters }; if (convertedOuterLoopState) { if (convertedOuterLoopState.argumentsName) { convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; } + if (convertedOuterLoopState.thisName) { + convertedLoopState.thisName = convertedOuterLoopState.thisName; + } if (convertedOuterLoopState.hoistedLocalVariables) { convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; } } - emitEmbeddedStatement(node.statement); - if (!bodyIsBlock) { - decreaseIndent(); - writeLine(); - write("}"); - } - write(";"); + write(" {"); writeLine(); + increaseIndent(); + if (bodyIsBlock) { + emitLines(node.statement.statements); + } + else { + emit(node.statement); + } + writeLine(); + copyLoopOutParameters(convertedLoopState, 1, true); + decreaseIndent(); + writeLine(); + write("};"); + writeLine(); + if (loopOutParameters) { + write("var "); + for (var i = 0; i < loopOutParameters.length; i++) { + if (i !== 0) { + write(", "); + } + write(loopOutParameters[i].outParamName); + } + write(";"); + writeLine(); + } if (convertedLoopState.argumentsName) { if (convertedOuterLoopState) { convertedOuterLoopState.argumentsName = convertedLoopState.argumentsName; @@ -26933,6 +28879,15 @@ var ts; writeLine(); } } + if (convertedLoopState.thisName) { + if (convertedOuterLoopState) { + convertedOuterLoopState.thisName = convertedLoopState.thisName; + } + else { + write("var " + convertedLoopState.thisName + " = this;"); + writeLine(); + } + } if (convertedLoopState.hoistedLocalVariables) { if (convertedOuterLoopState) { convertedOuterLoopState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; @@ -26960,15 +28915,21 @@ var ts; var currentLoopState = convertedLoopState; convertedLoopState = convertedOuterLoopState; return { functionName: functionName, paramList: paramList, state: currentLoopState }; - function collectNames(name) { + function processVariableDeclaration(name) { if (name.kind === 69) { - var nameText = isNameOfNestedRedeclaration(name) ? getGeneratedNameForNode(name) : name.text; + var nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(name) + ? getGeneratedNameForNode(name) + : name.text; loopParameters.push(nameText); + if (resolver.getNodeCheckFlags(name.parent) & 2097152) { + var reassignedVariable = { originalName: name, outParamName: makeUniqueName("out_" + nameText) }; + (loopOutParameters || (loopOutParameters = [])).push(reassignedVariable); + } } else { for (var _a = 0, _b = name.elements; _a < _b.length; _a++) { var element = _b[_a]; - collectNames(element.name); + processVariableDeclaration(element.name); } } } @@ -26982,7 +28943,7 @@ var ts; if (emitAsEmbeddedStatement) { emitEmbeddedStatement(node.statement); } - else if (node.statement.kind === 192) { + else if (node.statement.kind === 196) { emitLines(node.statement.statements); } else { @@ -26993,6 +28954,28 @@ var ts; convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; } } + function copyLoopOutParameters(state, copyDirection, emitAsStatements) { + if (state.loopOutParameters) { + for (var _a = 0, _b = state.loopOutParameters; _a < _b.length; _a++) { + var outParam = _b[_a]; + if (copyDirection === 0) { + emitIdentifier(outParam.originalName); + write(" = " + outParam.outParamName); + } + else { + write(outParam.outParamName + " = "); + emitIdentifier(outParam.originalName); + } + if (emitAsStatements) { + write(";"); + writeLine(); + } + else { + write(", "); + } + } + } + } function emitConvertedLoopCall(loop, emitAsBlock) { if (emitAsBlock) { write(" {"); @@ -27007,6 +28990,8 @@ var ts; write("var " + loopResult + " = "); } write(loop.functionName + "(" + loop.paramList + ");"); + writeLine(); + copyLoopOutParameters(loop.state, 0, true); if (!isSimpleLoop) { writeLine(); if (loop.state.nonLocalJumps & 8) { @@ -27016,7 +29001,7 @@ var ts; convertedLoopState.nonLocalJumps |= 8; } else { - write("return " + loopResult + ".value"); + write("return " + loopResult + ".value;"); } writeLine(); } @@ -27078,9 +29063,9 @@ var ts; var endPos = emitToken(86, node.pos); write(" "); endPos = emitToken(17, endPos); - if (node.initializer && node.initializer.kind === 212) { + if (node.initializer && node.initializer.kind === 216) { var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList); if (startIsEmitted) { emitCommaList(variableDeclarationList.declarations); } @@ -27104,7 +29089,7 @@ var ts; } } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 && node.kind === 201) { + if (languageVersion < 2 && node.kind === 205) { emitLoop(node, emitDownLevelForOfStatementWorker); } else { @@ -27115,17 +29100,17 @@ var ts; var endPos = emitToken(86, node.pos); write(" "); endPos = emitToken(17, endPos); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 216) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + tryEmitStartOfVariableDeclarationList(variableDeclarationList); emit(variableDeclarationList.declarations[0]); } } else { emit(node.initializer); } - if (node.kind === 200) { + if (node.kind === 204) { write(" in "); } else { @@ -27140,9 +29125,6 @@ var ts; emitNormalLoopBody(node, true); } } - function emitDownLevelForOfStatement(node) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } function emitDownLevelForOfStatementWorker(node, loop) { var endPos = emitToken(86, node.pos); write(" "); @@ -27164,24 +29146,24 @@ var ts; emitNodeWithoutSourceMap(node.expression); emitEnd(node.expression); write("; "); - emitStart(node.initializer); + emitStart(node.expression); emitNodeWithoutSourceMap(counter); write(" < "); emitNodeWithCommentsAndWithoutSourcemap(rhsReference); write(".length"); - emitEnd(node.initializer); + emitEnd(node.expression); write("; "); - emitStart(node.initializer); + emitStart(node.expression); emitNodeWithoutSourceMap(counter); write("++"); - emitEnd(node.initializer); + emitEnd(node.expression); emitToken(18, node.expression.end); write(" {"); writeLine(); increaseIndent(); var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 216) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -27203,7 +29185,7 @@ var ts; } else { var assignmentExpression = createBinaryExpression(node.initializer, 56, rhsIterationValue, false); - if (node.initializer.kind === 164 || node.initializer.kind === 165) { + if (node.initializer.kind === 168 || node.initializer.kind === 169) { emitDestructuring(assignmentExpression, true, undefined); } else { @@ -27225,23 +29207,25 @@ var ts; } function emitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 203 ? 2 : 4; + var jump = node.kind === 207 ? 2 : 4; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { + write("return "); + copyLoopOutParameters(convertedLoopState, 1, false); if (!node.label) { - if (node.kind === 203) { + if (node.kind === 207) { convertedLoopState.nonLocalJumps |= 2; - write("return \"break\";"); + write("\"break\";"); } else { convertedLoopState.nonLocalJumps |= 4; - write("return \"continue\";"); + write("\"continue\";"); } } else { var labelMarker; - if (node.kind === 203) { + if (node.kind === 207) { labelMarker = "break-" + node.label.text; setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); } @@ -27249,12 +29233,12 @@ var ts; labelMarker = "continue-" + node.label.text; setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); } - write("return \"" + labelMarker + "\";"); + write("\"" + labelMarker + "\";"); } return; } } - emitToken(node.kind === 203 ? 70 : 75, node.pos); + emitToken(node.kind === 207 ? 70 : 75, node.pos); emitOptional(" ", node.label); write(";"); } @@ -27307,19 +29291,19 @@ var ts; emitToken(16, node.clauses.end); } function nodeStartPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, node2.end); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end); } function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 241) { + if (node.kind === 245) { write("case "); emit(node.expression); write(":"); @@ -27388,7 +29372,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 218); + } while (node && node.kind !== 222); return node; } function emitContainingModuleName(node) { @@ -27397,13 +29381,13 @@ var ts; } function emitModuleMemberName(node) { emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 2) { + if (ts.getCombinedNodeFlags(node) & 1) { var container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); write("."); } - else if (modulekind !== 5 && modulekind !== 4) { + else if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { write("exports."); } } @@ -27413,20 +29397,20 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(8); zero.text = "0"; - var result = ts.createSynthesizedNode(177); + var result = ts.createSynthesizedNode(181); result.expression = zero; return result; } function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 248) { - ts.Debug.assert(!!(node.flags & 512) || node.kind === 227); - if (modulekind === 1 || modulekind === 2 || modulekind === 3) { - if (!currentSourceFile.symbol.exports["___esModule"]) { - if (languageVersion === 1) { + if (node.parent.kind === 252) { + ts.Debug.assert(!!(node.flags & 512) || node.kind === 231); + if (modulekind === ts.ModuleKind.CommonJS || modulekind === ts.ModuleKind.AMD || modulekind === ts.ModuleKind.UMD) { + if (!isEs6Module) { + if (languageVersion !== 0) { write("Object.defineProperty(exports, \"__esModule\", { value: true });"); writeLine(); } - else if (languageVersion === 0) { + else { write("exports.__esModule = true;"); writeLine(); } @@ -27435,10 +29419,10 @@ var ts; } } function emitExportMemberAssignment(node) { - if (node.flags & 2) { + if (node.flags & 1) { writeLine(); emitStart(node); - if (modulekind === 4 && node.parent === currentSourceFile) { + if (modulekind === ts.ModuleKind.System && node.parent === currentSourceFile) { write(exportFunctionForFile + "(\""); if (node.flags & 512) { write("default"); @@ -27471,7 +29455,7 @@ var ts; } } function emitExportMemberAssignments(name) { - if (modulekind === 4) { + if (modulekind === ts.ModuleKind.System) { return; } if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { @@ -27490,7 +29474,7 @@ var ts; } } function emitExportSpecifierInSystemModule(specifier) { - ts.Debug.assert(modulekind === 4); + ts.Debug.assert(modulekind === ts.ModuleKind.System); if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) { return; } @@ -27504,7 +29488,7 @@ var ts; emitEnd(specifier.name); write(";"); } - function emitAssignment(name, value, shouldEmitCommaBeforeAssignment) { + function emitAssignment(name, value, shouldEmitCommaBeforeAssignment, nodeForSourceMap) { if (shouldEmitCommaBeforeAssignment) { write(", "); } @@ -27514,63 +29498,75 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(name); write("\", "); } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 || name.parent.kind === 163); - if (isVariableDeclarationOrBindingElement) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 215 || name.parent.kind === 167); + emitStart(isFirstVariableDeclaration(nodeForSourceMap) ? nodeForSourceMap.parent : nodeForSourceMap); + withTemporaryNoSourceMap(function () { + if (isVariableDeclarationOrBindingElement) { + emitModuleMemberName(name.parent); + } + else { + emit(name); + } + write(" = "); + emit(value); + }); + emitEnd(nodeForSourceMap, true); if (exportChanged) { write(")"); } } - function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment) { + function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment, sourceMapNode) { var identifier = createTempVariable(0); if (!canDefineTempVariablesInPlace) { recordTempDeclaration(identifier); } - emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment); + emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment, sourceMapNode || expression.parent); return identifier; } + function isFirstVariableDeclaration(root) { + return root.kind === 215 && + root.parent.kind === 216 && + root.parent.declarations[0] === root; + } function emitDestructuring(root, isAssignmentExpressionStatement, value) { var emitCount = 0; var canDefineTempVariablesInPlace = false; - if (root.kind === 211) { - var isExported = ts.getCombinedNodeFlags(root) & 2; + if (root.kind === 215) { + var isExported = ts.getCombinedNodeFlags(root) & 1; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } - else if (root.kind === 138) { + else if (root.kind === 140) { canDefineTempVariablesInPlace = true; } - if (root.kind === 181) { + if (root.kind === 185) { emitAssignmentExpression(root); } else { ts.Debug.assert(!isAssignmentExpressionStatement); + if (isFirstVariableDeclaration(root)) { + sourceMap.changeEmitSourcePos(); + } emitBindingElement(root, value); } - function ensureIdentifier(expr, reuseIdentifierExpressions) { + function ensureIdentifier(expr, reuseIdentifierExpressions, sourceMapNode) { if (expr.kind === 69 && reuseIdentifierExpressions) { return expr; } - var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0); + var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0, sourceMapNode); emitCount++; return identifier; } - function createDefaultValueCheck(value, defaultValue) { - value = ensureIdentifier(value, true); - var equals = ts.createSynthesizedNode(181); + function createDefaultValueCheck(value, defaultValue, sourceMapNode) { + value = ensureIdentifier(value, true, sourceMapNode); + var equals = ts.createSynthesizedNode(185); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(32); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(182); + var cond = ts.createSynthesizedNode(186); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(53); cond.whenTrue = whenTrue; @@ -27584,15 +29580,21 @@ var ts; return node; } function createPropertyAccessForDestructuringProperty(object, propName) { - var syntheticName = ts.createSynthesizedNode(propName.kind); - syntheticName.text = propName.text; - if (syntheticName.kind !== 69) { - return createElementAccessExpression(object, syntheticName); + var index; + var nameIsComputed = propName.kind === 138; + if (nameIsComputed) { + index = ensureIdentifier(propName.expression, false, propName); } - return createPropertyAccessExpression(object, syntheticName); + else { + index = ts.createSynthesizedNode(propName.kind); + index.text = ts.unescapeIdentifier(propName.text); + } + return !nameIsComputed && index.kind === 69 + ? createPropertyAccessExpression(object, index) + : createElementAccessExpression(object, index); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(168); + var call = ts.createSynthesizedNode(172); var sliceIdentifier = ts.createSynthesizedNode(69); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -27600,56 +29602,56 @@ var ts; call.arguments[0] = createNumericLiteral(sliceIndex); return call; } - function emitObjectLiteralAssignment(target, value) { + function emitObjectLiteralAssignment(target, value, sourceMapNode) { var properties = target.properties; if (properties.length !== 1) { - value = ensureIdentifier(value, true); + value = ensureIdentifier(value, true, sourceMapNode); } for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { var p = properties_5[_a]; - if (p.kind === 245 || p.kind === 246) { + if (p.kind === 249 || p.kind === 250) { var propName = p.name; - var target_1 = p.kind === 246 ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName)); + var target_1 = p.kind === 250 ? p : p.initializer || propName; + emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName), p); } } } - function emitArrayLiteralAssignment(target, value) { + function emitArrayLiteralAssignment(target, value, sourceMapNode) { var elements = target.elements; if (elements.length !== 1) { - value = ensureIdentifier(value, true); + value = ensureIdentifier(value, true, sourceMapNode); } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187) { - if (e.kind !== 185) { - emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); + if (e.kind !== 191) { + if (e.kind !== 189) { + emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e); } else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i)); + emitDestructuringAssignment(e.expression, createSliceCall(value, i), e); } } } } - function emitDestructuringAssignment(target, value) { - if (target.kind === 246) { + function emitDestructuringAssignment(target, value, sourceMapNode) { + if (target.kind === 250) { if (target.objectAssignmentInitializer) { - value = createDefaultValueCheck(value, target.objectAssignmentInitializer); + value = createDefaultValueCheck(value, target.objectAssignmentInitializer, sourceMapNode); } target = target.name; } - else if (target.kind === 181 && target.operatorToken.kind === 56) { - value = createDefaultValueCheck(value, target.right); + else if (target.kind === 185 && target.operatorToken.kind === 56) { + value = createDefaultValueCheck(value, target.right, sourceMapNode); target = target.left; } - if (target.kind === 165) { - emitObjectLiteralAssignment(target, value); + if (target.kind === 169) { + emitObjectLiteralAssignment(target, value, sourceMapNode); } - else if (target.kind === 164) { - emitArrayLiteralAssignment(target, value); + else if (target.kind === 168) { + emitArrayLiteralAssignment(target, value, sourceMapNode); } else { - emitAssignment(target, value, emitCount > 0); + emitAssignment(target, value, emitCount > 0, sourceMapNode); emitCount++; } } @@ -27660,24 +29662,24 @@ var ts; emit(value); } else if (isAssignmentExpressionStatement) { - emitDestructuringAssignment(target, value); + emitDestructuringAssignment(target, value, ts.nodeIsSynthesized(root) ? target : root); } else { - if (root.parent.kind !== 172) { + if (root.parent.kind !== 176) { write("("); } - value = ensureIdentifier(value, true); - emitDestructuringAssignment(target, value); + value = ensureIdentifier(value, true, root); + emitDestructuringAssignment(target, value, root); write(", "); emit(value); - if (root.parent.kind !== 172) { + if (root.parent.kind !== 176) { write(")"); } } } function emitBindingElement(target, value) { if (target.initializer) { - value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; + value = value ? createDefaultValueCheck(value, target.initializer, target) : target.initializer; } else if (!value) { value = createVoidZero(); @@ -27687,15 +29689,15 @@ var ts; var elements = pattern.elements; var numElements = elements.length; if (numElements !== 1) { - value = ensureIdentifier(value, numElements !== 0); + value = ensureIdentifier(value, numElements !== 0, target); } for (var i = 0; i < numElements; i++) { var element = elements[i]; - if (pattern.kind === 161) { + if (pattern.kind === 165) { var propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } - else if (element.kind !== 187) { + else if (element.kind !== 191) { if (!element.dotDotDotToken) { emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); } @@ -27706,7 +29708,7 @@ var ts; } } else { - emitAssignment(target.name, value, emitCount > 0); + emitAssignment(target.name, value, emitCount > 0, target); emitCount++; } } @@ -27723,12 +29725,23 @@ var ts; } else { var initializer = node.initializer; - if (!initializer && languageVersion < 2) { - var isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & 16384) && - (getCombinedFlagsForIdentifier(node.name) & 8192); - if (isLetDefinedInLoop && - node.parent.parent.kind !== 200 && - node.parent.parent.kind !== 201) { + if (!initializer && + languageVersion < 2 && + node.name.kind === 69) { + var container = ts.getEnclosingBlockScopeContainer(node); + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 131072; + var isDeclaredInLoop = flags & 262144; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(container) || + (isCapturedInFunction && isDeclaredInLoop && container.kind === 196 && ts.isIterationStatement(container.parent, false)); + var emittedAsNestedLetDeclaration = ts.getCombinedNodeFlags(node) & 1024 && + !emittedAsTopLevel; + var emitExplicitInitializer = emittedAsNestedLetDeclaration && + container.kind !== 204 && + container.kind !== 205 && + (!resolver.isDeclarationWithCollidingName(node) || + (isDeclaredInLoop && !isCapturedInFunction && !ts.isIterationStatement(container, false))); + if (emitExplicitInitializer) { initializer = createVoidZero(); } } @@ -27746,7 +29759,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 187) { + if (node.kind === 191) { return; } var name = node.name; @@ -27757,20 +29770,14 @@ var ts; ts.forEach(name.elements, emitExportVariableAssignments); } } - function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 211 && node.parent.kind !== 163)) { - return 0; - } - return ts.getCombinedNodeFlags(node.parent); - } function isES6ExportedDeclaration(node) { - return !!(node.flags & 2) && - modulekind === 5 && - node.parent.kind === 248; + return !!(node.flags & 1) && + modulekind === ts.ModuleKind.ES6 && + node.parent.kind === 252; } function emitVariableStatement(node) { var startIsEmitted = false; - if (node.flags & 2) { + if (node.flags & 1) { if (isES6ExportedDeclaration(node)) { write("export "); startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); @@ -27789,12 +29796,12 @@ var ts; write(";"); } } - if (modulekind !== 5 && node.parent === currentSourceFile) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); } } function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { - if (!(node.flags & 2)) { + if (!(node.flags & 1)) { return true; } if (isES6ExportedDeclaration(node)) { @@ -27811,12 +29818,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_25 = createTempVariable(0); + var name_26 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_25); - emit(name_25); + tempParameters.push(name_26); + emit(name_26); } else { emit(node.name); @@ -27915,12 +29922,12 @@ var ts; } } function emitAccessor(node) { - write(node.kind === 145 ? "get " : "set "); + write(node.kind === 147 ? "get " : "set "); emit(node.name); emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 174 && languageVersion >= 2; + return node.kind === 178 && languageVersion >= 2; } function emitDeclarationName(node) { if (node.name) { @@ -27931,20 +29938,24 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 173) { + if (node.kind === 177) { return !!node.name; } - if (node.kind === 213) { - return !!node.name || languageVersion < 2; + if (node.kind === 217) { + return !!node.name || modulekind !== ts.ModuleKind.ES6; } } function emitFunctionDeclaration(node) { if (ts.nodeIsMissing(node.body)) { return emitCommentsOnNotEmittedNode(node); } - if (node.kind !== 143 && node.kind !== 142 && - node.parent && node.parent.kind !== 245 && - node.parent.kind !== 168) { + var kind = node.kind, parent = node.parent; + if (kind !== 145 && + kind !== 144 && + parent && + parent.kind !== 249 && + parent.kind !== 172 && + parent.kind !== 168) { emitLeadingComments(node); } emitStart(node); @@ -27965,11 +29976,11 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (modulekind !== 5 && node.kind === 213 && node.parent === currentSourceFile && node.name) { + if (modulekind !== ts.ModuleKind.ES6 && kind === 217 && parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } emitEnd(node); - if (node.kind !== 143 && node.kind !== 142) { + if (kind !== 145 && kind !== 144) { emitTrailingComments(node); } } @@ -28001,35 +30012,36 @@ var ts; } function emitAsyncFunctionBodyForES6(node) { var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 174; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096) !== 0; - var args; + var isArrowFunction = node.kind === 178; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; if (!isArrowFunction) { write(" {"); increaseIndent(); writeLine(); + if (resolver.getNodeCheckFlags(node) & 4096) { + writeLines("\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"); + writeLine(); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + write("const _super = name => super[name];"); + writeLine(); + } write("return"); } write(" __awaiter(this"); if (hasLexicalArguments) { - write(", arguments"); + write(", arguments, "); } else { - write(", void 0"); + write(", void 0, "); } - if (promiseConstructor) { - write(", "); - emitNodeWithoutSourceMap(promiseConstructor); + if (languageVersion >= 2 || !promiseConstructor) { + write("void 0"); } else { - write(", Promise"); - } - if (hasLexicalArguments) { - write(", function* (_arguments)"); - } - else { - write(", function* ()"); + emitEntityNameAsExpression(promiseConstructor, false); } + write(", function* ()"); emitFunctionBody(node); write(")"); if (!isArrowFunction) { @@ -28044,7 +30056,7 @@ var ts; write(" { }"); } else { - if (node.body.kind === 192) { + if (node.body.kind === 196) { emitBlockFunctionBody(node, node.body); } else { @@ -28069,7 +30081,7 @@ var ts; emitSignatureParameters(node); } var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync && languageVersion === 2) { + if (isAsync) { emitAsyncFunctionBodyForES6(node); } else { @@ -28096,14 +30108,13 @@ var ts; } write(" "); var current = body; - while (current.kind === 171) { + while (current.kind === 175) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 165); + emitParenthesizedIf(body, current.kind === 169); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); emitDetachedCommentsAndUpdateCommentsInfo(node.body); @@ -28124,8 +30135,10 @@ var ts; increaseIndent(); writeLine(); emitLeadingComments(node.body); + emitStart(body); write("return "); emit(body); + emitEnd(body); write(";"); emitTrailingComments(node.body); emitTempDeclarations(true); @@ -28135,11 +30148,9 @@ var ts; emitStart(node.body); write("}"); emitEnd(node.body); - scopeEmitEnd(); } function emitBlockFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); emitDetachedCommentsAndUpdateCommentsInfo(body.statements); @@ -28166,25 +30177,23 @@ var ts; decreaseIndent(); } emitToken(16, body.statements.end); - scopeEmitEnd(); } - function findInitialSuperCall(ctor) { - if (ctor.body) { - var statement = ctor.body.statements[0]; - if (statement && statement.kind === 195) { - var expr = statement.expression; - if (expr && expr.kind === 168) { - var func = expr.expression; - if (func && func.kind === 95) { - return statement; - } - } - } + function getSuperCallAtGivenIndex(ctor, index) { + if (!ctor.body) { + return undefined; + } + var statements = ctor.body.statements; + if (!statements || index >= statements.length) { + return undefined; + } + var statement = statements[index]; + if (statement.kind === 199) { + return ts.isSuperCallExpression(statement.expression) ? statement : undefined; } } function emitParameterPropertyAssignments(node) { ts.forEach(node.parameters, function (param) { - if (param.flags & 56) { + if (param.flags & 28) { writeLine(); emitStart(param); emitStart(param.name); @@ -28204,7 +30213,7 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(memberName); write("]"); } - else if (memberName.kind === 136) { + else if (memberName.kind === 138) { emitComputedPropertyName(memberName); } else { @@ -28216,7 +30225,7 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 141 && isStatic === ((member.flags & 64) !== 0) && member.initializer) { + if (member.kind === 143 && isStatic === ((member.flags & 32) !== 0) && member.initializer) { properties.push(member); } } @@ -28237,7 +30246,7 @@ var ts; emit(receiver); } else { - if (property.flags & 64) { + if (property.flags & 32) { emitDeclarationName(node); } else { @@ -28256,11 +30265,11 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 191) { + if (member.kind === 195) { writeLine(); write(";"); } - else if (member.kind === 143 || node.kind === 142) { + else if (member.kind === 145 || node.kind === 144) { if (!member.body) { return emitCommentsOnNotEmittedNode(member); } @@ -28277,7 +30286,7 @@ var ts; write(";"); emitTrailingComments(member); } - else if (member.kind === 145 || member.kind === 146) { + else if (member.kind === 147 || member.kind === 148) { var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); @@ -28327,22 +30336,22 @@ var ts; function emitMemberFunctionsForES6AndHigher(node) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.kind === 143 || node.kind === 142) && !member.body) { + if ((member.kind === 145 || node.kind === 144) && !member.body) { emitCommentsOnNotEmittedNode(member); } - else if (member.kind === 143 || - member.kind === 145 || - member.kind === 146) { + else if (member.kind === 145 || + member.kind === 147 || + member.kind === 148) { writeLine(); emitLeadingComments(member); emitStart(member); - if (member.flags & 64) { + if (member.flags & 32) { write("static "); } - if (member.kind === 145) { + if (member.kind === 147) { write("get "); } - else if (member.kind === 146) { + else if (member.kind === 148) { write("set "); } if (member.asteriskToken) { @@ -28353,7 +30362,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 191) { + else if (member.kind === 195) { writeLine(); write(";"); } @@ -28378,10 +30387,10 @@ var ts; function emitConstructorWorker(node, baseTypeElement) { var hasInstancePropertyWithInitializer = false; ts.forEach(node.members, function (member) { - if (member.kind === 144 && !member.body) { + if (member.kind === 146 && !member.body) { emitCommentsOnNotEmittedNode(member); } - if (member.kind === 141 && member.initializer && (member.flags & 64) === 0) { + if (member.kind === 143 && member.initializer && (member.flags & 32) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -28414,7 +30423,6 @@ var ts; } var startIndex = 0; write(" {"); - scopeEmitStart(node, "constructor"); increaseIndent(); if (ctor) { startIndex = emitDirectivePrologues(ctor.body.statements, true); @@ -28426,7 +30434,7 @@ var ts; emitDefaultValueAssignments(ctor); emitRestParameter(ctor); if (baseTypeElement) { - superCall = findInitialSuperCall(ctor); + superCall = getSuperCallAtGivenIndex(ctor, startIndex); if (superCall) { writeLine(); emit(superCall); @@ -28462,7 +30470,6 @@ var ts; } decreaseIndent(); emitToken(16, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); emitEnd(ctor || node); if (ctor) { emitTrailingComments(ctor); @@ -28481,19 +30488,29 @@ var ts; else { emitClassLikeDeclarationForES6AndHigher(node); } - if (modulekind !== 5 && node.parent === currentSourceFile && node.name) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } } function emitClassLikeDeclarationForES6AndHigher(node) { + var decoratedClassAlias; var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 214) { + if (node.kind === 218) { if (thisNodeIsDecorated) { + if (resolver.getNodeCheckFlags(node) & 524288) { + decoratedClassAlias = ts.unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default")); + decoratedClassAliases[ts.getNodeId(node)] = decoratedClassAlias; + write("let " + decoratedClassAlias + ";"); + writeLine(); + } if (isES6ExportedDeclaration(node) && !(node.flags & 512)) { write("export "); } write("let "); emitDeclarationName(node); + if (decoratedClassAlias !== undefined) { + write(" = " + decoratedClassAlias); + } write(" = "); } else if (isES6ExportedDeclaration(node)) { @@ -28504,7 +30521,7 @@ var ts; } } var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186; + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 190; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0); @@ -28514,7 +30531,7 @@ var ts; write(" = "); } write("class"); - if ((node.name || (node.flags & 512 && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if (node.name || (node.flags & 512 && (staticProperties.length > 0 || modulekind !== ts.ModuleKind.ES6) && !thisNodeIsDecorated)) { write(" "); emitDeclarationName(node); } @@ -28525,15 +30542,14 @@ var ts; } write(" {"); increaseIndent(); - scopeEmitStart(node); writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES6AndHigher(node); decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); if (thisNodeIsDecorated) { + decoratedClassAliases[ts.getNodeId(node)] = undefined; write(";"); } if (isClassExpressionWithStaticProperties) { @@ -28552,26 +30568,36 @@ var ts; else { writeLine(); emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node); + emitDecoratorsOfClass(node, decoratedClassAlias); } - if (!isES6ExportedDeclaration(node) && (node.flags & 2)) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); + if (!(node.flags & 1)) { + return; } - else if (isES6ExportedDeclaration(node) && (node.flags & 512) && thisNodeIsDecorated) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); + if (modulekind !== ts.ModuleKind.ES6) { + emitExportMemberAssignment(node); + } + else { + if (node.flags & 512) { + if (thisNodeIsDecorated) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } + } + else if (node.parent.kind !== 252) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emitDeclarationName(node); + emitEnd(node); + write(";"); + } } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 214) { + if (node.kind === 218) { if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -28595,7 +30621,6 @@ var ts; tempParameters = undefined; computedPropertyNamesToGeneratedNames = undefined; increaseIndent(); - scopeEmitStart(node); if (baseTypeNode) { writeLine(); emitStart(baseTypeNode); @@ -28609,7 +30634,7 @@ var ts; emitMemberFunctionsForES5AndLower(node); emitPropertyDeclarations(node, getInitializedProperties(node, true)); writeLine(); - emitDecoratorsOfClass(node); + emitDecoratorsOfClass(node, undefined); writeLine(); emitToken(16, node.members.end, function () { write("return "); @@ -28626,73 +30651,71 @@ var ts; decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); emitStart(node); - write(")("); + write("("); if (baseTypeNode) { emit(baseTypeNode.expression); } - write(")"); - if (node.kind === 214) { + write("))"); + if (node.kind === 218) { write(";"); } emitEnd(node); - if (node.kind === 214) { + if (node.kind === 218) { emitExportMemberAssignment(node); } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); - if (!(member.flags & 64)) { + if (!(member.flags & 32)) { write(".prototype"); } } - function emitDecoratorsOfClass(node) { + function emitDecoratorsOfClass(node, decoratedClassAlias) { emitDecoratorsOfMembers(node, 0); - emitDecoratorsOfMembers(node, 64); - emitDecoratorsOfConstructor(node); + emitDecoratorsOfMembers(node, 32); + emitDecoratorsOfConstructor(node, decoratedClassAlias); } - function emitDecoratorsOfConstructor(node) { + function emitDecoratorsOfConstructor(node, decoratedClassAlias) { var decorators = node.decorators; var constructor = ts.getFirstConstructorWithBody(node); - var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); - if (!decorators && !hasDecoratedParameters) { + var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); + if (!decorators && !firstParameterDecorator) { return; } writeLine(); - emitStart(node); + emitStart(node.decorators || firstParameterDecorator); emitDeclarationName(node); + if (decoratedClassAlias !== undefined) { + write(" = " + decoratedClassAlias); + } write(" = __decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); + } emitSerializedTypeMetadata(node, argumentsWritten >= 0); decreaseIndent(); writeLine(); write("], "); emitDeclarationName(node); - write(");"); - emitEnd(node); + write(")"); + emitEnd(node.decorators || firstParameterDecorator); + write(";"); writeLine(); } function emitDecoratorsOfMembers(node, staticFlag) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.flags & 64) !== staticFlag) { + if ((member.flags & 32) !== staticFlag) { continue; } if (!ts.nodeCanBeDecorated(member)) { continue; } - if (!ts.nodeOrChildIsDecorated(member)) { - continue; - } var decorators = void 0; var functionLikeMember = void 0; if (ts.isAccessor(member)) { @@ -28708,41 +30731,42 @@ var ts; } else { decorators = member.decorators; - if (member.kind === 143) { + if (member.kind === 145) { functionLikeMember = member; } } + var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); + if (!decorators && !firstParameterDecorator) { + continue; + } writeLine(); - emitStart(member); + emitStart(decorators || firstParameterDecorator); write("__decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + } emitSerializedTypeMetadata(member, argumentsWritten > 0); decreaseIndent(); writeLine(); write("], "); - emitStart(member.name); emitClassMemberPrefix(node, member); write(", "); emitExpressionForPropertyName(member.name); - emitEnd(member.name); if (languageVersion > 0) { - if (member.kind !== 141) { + if (member.kind !== 143) { write(", null"); } else { write(", void 0"); } } - write(");"); - emitEnd(member); + write(")"); + emitEnd(decorators || firstParameterDecorator); + write(";"); writeLine(); } } @@ -28755,60 +30779,58 @@ var ts; if (ts.nodeIsDecorated(parameter)) { var decorators = parameter.decorators; argumentsWritten += emitList(decorators, 0, decorators.length, true, false, leadingComma, true, function (decorator) { - emitStart(decorator); write("__param(" + parameterIndex + ", "); emit(decorator.expression); write(")"); - emitEnd(decorator); }); leadingComma = true; } - ++parameterIndex; + parameterIndex++; } } return argumentsWritten; } function shouldEmitTypeMetadata(node) { switch (node.kind) { - case 143: case 145: - case 146: - case 141: + case 147: + case 148: + case 143: return true; } return false; } function shouldEmitReturnTypeMetadata(node) { switch (node.kind) { - case 143: + case 145: return true; } return false; } function shouldEmitParamTypesMetadata(node) { switch (node.kind) { - case 214: - case 143: - case 146: + case 218: + case 145: + case 148: return true; } return false; } function emitSerializedTypeOfNode(node) { switch (node.kind) { - case 214: + case 218: write("Function"); return; - case 141: + case 143: emitSerializedTypeNode(node.type); return; - case 138: + case 140: emitSerializedTypeNode(node.type); return; - case 145: + case 147: emitSerializedTypeNode(node.type); return; - case 146: + case 148: emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); return; } @@ -28824,39 +30846,40 @@ var ts; case 103: write("void 0"); return; - case 160: + case 162: emitSerializedTypeNode(node.type); return; - case 152: - case 153: - write("Function"); - return; - case 156: - case 157: - write("Array"); - return; - case 150: - case 120: - write("Boolean"); - return; - case 130: - case 9: - write("String"); - return; - case 128: - write("Number"); - return; - case 131: - write("Symbol"); - return; - case 151: - emitSerializedTypeReferenceNode(node); - return; case 154: case 155: + write("Function"); + return; case 158: case 159: + write("Array"); + return; + case 152: + case 120: + write("Boolean"); + return; + case 131: + case 164: + write("String"); + return; + case 129: + write("Number"); + return; + case 132: + write("Symbol"); + return; + case 153: + emitSerializedTypeReferenceNode(node); + return; + case 156: + case 157: + case 160: + case 161: case 117: + case 163: break; default: ts.Debug.fail("Cannot serialize unexpected type node."); @@ -28870,8 +30893,7 @@ var ts; while (ts.isDeclaration(location) || ts.isTypeNode(location)) { location = location.parent; } - var typeName = ts.cloneEntityName(node.typeName); - typeName.parent = location; + var typeName = ts.cloneEntityName(node.typeName, location); var result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case ts.TypeReferenceSerializationKind.Unknown: @@ -28921,7 +30943,7 @@ var ts; function emitSerializedParameterTypesOfNode(node) { if (node) { var valueDeclaration; - if (node.kind === 214) { + if (node.kind === 218) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -28937,10 +30959,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 156) { + if (parameterType.kind === 158) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 151 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType.kind === 153 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -29011,9 +31033,10 @@ var ts; return; } if (!shouldHoistDeclarationInSystemJsModule(node)) { - if (!(node.flags & 2) || isES6ExportedDeclaration(node)) { + var isES6ExportedEnum = isES6ExportedDeclaration(node); + if (!(node.flags & 1) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 221))) { emitStart(node); - if (isES6ExportedDeclaration(node)) { + if (isES6ExportedEnum) { write("export "); } write("var "); @@ -29030,19 +31053,17 @@ var ts; emitEnd(node.name); write(") {"); increaseIndent(); - scopeEmitStart(node); emitLines(node.members); decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); write(")("); emitModuleMemberName(node); write(" || ("); emitModuleMemberName(node); write(" = {}));"); emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 2 && !shouldHoistDeclarationInSystemJsModule(node)) { + if (!isES6ExportedDeclaration(node) && node.flags & 1 && !shouldHoistDeclarationInSystemJsModule(node)) { writeLine(); emitStart(node); write("var "); @@ -29052,8 +31073,8 @@ var ts; emitEnd(node); write(";"); } - if (modulekind !== 5 && node.parent === currentSourceFile) { - if (modulekind === 4 && (node.flags & 2)) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { + if (modulekind === ts.ModuleKind.System && (node.flags & 1)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -29093,7 +31114,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 218) { + if (moduleDeclaration.body.kind === 222) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -29104,6 +31125,9 @@ var ts; function isModuleMergedWithES6Class(node) { return languageVersion === 2 && !!(resolver.getNodeCheckFlags(node) & 32768); } + function isFirstDeclarationOfKind(node, declarations, kind) { + return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); + } function emitModuleDeclaration(node) { var shouldEmit = shouldEmitModuleDeclaration(node); if (!shouldEmit) { @@ -29112,15 +31136,18 @@ var ts; var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); + var isES6ExportedNamespace = isES6ExportedDeclaration(node); + if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 222)) { + emitStart(node); + if (isES6ExportedNamespace) { + write("export "); + } + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); } emitStart(node); write("(function ("); @@ -29128,7 +31155,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 219) { + if (node.body.kind === 223) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; @@ -29144,7 +31171,6 @@ var ts; else { write("{"); increaseIndent(); - scopeEmitStart(node); emitCaptureThisForNodeIfNecessary(node); writeLine(); emit(node.body); @@ -29152,10 +31178,9 @@ var ts; writeLine(); var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(16, moduleBlock.statements.end); - scopeEmitEnd(); } write(")("); - if ((node.flags & 2) && !isES6ExportedDeclaration(node)) { + if ((node.flags & 1) && !isES6ExportedDeclaration(node)) { emit(node.name); write(" = "); } @@ -29165,7 +31190,7 @@ var ts; write(" = {}));"); emitEnd(node); if (!isES6ExportedDeclaration(node) && node.name.kind === 69 && node.parent === currentSourceFile) { - if (modulekind === 4 && (node.flags & 2)) { + if (modulekind === ts.ModuleKind.System && (node.flags & 1)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -29177,8 +31202,8 @@ var ts; } } function tryRenameExternalModule(moduleName) { - if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) { - return "\"" + currentSourceFile.renamedDependencies[moduleName.text] + "\""; + if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { + return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; } @@ -29201,16 +31226,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 221) { + if (node.kind === 225) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 228) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 222 && node.importClause && !!node.importClause.name; + return node.kind === 226 && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -29219,7 +31244,7 @@ var ts; ts.forEachChild(node, emitExportImportAssignments); } function emitImportDeclaration(node) { - if (modulekind !== 5) { + if (modulekind !== ts.ModuleKind.ES6) { return emitExternalImportDeclaration(node); } if (node.importClause) { @@ -29237,7 +31262,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 224) { + if (node.importClause.namedBindings.kind === 228) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -29263,21 +31288,24 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 && (node.flags & 2) !== 0; + var isExportedImport = node.kind === 225 && (node.flags & 1) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); - if (modulekind !== 2) { + var varOrConst = (languageVersion <= 1) ? "var " : "const "; + if (modulekind !== ts.ModuleKind.AMD) { emitLeadingComments(node); emitStart(node); if (namespaceDeclaration && !isDefaultImport(node)) { - if (!isExportedImport) - write("var "); + if (!isExportedImport) { + write(varOrConst); + } + ; emitModuleMemberName(namespaceDeclaration); write(" = "); } else { - var isNakedImport = 222 && !node.importClause; + var isNakedImport = 226 && !node.importClause; if (!isNakedImport) { - write("var "); + write(varOrConst); write(getGeneratedNameForNode(node)); write(" = "); } @@ -29302,7 +31330,7 @@ var ts; write(";"); } else if (namespaceDeclaration && isDefaultImport(node)) { - write("var "); + write(varOrConst); emitModuleMemberName(namespaceDeclaration); write(" = "); write(getGeneratedNameForNode(node)); @@ -29318,7 +31346,7 @@ var ts; return; } if (resolver.isReferencedAliasDeclaration(node) || - (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { + (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { emitLeadingComments(node); emitStart(node); var variableDeclarationIsHoisted = shouldHoistVariable(node, true); @@ -29329,7 +31357,7 @@ var ts; write("export "); write("var "); } - else if (!(node.flags & 2)) { + else if (!(node.flags & 1)) { write("var "); } } @@ -29351,13 +31379,13 @@ var ts; } } function emitExportDeclaration(node) { - ts.Debug.assert(modulekind !== 4); - if (modulekind !== 5) { + ts.Debug.assert(modulekind !== ts.ModuleKind.System); + if (modulekind !== ts.ModuleKind.ES6) { if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { emitStart(node); var generatedName = getGeneratedNameForNode(node); if (node.exportClause) { - if (modulekind !== 2) { + if (modulekind !== ts.ModuleKind.AMD) { write("var "); write(generatedName); write(" = "); @@ -29382,15 +31410,17 @@ var ts; } } else { - writeLine(); - write("__export("); - if (modulekind !== 2) { - emitRequire(ts.getExternalModuleName(node)); + if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + writeLine(); + write("__export("); + if (modulekind !== ts.ModuleKind.AMD) { + emitRequire(ts.getExternalModuleName(node)); + } + else { + write(generatedName); + } + write(");"); } - else { - write(generatedName); - } - write(");"); } emitEnd(node); } @@ -29415,7 +31445,7 @@ var ts; } } function emitExportOrImportSpecifierList(specifiers, shouldEmit) { - ts.Debug.assert(modulekind === 5); + ts.Debug.assert(modulekind === ts.ModuleKind.ES6); var needsComma = false; for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { var specifier = specifiers_1[_a]; @@ -29434,14 +31464,14 @@ var ts; } function emitExportAssignment(node) { if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { - if (modulekind === 5) { + if (modulekind === ts.ModuleKind.ES6) { writeLine(); emitStart(node); write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 213 && - expression.kind !== 214) { + if (expression.kind !== 217 && + expression.kind !== 218) { write(";"); } emitEnd(node); @@ -29449,7 +31479,7 @@ var ts; else { writeLine(); emitStart(node); - if (modulekind === 4) { + if (modulekind === ts.ModuleKind.System) { write(exportFunctionForFile + "(\"default\","); emit(node.expression); write(")"); @@ -29474,26 +31504,28 @@ var ts; externalImports = []; exportSpecifiers = {}; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 222: + case 226: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, true)) { externalImports.push(node); } break; - case 221: - if (node.moduleReference.kind === 232 && resolver.isReferencedAliasDeclaration(node)) { + case 225: + if (node.moduleReference.kind === 236 && resolver.isReferencedAliasDeclaration(node)) { externalImports.push(node); } break; - case 228: + case 232: if (node.moduleSpecifier) { if (!node.exportClause) { - externalImports.push(node); - hasExportStars = true; + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } } else if (resolver.isValueAliasDeclaration(node)) { externalImports.push(node); @@ -29502,12 +31534,12 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_26 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_26] || (exportSpecifiers[name_26] = [])).push(specifier); + var name_27 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_27] || (exportSpecifiers[name_27] = [])).push(specifier); } } break; - case 227: + case 231: if (node.isExportEquals && !exportEquals) { exportEquals = node; } @@ -29516,7 +31548,7 @@ var ts; } } function emitExportStarHelper() { - if (hasExportStars) { + if (hasExportStarsToExportValues) { writeLine(); write("function __export(m) {"); increaseIndent(); @@ -29530,16 +31562,22 @@ var ts; function getLocalNameForExternalImport(node) { var namespaceDeclaration = getNamespaceDeclarationNode(node); if (namespaceDeclaration && !isDefaultImport(node)) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); + return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); } - if (node.kind === 222 && node.importClause) { + if (node.kind === 226 && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 228 && node.moduleSpecifier) { + if (node.kind === 232 && node.moduleSpecifier) { return getGeneratedNameForNode(node); } } - function getExternalModuleNameText(importNode) { + function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { + if (emitRelativePathAsModuleName) { + var name_28 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_28) { + return "\"" + name_28 + "\""; + } + } var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); @@ -29554,8 +31592,8 @@ var ts; var started = false; for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { var importNode = externalImports_1[_a]; - var skipNode = importNode.kind === 228 || - (importNode.kind === 222 && !importNode.importClause); + var skipNode = importNode.kind === 232 || + (importNode.kind === 226 && !importNode.importClause); if (skipNode) { continue; } @@ -29573,14 +31611,14 @@ var ts; } } function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) { - if (!hasExportStars) { + if (!hasExportStarsToExportValues) { return undefined; } if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; - if (externalImport.kind === 228 && externalImport.exportClause) { + if (externalImport.kind === 232 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -29595,7 +31633,7 @@ var ts; increaseIndent(); var started = false; if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; ++i) { + for (var i = 0; i < exportedDeclarations.length; i++) { writeExportedName(exportedDeclarations[i]); } } @@ -29609,7 +31647,7 @@ var ts; } for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 228) { + if (externalImport.kind !== 232) { continue; } var exportDecl = externalImport; @@ -29681,13 +31719,13 @@ var ts; writeLine(); write("var "); var seen = {}; - for (var i = 0; i < hoistedVars.length; ++i) { + for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_27 = local.kind === 69 + var name_29 = local.kind === 69 ? local : local.name; - if (name_27) { - var text = ts.unescapeIdentifier(name_27.text); + if (name_29) { + var text = ts.unescapeIdentifier(name_29.text); if (ts.hasProperty(seen, text)) { continue; } @@ -29698,14 +31736,14 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 214 || local.kind === 218 || local.kind === 217) { + if (local.kind === 218 || local.kind === 222 || local.kind === 221) { emitDeclarationName(local); } else { emit(local); } var flags = ts.getCombinedNodeFlags(local.kind === 69 ? local.parent : local); - if (flags & 2) { + if (flags & 1) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -29719,7 +31757,7 @@ var ts; var f = hoistedFunctionDeclarations_1[_a]; writeLine(); emit(f); - if (f.flags & 2) { + if (f.flags & 1) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -29729,24 +31767,24 @@ var ts; } return exportedDeclarations; function visit(node) { - if (node.flags & 4) { + if (node.flags & 2) { return; } - if (node.kind === 213) { + if (node.kind === 217) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 214) { + if (node.kind === 218) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 217) { + if (node.kind === 221) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -29755,7 +31793,7 @@ var ts; } return; } - if (node.kind === 218) { + if (node.kind === 222) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -29764,17 +31802,17 @@ var ts; } return; } - if (node.kind === 211 || node.kind === 163) { + if (node.kind === 215 || node.kind === 167) { if (shouldHoistVariable(node, false)) { - var name_28 = node.name; - if (name_28.kind === 69) { + var name_30 = node.name; + if (name_30.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_28); + hoistedVars.push(name_30); } else { - ts.forEachChild(name_28, visit); + ts.forEachChild(name_30, visit); } } return; @@ -29799,11 +31837,11 @@ var ts; if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) { return false; } - return (ts.getCombinedNodeFlags(node) & 24576) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 248; + return (ts.getCombinedNodeFlags(node) & 3072) === 0 || + ts.getEnclosingBlockScopeContainer(node).kind === 252; } function isCurrentFileSystemExternalModule() { - return modulekind === 4 && ts.isExternalModule(currentSourceFile); + return modulekind === ts.ModuleKind.System && isCurrentFileExternalModule; } function emitSystemModuleBody(node, dependencyGroups, startIndex) { emitVariableDeclarationsForImports(); @@ -29824,7 +31862,7 @@ var ts; } function emitSetters(exportStarFunction, dependencyGroups) { write("setters:["); - for (var i = 0; i < dependencyGroups.length; ++i) { + for (var i = 0; i < dependencyGroups.length; i++) { if (i !== 0) { write(","); } @@ -29838,29 +31876,29 @@ var ts; var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { - case 222: + case 226: if (!entry.importClause) { break; } - case 221: + case 225: ts.Debug.assert(importVariableName !== ""); writeLine(); write(importVariableName + " = " + parameterName + ";"); writeLine(); break; - case 228: + case 232: ts.Debug.assert(importVariableName !== ""); if (entry.exportClause) { writeLine(); write(exportFunctionForFile + "({"); writeLine(); increaseIndent(); - for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) { - if (i_2 !== 0) { + for (var i_1 = 0, len = entry.exportClause.elements.length; i_1 < len; i_1++) { + if (i_1 !== 0) { write(","); writeLine(); } - var e = entry.exportClause.elements[i_2]; + var e = entry.exportClause.elements[i_1]; write("\""); emitNodeWithCommentsAndWithoutSourcemap(e.name); write("\": " + parameterName + "[\""); @@ -29889,13 +31927,13 @@ var ts; write("execute: function() {"); increaseIndent(); writeLine(); - for (var i = startIndex; i < node.statements.length; ++i) { + for (var i = startIndex; i < node.statements.length; i++) { var statement = node.statements[i]; switch (statement.kind) { - case 213: - case 222: + case 217: + case 226: continue; - case 228: + case 232: if (!statement.moduleSpecifier) { for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { var element = _b[_a]; @@ -29903,7 +31941,7 @@ var ts; } } continue; - case 221: + case 225: if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { continue; } @@ -29916,27 +31954,36 @@ var ts; writeLine(); write("}"); } - function emitSystemModule(node) { + function writeModuleName(node, emitRelativePathAsModuleName) { + var moduleName = node.moduleName; + if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) { + write("\"" + moduleName + "\", "); + } + } + function emitSystemModule(node, emitRelativePathAsModuleName) { collectExternalModuleInfo(node); ts.Debug.assert(!exportFunctionForFile); exportFunctionForFile = makeUniqueName("exports"); + contextObjectForFile = makeUniqueName("context"); writeLine(); write("System.register("); - if (node.moduleName) { - write("\"" + node.moduleName + "\", "); - } + writeModuleName(node, emitRelativePathAsModuleName); write("["); var groupIndices = {}; var dependencyGroups = []; - for (var i = 0; i < externalImports.length; ++i) { - var text = getExternalModuleNameText(externalImports[i]); - if (ts.hasProperty(groupIndices, text)) { - var groupIndex = groupIndices[text]; + for (var i = 0; i < externalImports.length; i++) { + var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); + if (text === undefined) { + continue; + } + var key = text.substr(1, text.length - 2); + if (ts.hasProperty(groupIndices, key)) { + var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; } else { - groupIndices[text] = dependencyGroups.length; + groupIndices[key] = dependencyGroups.length; dependencyGroups.push([externalImports[i]]); } if (i !== 0) { @@ -29944,10 +31991,13 @@ var ts; } write(text); } - write("], function(" + exportFunctionForFile + ") {"); + write("], function(" + exportFunctionForFile + ", " + contextObjectForFile + ") {"); writeLine(); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); + writeLine(); + write("var __moduleName = " + contextObjectForFile + " && " + contextObjectForFile + ".id;"); + writeLine(); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -29955,7 +32005,7 @@ var ts; writeLine(); write("});"); } - function getAMDDependencyNames(node, includeNonAmdDependencies) { + function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { var aliasedModuleNames = []; var unaliasedModuleNames = []; var importAliasNames = []; @@ -29971,7 +32021,7 @@ var ts; } for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { var importNode = externalImports_4[_c]; - var externalModuleName = getExternalModuleNameText(importNode); + var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { aliasedModuleNames.push(externalModuleName); @@ -29983,8 +32033,8 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } - function emitAMDDependencies(node, includeNonAmdDependencies) { - var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies); + function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { + var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName); emitAMDDependencyList(dependencyNames); write(", "); emitAMDFactoryHeader(dependencyNames); @@ -30011,17 +32061,15 @@ var ts; } write(") {"); } - function emitAMDModule(node) { + function emitAMDModule(node, emitRelativePathAsModuleName) { emitEmitHelpers(node); collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.moduleName) { - write("\"" + node.moduleName + "\", "); - } - emitAMDDependencies(node, true); + writeModuleName(node, emitRelativePathAsModuleName); + emitAMDDependencies(node, true, emitRelativePathAsModuleName); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30032,7 +32080,7 @@ var ts; write("});"); } function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, false); + var startIndex = emitDirectivePrologues(node.statements, false, !compilerOptions.noImplicitUseStrict); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -30051,7 +32099,7 @@ var ts; writeLines(" }\n})("); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30065,7 +32113,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; var startIndex = emitDirectivePrologues(node.statements, false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); @@ -30121,7 +32169,8 @@ var ts; if (result) { result = result.replace(/&(\w+);/g, function (s, m) { if (entities[m] !== undefined) { - return String.fromCharCode(entities[m]); + var ch = String.fromCharCode(entities[m]); + return ch === "\"" ? "\\\"" : ch; } else { return s; @@ -30130,6 +32179,16 @@ var ts; } return result; } + function isJsxChildEmittable(child) { + if (child.kind === 244) { + return !!child.expression; + } + else if (child.kind === 240) { + return !!getTextToEmit(child); + } + return true; + } + ; function getTextToEmit(node) { switch (compilerOptions.jsx) { case 2: @@ -30173,23 +32232,40 @@ var ts; } } } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { + function isUseStrictPrologue(node) { + return !!node.expression.text.match(/use strict/); + } + function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { + if (writeUseStrict) { + if (startWithNewLine) { + writeLine(); + } + write("\"use strict\";"); + } + } + function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { + var foundUseStrict = false; + for (var i = 0; i < statements.length; i++) { if (ts.isPrologueDirective(statements[i])) { + if (isUseStrictPrologue(statements[i])) { + foundUseStrict = true; + } if (startWithNewLine || i > 0) { writeLine(); } emit(statements[i]); } else { + ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); return i; } } + ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); return statements.length; } function writeLines(text) { var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; ++i) { + for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line.length) { writeLine(); @@ -30199,22 +32275,22 @@ var ts; } function emitEmitHelpers(node) { if (!compilerOptions.noEmitHelpers) { - if ((languageVersion < 2) && (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8)) { + if ((languageVersion < 2) && (!extendsEmitted && node.flags & 262144)) { writeLines(extendsHelper); extendsEmitted = true; } - if (!decorateEmitted && resolver.getNodeCheckFlags(node) & 16) { + if (!decorateEmitted && node.flags & 524288) { writeLines(decorateHelper); if (compilerOptions.emitDecoratorMetadata) { writeLines(metadataHelper); } decorateEmitted = true; } - if (!paramEmitted && resolver.getNodeCheckFlags(node) & 32) { + if (!paramEmitted && node.flags & 1048576) { writeLines(paramHelper); paramEmitted = true; } - if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & 64) { + if (!awaiterEmitted && node.flags & 2097152) { writeLines(awaiterHelper); awaiterEmitted = true; } @@ -30225,15 +32301,20 @@ var ts; emitShebang(); emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1]; - emitModule(node); + if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { + var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ts.ModuleKind.CommonJS]; + emitModule(node); + } + else { + bundleEmitDelegates[modulekind](node, true); + } } else { var startIndex = emitDirectivePrologues(node.statements, false); externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30241,12 +32322,15 @@ var ts; } emitLeadingComments(node.endOfFileToken); } + function emit(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + } function emitNodeWithCommentsAndWithoutSourcemap(node) { emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); } function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { if (node) { - if (node.flags & 4) { + if (node.flags & 2) { return emitCommentsOnNotEmittedNode(node); } if (isSpecializedCommentHandling(node)) { @@ -30262,35 +32346,55 @@ var ts; } } } + function emitNodeWithSourceMap(node) { + if (node) { + emitStart(node); + emitNodeWithoutSourceMap(node); + emitEnd(node); + } + } function emitNodeWithoutSourceMap(node) { if (node) { emitJavaScriptWorker(node); } } + function changeSourceMapEmit(writer) { + sourceMap = writer; + emitStart = writer.emitStart; + emitEnd = writer.emitEnd; + emitPos = writer.emitPos; + setSourceFile = writer.setSourceFile; + } + function withTemporaryNoSourceMap(callback) { + var prevSourceMap = sourceMap; + setSourceMapWriterEmit(ts.getNullSourceMapWriter()); + callback(); + setSourceMapWriterEmit(prevSourceMap); + } function isSpecializedCommentHandling(node) { switch (node.kind) { - case 215: - case 213: - case 222: - case 221: - case 216: - case 227: + case 219: + case 217: + case 226: + case 225: + case 220: + case 231: return true; } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 193: + case 197: return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 218: + case 222: return shouldEmitModuleDeclaration(node); - case 217: + case 221: return shouldEmitEnumDeclaration(node); } ts.Debug.assert(!isSpecializedCommentHandling(node)); - if (node.kind !== 192 && + if (node.kind !== 196 && node.parent && - node.parent.kind === 174 && + node.parent.kind === 178 && node.parent.body === node && compilerOptions.target <= 1) { return false; @@ -30301,13 +32405,13 @@ var ts; switch (node.kind) { case 69: return emitIdentifier(node); - case 138: + case 140: return emitParameter(node); - case 143: - case 142: - return emitMethod(node); case 145: - case 146: + case 144: + return emitMethod(node); + case 147: + case 148: return emitAccessor(node); case 97: return emitThis(node); @@ -30327,142 +32431,142 @@ var ts; case 13: case 14: return emitLiteral(node); - case 183: - return emitTemplateExpression(node); - case 190: - return emitTemplateSpan(node); - case 233: - case 234: - return emitJsxElement(node); - case 236: - return emitJsxText(node); - case 240: - return emitJsxExpression(node); - case 135: - return emitQualifiedName(node); - case 161: - return emitObjectBindingPattern(node); - case 162: - return emitArrayBindingPattern(node); - case 163: - return emitBindingElement(node); - case 164: - return emitArrayLiteral(node); - case 165: - return emitObjectLiteral(node); - case 245: - return emitPropertyAssignment(node); - case 246: - return emitShorthandPropertyAssignment(node); - case 136: - return emitComputedPropertyName(node); - case 166: - return emitPropertyAccess(node); - case 167: - return emitIndexedAccess(node); - case 168: - return emitCallExpression(node); - case 169: - return emitNewExpression(node); - case 170: - return emitTaggedTemplateExpression(node); - case 171: - return emit(node.expression); - case 189: - return emit(node.expression); - case 172: - return emitParenExpression(node); - case 213: - case 173: - case 174: - return emitFunctionDeclaration(node); - case 175: - return emitDeleteExpression(node); - case 176: - return emitTypeOfExpression(node); - case 177: - return emitVoidExpression(node); - case 178: - return emitAwaitExpression(node); - case 179: - return emitPrefixUnaryExpression(node); - case 180: - return emitPostfixUnaryExpression(node); - case 181: - return emitBinaryExpression(node); - case 182: - return emitConditionalExpression(node); - case 185: - return emitSpreadElementExpression(node); - case 184: - return emitYieldExpression(node); case 187: - return; - case 192: - case 219: - return emitBlock(node); - case 193: - return emitVariableStatement(node); + return emitTemplateExpression(node); case 194: - return write(";"); - case 195: - return emitExpressionStatement(node); - case 196: - return emitIfStatement(node); - case 197: - return emitDoStatement(node); - case 198: - return emitWhileStatement(node); - case 199: - return emitForStatement(node); - case 201: - case 200: - return emitForInOrForOfStatement(node); - case 202: - case 203: - return emitBreakOrContinueStatement(node); - case 204: - return emitReturnStatement(node); - case 205: - return emitWithStatement(node); - case 206: - return emitSwitchStatement(node); - case 241: - case 242: - return emitCaseOrDefaultClause(node); - case 207: - return emitLabeledStatement(node); - case 208: - return emitThrowStatement(node); - case 209: - return emitTryStatement(node); + return emitTemplateSpan(node); + case 237: + case 238: + return emitJsxElement(node); + case 240: + return emitJsxText(node); case 244: - return emitCatchClause(node); - case 210: - return emitDebuggerStatement(node); - case 211: - return emitVariableDeclaration(node); - case 186: - return emitClassExpression(node); - case 214: - return emitClassDeclaration(node); - case 215: - return emitInterfaceDeclaration(node); + return emitJsxExpression(node); + case 137: + return emitQualifiedName(node); + case 165: + return emitObjectBindingPattern(node); + case 166: + return emitArrayBindingPattern(node); + case 167: + return emitBindingElement(node); + case 168: + return emitArrayLiteral(node); + case 169: + return emitObjectLiteral(node); + case 249: + return emitPropertyAssignment(node); + case 250: + return emitShorthandPropertyAssignment(node); + case 138: + return emitComputedPropertyName(node); + case 170: + return emitPropertyAccess(node); + case 171: + return emitIndexedAccess(node); + case 172: + return emitCallExpression(node); + case 173: + return emitNewExpression(node); + case 174: + return emitTaggedTemplateExpression(node); + case 175: + return emit(node.expression); + case 193: + return emit(node.expression); + case 176: + return emitParenExpression(node); case 217: - return emitEnumDeclaration(node); - case 247: - return emitEnumMember(node); - case 218: - return emitModuleDeclaration(node); - case 222: - return emitImportDeclaration(node); - case 221: - return emitImportEqualsDeclaration(node); - case 228: - return emitExportDeclaration(node); - case 227: - return emitExportAssignment(node); + case 177: + case 178: + return emitFunctionDeclaration(node); + case 179: + return emitDeleteExpression(node); + case 180: + return emitTypeOfExpression(node); + case 181: + return emitVoidExpression(node); + case 182: + return emitAwaitExpression(node); + case 183: + return emitPrefixUnaryExpression(node); + case 184: + return emitPostfixUnaryExpression(node); + case 185: + return emitBinaryExpression(node); + case 186: + return emitConditionalExpression(node); + case 189: + return emitSpreadElementExpression(node); + case 188: + return emitYieldExpression(node); + case 191: + return; + case 196: + case 223: + return emitBlock(node); + case 197: + return emitVariableStatement(node); + case 198: + return write(";"); + case 199: + return emitExpressionStatement(node); + case 200: + return emitIfStatement(node); + case 201: + return emitDoStatement(node); + case 202: + return emitWhileStatement(node); + case 203: + return emitForStatement(node); + case 205: + case 204: + return emitForInOrForOfStatement(node); + case 206: + case 207: + return emitBreakOrContinueStatement(node); + case 208: + return emitReturnStatement(node); + case 209: + return emitWithStatement(node); + case 210: + return emitSwitchStatement(node); + case 245: + case 246: + return emitCaseOrDefaultClause(node); + case 211: + return emitLabeledStatement(node); + case 212: + return emitThrowStatement(node); + case 213: + return emitTryStatement(node); case 248: + return emitCatchClause(node); + case 214: + return emitDebuggerStatement(node); + case 215: + return emitVariableDeclaration(node); + case 190: + return emitClassExpression(node); + case 218: + return emitClassDeclaration(node); + case 219: + return emitInterfaceDeclaration(node); + case 221: + return emitEnumDeclaration(node); + case 251: + return emitEnumMember(node); + case 222: + return emitModuleDeclaration(node); + case 226: + return emitImportDeclaration(node); + case 225: + return emitImportEqualsDeclaration(node); + case 232: + return emitExportDeclaration(node); + case 231: + return emitExportAssignment(node); + case 252: return emitSourceFileNode(node); } } @@ -30470,7 +32574,7 @@ var ts; return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } function getLeadingCommentsWithoutDetachedComments() { - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); + var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -30480,10 +32584,10 @@ var ts; return leadingComments; } function isTripleSlashComment(comment) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 && + if (currentText.charCodeAt(comment.pos + 1) === 47 && comment.pos + 2 < comment.end && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 47) { - var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end); + currentText.charCodeAt(comment.pos + 2) === 47) { + var textSubStr = currentText.substring(comment.pos, comment.end); return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? true : false; @@ -30492,20 +32596,20 @@ var ts; } function getLeadingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 248 || node.pos !== node.parent.pos) { + if (node.parent.kind === 252 || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { return getLeadingCommentsWithoutDetachedComments(); } else { - return ts.getLeadingCommentRangesOfNode(node, currentSourceFile); + return ts.getLeadingCommentRangesOfNodeFromText(node, currentText); } } } } function getTrailingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 248 || node.end !== node.parent.end) { - return ts.getTrailingCommentRanges(currentSourceFile.text, node.end); + if (node.parent.kind === 252 || node.end !== node.parent.end) { + return ts.getTrailingCommentRanges(currentText, node.end); } } } @@ -30528,22 +32632,22 @@ var ts; leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); } } - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment); } function emitTrailingComments(node) { if (compilerOptions.removeComments) { return; } var trailingComments = getTrailingCommentsToEmit(node); - ts.emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, trailingComments, false, newLine, writeComment); } function emitTrailingCommentsOfPosition(pos) { if (compilerOptions.removeComments) { return; } - var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos); - ts.emitComments(currentSourceFile, writer, trailingComments, true, newLine, writeComment); + var trailingComments = ts.getTrailingCommentRanges(currentText, pos); + ts.emitComments(currentText, currentLineMap, writer, trailingComments, true, newLine, writeComment); } function emitLeadingCommentsOfPositionWorker(pos) { if (compilerOptions.removeComments) { @@ -30554,13 +32658,13 @@ var ts; leadingComments = getLeadingCommentsWithoutDetachedComments(); } else { - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); + leadingComments = ts.getLeadingCommentRanges(currentText, pos); } - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); - ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment); } function emitDetachedCommentsAndUpdateCommentsInfo(node) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); + var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments); if (currentDetachedCommentInfo) { if (detachedCommentsInfo) { detachedCommentsInfo.push(currentDetachedCommentInfo); @@ -30570,18 +32674,30 @@ var ts; } } } + function writeComment(text, lineMap, writer, comment, newLine) { + emitPos(comment.pos); + ts.writeCommentRange(text, lineMap, writer, comment, newLine); + emitPos(comment.end); + } function emitShebang() { - var shebang = ts.getShebang(currentSourceFile.text); + var shebang = ts.getShebang(currentText); if (shebang) { write(shebang); + writeLine(); } } - var _a; + var _a, _b; } - function emitFile(jsFilePath, sourceFile) { - emitJavaScript(jsFilePath, sourceFile); - if (compilerOptions.declaration) { - ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); + function emitFile(_a, sourceFiles, isBundledEmit) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; + } + if (declarationFilePath) { + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } } } @@ -30594,11 +32710,11 @@ var ts; ts.ioReadTime = 0; ts.ioWriteTime = 0; var emptyArray = []; - ts.version = "1.8.0"; - function findConfigFile(searchPath) { + ts.version = "1.9.0"; + function findConfigFile(searchPath, fileExists) { var fileName = "tsconfig.json"; while (true) { - if (ts.sys.fileExists(fileName)) { + if (fileExists(fileName)) { return fileName; } var parentPath = ts.getDirectoryPath(searchPath); @@ -30617,86 +32733,331 @@ var ts; return ts.normalizePath(referencedFileName); } ts.resolveTripleslashReference = resolveTripleslashReference; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var moduleResolution = compilerOptions.moduleResolution !== undefined - ? compilerOptions.moduleResolution - : compilerOptions.module === 1 ? 2 : 1; - switch (moduleResolution) { - case 2: return nodeModuleNameResolver(moduleName, containingFile, host); - case 1: return classicNameResolver(moduleName, containingFile, compilerOptions, host); - } + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); } - ts.resolveModuleName = resolveModuleName; - function nodeModuleNameResolver(moduleName, containingFile, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { - var failedLookupLocations = []; - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host); - if (resolvedFileName) { - return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceModuleResolution && host.trace !== undefined; + } + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return str.indexOf(suffix, expectedPos) === expectedPos; + } + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + if (ts.isRootedDiskPath(moduleName)) { + return false; + } + var i = moduleName.lastIndexOf("./", 1); + var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46); + return !startsWithDotSlashOrDotDotSlash; + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); } - resolvedFileName = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); - return resolvedFileName - ? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } else { - return loadModuleFromNodeModules(moduleName, containingDirectory, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); } } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var longestMatchPrefixLength = -1; + var matchedPattern; + var matchedStar; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + for (var key in state.compilerOptions.paths) { + var pattern = key; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (moduleName.length >= prefix.length + suffix.length && + startsWith(moduleName, prefix) && + endsWith(moduleName, suffix)) { + if (prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = prefix.length; + matchedPattern = pattern; + matchedStar = moduleName.substr(prefix.length, moduleName.length - suffix.length); + } + } + } + else if (pattern === moduleName) { + matchedPattern = pattern; + matchedStar = undefined; + break; + } + } + } + if (matchedPattern) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPattern); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPattern]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("\*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var isExternalLibraryImport = false; + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function loadNodeModuleFromFile(candidate, failedLookupLocation, host) { - return ts.forEach(ts.moduleFileExtensions, tryLoad); + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + return ts.forEach(extensions, tryLoad); function tryLoad(ext) { + if (ext === ".tsx" && state.skipTsx) { + return undefined; + } var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (host.fileExists(fileName)) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName); + } return fileName; } else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } failedLookupLocation.push(fileName); return undefined; } } } - function loadNodeModuleFromDirectory(candidate, failedLookupLocation, host) { + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { var packageJsonPath = ts.combinePaths(candidate, "package.json"); - if (host.fileExists(packageJsonPath)) { + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } var jsonContent; try { - var jsonText = host.readFile(packageJsonPath); + var jsonText = state.host.readFile(packageJsonPath); jsonContent = jsonText ? JSON.parse(jsonText) : { typings: undefined }; } catch (e) { jsonContent = { typings: undefined }; } if (jsonContent.typings) { - var result = loadNodeModuleFromFile(ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); - if (result) { - return result; + if (typeof jsonContent.typings === "string") { + var typingsFile = ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile); + } + var result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typingsFile), state.host), state); + if (result) { + return result; + } + } + else if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings); + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_typings_field); } } } else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } failedLookupLocation.push(packageJsonPath); } - return loadNodeModuleFromFile(ts.combinePaths(candidate, "index"), failedLookupLocation, host); + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } - function loadModuleFromNodeModules(moduleName, directory, host) { - var failedLookupLocations = []; + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { directory = ts.normalizeSlashes(directory); while (true) { var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var result = loadNodeModuleFromFile(candidate, failedLookupLocations, host); + var result = loadModuleFromFile(candidate, ts.supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { - return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; + return result; } - result = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); + result = loadNodeModuleFromDirectory(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { - return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; + return result; } } var parentPath = ts.getDirectoryPath(directory); @@ -30705,42 +33066,36 @@ var ts; } directory = parentPath; } - return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - function nameStartsWithDotSlashOrDotDotSlash(name) { - var i = name.lastIndexOf("./", 1); - return i === 0 || (i === 1 && name.charCodeAt(0) === 46); + return undefined; } function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - if (moduleName.indexOf("!") != -1) { - return { resolvedModule: undefined, failedLookupLocations: [] }; - } - var searchPath = ts.getDirectoryPath(containingFile); - var searchName; + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } var referencedSourceFile; - while (true) { - searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - referencedSourceFile = ts.forEach(ts.supportedExtensions, function (extension) { - if (extension === ".tsx" && !compilerOptions.jsx) { - return undefined; + if (moduleHasNonRelativeName(moduleName)) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + break; } - var candidate = searchName + extension; - if (host.fileExists(candidate)) { - return candidate; + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + break; } - else { - failedLookupLocations.push(candidate); - } - }); - if (referencedSourceFile) { - break; + containingDirectory = parentPath; } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); } return referencedSourceFile ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } @@ -30748,11 +33103,9 @@ var ts; } ts.classicNameResolver = classicNameResolver; ts.defaultInitCompilerOptions = { - module: 1, - target: 0, + module: ts.ModuleKind.CommonJS, + target: 1, noImplicitAny: false, - outDir: "built", - rootDir: ".", sourceMap: false }; function createCompilerHost(options, setParentNodes) { @@ -30818,14 +33171,16 @@ var ts; getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); } + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + trace: function (s) { return ts.sys.write(s + newLine); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); } }; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -30863,12 +33218,30 @@ var ts; var noDiagnosticsTypeChecker; var classifiableNames; var skipDefaultLib = options.noLib; + var supportedExtensions = ts.getSupportedExtensions(options); var start = new Date().getTime(); host = host || createCompilerHost(options); + var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var currentDirectory = host.getCurrentDirectory(); var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) - : (function (moduleNames, containingFile) { return ts.map(moduleNames, function (moduleName) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }); }); + : (function (moduleNames, containingFile) { + var resolvedModuleNames = []; + var lookup = {}; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedName = void 0; + if (ts.hasProperty(lookup, moduleName)) { + resolvedName = lookup[moduleName]; + } + else { + resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule; + lookup[moduleName] = resolvedName; + } + resolvedModuleNames.push(resolvedName); + } + return resolvedModuleNames; + }); var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (oldProgram) { @@ -30877,7 +33250,8 @@ var ts; (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx)) { + (oldOptions.jsx !== options.jsx) || + (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } @@ -30887,9 +33261,7 @@ var ts; processRootFile(host.getDefaultLibFileName(options), true); } } - verifyCompilerOptions(); oldProgram = undefined; - ts.programTime += new Date().getTime() - start; program = { getRootFileNames: function () { return rootNames; }, getSourceFile: getSourceFile, @@ -30903,7 +33275,7 @@ var ts; getTypeChecker: getTypeChecker, getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: function () { return commonSourceDirectory; }, + getCommonSourceDirectory: getCommonSourceDirectory, emit: emit, getCurrentDirectory: function () { return currentDirectory; }, getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, @@ -30912,7 +33284,23 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; } }; + verifyCompilerOptions(); + ts.programTime += new Date().getTime() - start; return program; + function getCommonSourceDirectory() { + if (typeof commonSourceDirectory === "undefined") { + if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(files); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); @@ -30955,10 +33343,13 @@ var ts; if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { return false; } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + return false; + } if (resolveModuleNamesWorker) { - var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); + var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); - for (var i = 0; i < moduleNames.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); var resolutionChanged = oldResolution @@ -30979,7 +33370,7 @@ var ts; } newSourceFiles.push(newSourceFile); } - for (var i = 0, len = newSourceFiles.length; i < len; ++i) { + for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; @@ -31000,7 +33391,8 @@ var ts; getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, - writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }) + writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }), + isEmitBlocked: isEmitBlocked }; } function getDiagnosticsProducingTypeChecker() { @@ -31013,9 +33405,22 @@ var ts; var _this = this; return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { - if (options.noEmitOnError && getPreEmitDiagnostics(program, undefined, cancellationToken).length > 0) { - return { diagnostics: [], sourceMaps: undefined, emitSkipped: true }; + var declarationDiagnostics = []; + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emitSkipped: true }; + } + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { diagnostics: diagnostics, sourceMaps: undefined, emitSkipped: true }; + } } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); var start = new Date().getTime(); @@ -31068,12 +33473,166 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? + getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : + typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } + function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var diagnostics = []; + walk(sourceFile); + return diagnostics; + function walk(node) { + if (!node) { + return false; + } + switch (node.kind) { + case 225: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return true; + case 231: + if (node.isExportEquals) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 218: + var classDeclaration = node; + if (checkModifiers(classDeclaration.modifiers) || + checkTypeParameters(classDeclaration.typeParameters)) { + return true; + } + break; + case 247: + var heritageClause = node; + if (heritageClause.token === 106) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 219: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 222: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 220: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return true; + case 145: + case 144: + case 146: + case 147: + case 148: + case 177: + case 217: + case 178: + case 217: + var functionDeclaration = node; + if (checkModifiers(functionDeclaration.modifiers) || + checkTypeParameters(functionDeclaration.typeParameters) || + checkTypeAnnotation(functionDeclaration.type)) { + return true; + } + break; + case 197: + var variableStatement = node; + if (checkModifiers(variableStatement.modifiers)) { + return true; + } + break; + case 215: + var variableDeclaration = node; + if (checkTypeAnnotation(variableDeclaration.type)) { + return true; + } + break; + case 172: + case 173: + var expression = node; + if (expression.typeArguments && expression.typeArguments.length > 0) { + var start_2 = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 140: + var parameter = node; + if (parameter.modifiers) { + var start_3 = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return true; + } + if (parameter.questionToken) { + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return true; + } + if (parameter.type) { + diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 143: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 221: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 175: + 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 141: + if (!options.experimentalDecorators) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + return true; + } + return ts.forEachChild(node, walk); + } + function checkTypeParameters(typeParameters) { + if (typeParameters) { + var start_4 = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkTypeAnnotation(type) { + if (type) { + diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkModifiers(modifiers) { + if (modifiers) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 112: + case 110: + case 111: + case 127: + case 122: + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + case 113: + case 82: + case 74: + case 77: + case 115: + } + } + } + return false; + } + }); + } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (!ts.isDeclarationFile(sourceFile)) { @@ -31106,21 +33665,32 @@ var ts; function moduleNameIsEqualTo(a, b) { return a.text === b.text; } + function getTextOfLiteral(literal) { + return literal.text; + } function collectExternalModuleReferences(file) { if (file.imports) { return; } + var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isExternalModuleFile = ts.isExternalModule(file); var imports; + var moduleAugmentations; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; - collect(node, true); + collectModuleReferences(node, false); + if (isJavaScriptFile) { + collectRequireCalls(node); + } } file.imports = imports || emptyArray; - function collect(node, allowRelativeModuleNames) { + file.moduleAugmentations = moduleAugmentations || emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 222: - case 221: - case 228: + case 226: + case 225: + case 232: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9) { break; @@ -31128,17 +33698,31 @@ var ts; if (!moduleNameExpr.text) { break; } - if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { + if (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { (imports || (imports = [])).push(moduleNameExpr); } break; - case 218: - if (node.name.kind === 9 && (node.flags & 4 || ts.isDeclarationFile(file))) { - ts.forEachChild(node.body, function (node) { - collect(node, false); - }); + case 222: + if (ts.isAmbientModule(node) && (inAmbientModule || node.flags & 2 || ts.isDeclarationFile(file))) { + var moduleName = node.name; + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { + (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); + } + else if (!inAmbientModule) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); + } + } } - break; + } + } + function collectRequireCalls(node) { + if (ts.isRequireCall(node, true)) { + (imports || (imports = [])).push(node.arguments[0]); + } + else { + ts.forEachChild(node, collectRequireCalls); } } } @@ -31146,9 +33730,9 @@ var ts; var diagnosticArgument; var diagnostic; if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; + diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; @@ -31166,7 +33750,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -31190,10 +33774,10 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function findSourceFile(fileName, normalizedAbsolutePath, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(normalizedAbsolutePath)) { - var file_1 = filesByName.get(normalizedAbsolutePath); - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== normalizedAbsolutePath) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + if (filesByName.contains(path)) { + var file_1 = filesByName.get(path); + if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } return file_1; @@ -31206,16 +33790,16 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); - filesByName.set(normalizedAbsolutePath, file); + filesByName.set(path, file); if (file) { - file.path = normalizedAbsolutePath; + file.path = path; if (host.useCaseSensitiveFileNames()) { - var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); + var existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(normalizedAbsolutePath, file); + filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -31225,7 +33809,6 @@ var ts; } processImportedModules(file, basePath); if (isDefaultLib) { - file.isDefaultLib = true; files.unshift(file); } else { @@ -31245,19 +33828,22 @@ var ts; } function processImportedModules(file, basePath) { collectExternalModuleReferences(file); - if (file.imports.length) { + if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = {}; - var moduleNames = ts.map(file.imports, function (name) { return name.text; }); + var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); - for (var i = 0; i < file.imports.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - if (resolution && !options.noResolve) { + var shouldAddFile = resolution && + !options.noResolve && + i < file.imports.length; + if (shouldAddFile) { var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { - if (!ts.isExternalModule(importedFile)) { - var start_2 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); + if (!ts.isExternalModule(importedFile) && importedFile.statements.length) { + var start_5 = ts.getTokenPosOfNode(file.imports[i], file); + fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { var firstRef = importedFile.referencedFiles[0]; @@ -31274,7 +33860,7 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var commonPathComponents; - ts.forEach(files, function (sourceFile) { + var failed = ts.forEach(files, function (sourceFile) { if (ts.isDeclarationFile(sourceFile)) { return; } @@ -31285,10 +33871,9 @@ var ts; return; } for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; + return true; } commonPathComponents.length = i; break; @@ -31298,14 +33883,20 @@ var ts; commonPathComponents.length = sourcePathComponents.length; } }); + if (failed) { + return ""; + } + if (!commonPathComponents) { + return currentDirectory; + } return ts.getNormalizedPathFromPathComponents(commonPathComponents); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -31339,14 +33930,33 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } - if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap")); + } + if (options.paths && options.baseUrl === undefined) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!hasZeroOrOneAsteriskCharacter(key)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); + } + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var subst = _a[_i]; + if (!hasZeroOrOneAsteriskCharacter(subst)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); + } + } } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } + if (options.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); + } } if (options.out && options.outFile) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); @@ -31355,16 +33965,15 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } - if (options.sourceRoot) { + if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } - return; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); if (options.isolatedModules) { - if (!options.module && languageVersion < 2) { + if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -31373,25 +33982,22 @@ var ts; programDiagnostics.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) { + else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } - if (options.module === 5 && languageVersion < 2) { + if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } + if (outFile && options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + } if (options.outDir || options.sourceRoot || - (options.mapRoot && - (!outFile || firstExternalModuleSourceFile !== undefined))) { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { - commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); - } - else { - commonSourceDirectory = computeCommonSourceDirectory(files); - } - if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { - commonSourceDirectory += ts.directorySeparator; + options.mapRoot) { + var dir = getCommonSourceDirectory(); + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { @@ -31408,10 +34014,42 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } + else if (options.allowJs && options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } + if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + } + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); + }); + } + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + if (filesByName.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + } + if (emitFilesSeen.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + } + else { + emitFilesSeen.set(emitFilePath, true); + } + } + } + } + function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); } } ts.createProgram = createProgram; @@ -31466,6 +34104,11 @@ var ts; description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, error: ts.Diagnostics.Argument_for_jsx_must_be_preserve_or_react }, + { + name: "reactNamespace", + type: "string", + description: ts.Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit + }, { name: "listFiles", type: "boolean" @@ -31485,16 +34128,17 @@ var ts; name: "module", shortName: "m", type: { - "commonjs": 1, - "amd": 2, - "system": 4, - "umd": 3, - "es6": 5, - "es2015": 5 + "none": ts.ModuleKind.None, + "commonjs": ts.ModuleKind.CommonJS, + "amd": ts.ModuleKind.AMD, + "system": ts.ModuleKind.System, + "umd": ts.ModuleKind.UMD, + "es6": ts.ModuleKind.ES6, + "es2015": ts.ModuleKind.ES2015 }, description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND, - error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015 + error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none }, { name: "newLine", @@ -31660,8 +34304,8 @@ var ts; { name: "moduleResolution", type: { - "node": 2, - "classic": 1 + "node": ts.ModuleResolutionKind.NodeJs, + "classic": ts.ModuleResolutionKind.Classic }, description: ts.Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, error: ts.Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic @@ -31690,6 +34334,43 @@ var ts; name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "baseUrl", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + name: "paths", + type: "object", + isTSConfigOnly: true + }, + { + name: "rootDirs", + type: "object", + isTSConfigOnly: true, + isFilePath: true + }, + { + name: "traceModuleResolution", + type: "boolean", + description: ts.Diagnostics.Enable_tracing_of_the_module_resolution_process + }, + { + name: "allowJs", + type: "boolean", + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "noImplicitUseStrict", + type: "boolean", + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output } ]; var optionNameMapCache; @@ -31723,7 +34404,8 @@ var ts; function parseStrings(args) { var i = 0; while (i < args.length) { - var s = args[i++]; + var s = args[i]; + i++; if (s.charCodeAt(0) === 64) { parseResponseFile(s.slice(1)); } @@ -31734,28 +34416,36 @@ var ts; } if (ts.hasProperty(optionNameMap, s)) { var opt = optionNameMap[s]; - if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); } - switch (opt.type) { - case "number": - options[opt.name] = parseInt(args[i++]); - break; - case "boolean": - options[opt.name] = true; - break; - case "string": - options[opt.name] = args[i++] || ""; - break; - default: - var map_2 = opt.type; - var key = (args[i++] || "").toLowerCase(); - if (ts.hasProperty(map_2, key)) { - options[opt.name] = map_2[key]; - } - else { - errors.push(ts.createCompilerDiagnostic(opt.error)); - } + else { + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + options[opt.name] = true; + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + default: + var map_1 = opt.type; + var key = (args[i] || "").toLowerCase(); + i++; + if (ts.hasProperty(map_1, key)) { + options[opt.name] = map_1[key]; + } + else { + errors.push(ts.createCompilerDiagnostic(opt.error)); + } + } } } else { @@ -31841,8 +34531,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath) { - var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors; + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { + if (existingOptions === void 0) { existingOptions = {}; } + var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath, configFileName), optionsFromJsonConfigFile = _a.options, errors = _a.errors; + var options = ts.extend(existingOptions, optionsFromJsonConfigFile); return { options: options, fileNames: getFileNames(), @@ -31859,23 +34551,40 @@ var ts; } } else { - var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; - var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); - for (var i = 0; i < sysFiles.length; i++) { - var name_29 = sysFiles[i]; - if (ts.fileExtensionIs(name_29, ".d.ts")) { - var baseName = name_29.substr(0, name_29.length - ".d.ts".length); - if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) { - fileNames.push(name_29); - } + var filesSeen = {}; + var exclude = []; + if (json["exclude"] instanceof Array) { + exclude = json["exclude"]; + } + else { + exclude = ["node_modules"]; + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + exclude.push(outDir); } - else if (ts.fileExtensionIs(name_29, ".ts")) { - if (!ts.contains(sysFiles, name_29 + "x")) { - fileNames.push(name_29); + } + exclude = ts.map(exclude, ts.normalizeSlashes); + var supportedExtensions = ts.getSupportedExtensions(options); + ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); + for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; + var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); + for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { + var fileName = filesInDirWithExtension_1[_a]; + if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { + continue; } - } - else { - fileNames.push(name_29); + if (/\.min\.js$/.test(fileName)) { + continue; + } + if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { + var baseName = fileName.substr(0, fileName.length - extension.length); + if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { + continue; + } + } + filesSeen[fileName] = true; + fileNames.push(fileName); } } } @@ -31883,9 +34592,12 @@ var ts; } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function convertCompilerOptionsFromJson(jsonOptions, basePath) { + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var options = {}; var errors = []; + if (configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json") { + options.allowJs = true; + } if (!jsonOptions) { return { options: options, errors: errors }; } @@ -31908,7 +34620,36 @@ var ts; } } if (opt.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + switch (typeof value) { + case "string": + value = ts.normalizePath(ts.combinePaths(basePath, value)); + break; + case "object": + var paths = []; + var invalidOptionType = false; + if (!ts.isArray(value)) { + invalidOptionType = true; + } + else { + for (var _i = 0, _a = value; _i < _a.length; _i++) { + var element = _a[_i]; + if (typeof element === "string") { + paths.push(ts.normalizePath(ts.combinePaths(basePath, element))); + } + else { + invalidOptionType = true; + break; + } + } + } + if (invalidOptionType) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_should_have_array_of_strings_as_a_value, opt.name)); + } + else { + value = paths; + } + break; + } if (value === "") { value = "."; } @@ -31994,14 +34735,15 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } + function getRelativeFileName(fileName, host) { + return host ? ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : fileName; + } function reportDiagnosticSimply(diagnostic, host) { var output = ""; if (diagnostic.file) { var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var relativeFileName = host - ? ts.convertToRelativePath(diagnostic.file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) - : diagnostic.file.fileName; - output += diagnostic.file.fileName + "(" + (line + 1) + "," + (character + 1) + "): "; + var relativeFileName = getRelativeFileName(diagnostic.file.fileName, host); + output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): "; } var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); output += category + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + ts.sys.newLine; @@ -32013,7 +34755,7 @@ var ts; var gutterStyleSequence = "\u001b[100;30m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; - var elipsis = "..."; + var ellipsis = "..."; var categoryFormatMap = (_a = {}, _a[ts.DiagnosticCategory.Warning] = yellowForegroundEscapeSequence, _a[ts.DiagnosticCategory.Error] = redForegroundEscapeSequence, @@ -32030,15 +34772,16 @@ var ts; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; var _b = ts.getLineAndCharacterOfPosition(file, start + length_3), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var relativeFileName = getRelativeFileName(file.fileName, host); var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; var gutterWidth = (lastLine + 1 + "").length; if (hasMoreThanFiveLines) { - gutterWidth = Math.max(elipsis.length, gutterWidth); + gutterWidth = Math.max(ellipsis.length, gutterWidth); } output += ts.sys.newLine; for (var i = firstLine; i <= lastLine; i++) { if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(elipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -32065,7 +34808,7 @@ var ts; output += ts.sys.newLine; } output += ts.sys.newLine; - output += file.fileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; + output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; } var categoryColor = categoryFormatMap[diagnostic.category]; var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); @@ -32106,6 +34849,9 @@ var ts; function isJSONSupported() { return typeof JSON === "object" && typeof JSON.parse === "function"; } + function isWatchSet(options) { + return options.watch && options.hasOwnProperty("watch"); + } function executeCommandLine(args) { var commandLine = ts.parseCommandLine(args); var configFileName; @@ -32137,7 +34883,7 @@ var ts; return ts.sys.exit(ts.ExitStatus.Success); } if (commandLine.options.version) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Version_0, ts.version), undefined); + printVersion(); return ts.sys.exit(ts.ExitStatus.Success); } if (commandLine.options.help) { @@ -32150,28 +34896,43 @@ var ts; reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--project"), undefined); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } - configFileName = ts.normalizePath(ts.combinePaths(commandLine.options.project, "tsconfig.json")); if (commandLine.fileNames.length !== 0) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line), undefined); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } + var fileOrDirectory = ts.normalizePath(commandLine.options.project); + if (!fileOrDirectory || ts.sys.directoryExists(fileOrDirectory)) { + configFileName = ts.combinePaths(fileOrDirectory, "tsconfig.json"); + if (!ts.sys.fileExists(configFileName)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project), undefined); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + } + else { + configFileName = fileOrDirectory; + if (!ts.sys.fileExists(configFileName)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project), undefined); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + } } else if (commandLine.fileNames.length === 0 && isJSONSupported()) { var searchPath = ts.normalizePath(ts.sys.getCurrentDirectory()); - configFileName = ts.findConfigFile(searchPath); + configFileName = ts.findConfigFile(searchPath, ts.sys.fileExists); } if (commandLine.fileNames.length === 0 && !configFileName) { printVersion(); printHelp(); return ts.sys.exit(ts.ExitStatus.Success); } - if (commandLine.options.watch && commandLine.options.hasOwnProperty("watch")) { + if (isWatchSet(commandLine.options)) { if (!ts.sys.watchFile) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), undefined); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (configFileName) { - configFileWatcher = ts.sys.watchFile(configFileName, configFileChanged); + var configFilePath = ts.toPath(configFileName, ts.sys.getCurrentDirectory(), ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)); + configFileWatcher = ts.sys.watchFile(configFilePath, configFileChanged); } if (ts.sys.watchDirectory && configFileName) { var directory = ts.getDirectoryPath(configFileName); @@ -32191,9 +34952,20 @@ var ts; return; } } + if (!cachedConfigFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + reportDiagnostics([error], undefined); + ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return; + } var result = ts.parseConfigFileTextToJson(configFileName, cachedConfigFileText); var configObject = result.config; - var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getDirectoryPath(configFileName)); + if (!configObject) { + reportDiagnostics([result.error], undefined); + ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return; + } + var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), ts.sys.getCurrentDirectory()), commandLine.options, configFileName); if (configParseResult.errors.length > 0) { reportDiagnostics(configParseResult.errors, undefined); ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); @@ -32206,7 +34978,7 @@ var ts; if (configFileName) { var configParseResult = parseConfigFile(); rootFileNames = configParseResult.fileNames; - compilerOptions = ts.extend(commandLine.options, configParseResult.options); + compilerOptions = configParseResult.options; } else { rootFileNames = commandLine.fileNames; @@ -32223,7 +34995,7 @@ var ts; } cachedExistingFiles = {}; var compileResult = compile(rootFileNames, compilerOptions, compilerHost); - if (!compilerOptions.watch) { + if (!isWatchSet(compilerOptions)) { return ts.sys.exit(compileResult.exitStatus); } setCachedProgram(compileResult.program); @@ -32243,8 +35015,9 @@ var ts; } } var sourceFile = hostGetSourceFile(fileName, languageVersion, onError); - if (sourceFile && compilerOptions.watch) { - sourceFile.fileWatcher = ts.sys.watchFile(sourceFile.fileName, function (fileName, removed) { return sourceFileChanged(sourceFile, removed); }); + if (sourceFile && isWatchSet(compilerOptions)) { + var filePath = ts.toPath(sourceFile.fileName, ts.sys.getCurrentDirectory(), ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)); + sourceFile.fileWatcher = ts.sys.watchFile(filePath, function (fileName, removed) { return sourceFileChanged(sourceFile, removed); }); } return sourceFile; } @@ -32279,7 +35052,7 @@ var ts; startTimerForRecompilation(); } function watchedDirectoryChanged(fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName)) { + if (fileName && !ts.isSupportedSourceFileName(fileName, compilerOptions)) { return; } startTimerForHandlingDirectoryChanges(); @@ -32355,18 +35128,13 @@ var ts; diagnostics = program.getSemanticDiagnostics(); } } - reportDiagnostics(diagnostics, compilerHost); - if (compilerOptions.noEmit) { - return diagnostics.length - ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped - : ts.ExitStatus.Success; - } var emitOutput = program.emit(); - reportDiagnostics(emitOutput.diagnostics, compilerHost); - if (emitOutput.emitSkipped) { + diagnostics = diagnostics.concat(emitOutput.diagnostics); + reportDiagnostics(ts.sortAndDeduplicateDiagnostics(diagnostics), compilerHost); + if (emitOutput.emitSkipped && diagnostics.length > 0) { return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } - if (diagnostics.length > 0 || emitOutput.diagnostics.length > 0) { + else if (diagnostics.length > 0) { return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; } return ts.ExitStatus.Success; @@ -32442,12 +35210,17 @@ var ts; else { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions), - exclude: ["node_modules"] + compilerOptions: serializeCompilerOptions(compilerOptions) }; if (fileNames && fileNames.length) { configurations.files = fileNames; } + else { + configurations.exclude = ["node_modules"]; + if (compilerOptions.outDir) { + configurations.exclude.push(compilerOptions.outDir); + } + } ts.sys.writeFile(file, JSON.stringify(configurations, undefined, 4)); reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Successfully_created_a_tsconfig_json_file), undefined); } @@ -32455,10 +35228,10 @@ var ts; function serializeCompilerOptions(options) { var result = {}; var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name_30 in options) { - if (ts.hasProperty(options, name_30)) { - var value = options[name_30]; - switch (name_30) { + for (var name_31 in options) { + if (ts.hasProperty(options, name_31)) { + var value = options[name_31]; + switch (name_31) { case "init": case "watch": case "version": @@ -32466,17 +35239,17 @@ var ts; case "project": break; default: - var optionDefinition = optionsNameMap[name_30.toLowerCase()]; + var optionDefinition = optionsNameMap[name_31.toLowerCase()]; if (optionDefinition) { if (typeof optionDefinition.type === "string") { - result[name_30] = value; + result[name_31] = value; } else { var typeMap = optionDefinition.type; for (var key in typeMap) { if (ts.hasProperty(typeMap, key)) { if (typeMap[key] === value) - result[name_30] = key; + result[name_31] = key; } } } diff --git a/lib/tsserver.js b/lib/tsserver.js index 2893dab82ef..8c33f866268 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -13,13 +13,18 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +var __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 ts; (function (ts) { var OperationCanceledException = (function () { function OperationCanceledException() { } return OperationCanceledException; - })(); + }()); ts.OperationCanceledException = OperationCanceledException; (function (ExitStatus) { ExitStatus[ExitStatus["Success"] = 0] = "Success"; @@ -46,6 +51,21 @@ var ts; DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); var DiagnosticCategory = ts.DiagnosticCategory; + (function (ModuleResolutionKind) { + ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; + ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; + })(ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleResolutionKind = ts.ModuleResolutionKind; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; + ModuleKind[ModuleKind["System"] = 4] = "System"; + ModuleKind[ModuleKind["ES6"] = 5] = "ES6"; + ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + })(ts.ModuleKind || (ts.ModuleKind = {})); + var ModuleKind = ts.ModuleKind; })(ts || (ts = {})); var ts; (function (ts) { @@ -247,9 +267,11 @@ var ts; var count = array.length; if (count > 0) { var pos = 0; - var result = arguments.length <= 2 ? array[pos++] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos++; while (pos < count) { - result = f(result, array[pos++]); + result = f(result, array[pos]); + pos++; } return result; } @@ -261,9 +283,11 @@ var ts; if (array) { var pos = array.length - 1; if (pos >= 0) { - var result = arguments.length <= 2 ? array[pos--] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos--; while (pos >= 0) { - result = f(result, array[pos--]); + result = f(result, array[pos]); + pos--; } return result; } @@ -346,6 +370,22 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function reduceProperties(map, callback, initial) { + var result = initial; + if (map) { + for (var key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } + } + return result; + } + ts.reduceProperties = reduceProperties; + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; function memoize(callback) { var value; return function () { @@ -390,6 +430,14 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; + function formatMessage(dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; function createCompilerDiagnostic(message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 1) { @@ -616,7 +664,8 @@ var ts; if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { directoryComponents.length--; } - for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { + var joinStartIndex; + for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { break; } @@ -639,7 +688,7 @@ var ts; } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; function getBaseFileName(path) { - if (!path) { + if (path === undefined) { return undefined; } var i = path.lastIndexOf(ts.directorySeparator); @@ -664,14 +713,19 @@ var ts; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; - ts.supportedExtensions = [".ts", ".tsx", ".d.ts"]; - ts.moduleFileExtensions = ts.supportedExtensions; - function isSupportedSourceFileName(fileName) { + ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedJavascriptExtensions = [".js", ".jsx"]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options) { + return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + ts.getSupportedExtensions = getSupportedExtensions; + function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; } - for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; + for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -690,22 +744,6 @@ var ts; return path; } ts.removeFileExtension = removeFileExtension; - var backslashOrDoubleQuote = /[\"\\]/g; - var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { - "\0": "\\0", - "\t": "\\t", - "\v": "\\v", - "\f": "\\f", - "\b": "\\b", - "\r": "\\r", - "\n": "\\n", - "\\": "\\\\", - "\"": "\\\"", - "\u2028": "\\u2028", - "\u2029": "\\u2029", - "\u0085": "\\u0085" - }; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -716,17 +754,16 @@ var ts; } function Signature(checker) { } + function Node(kind, pos, end) { + this.kind = kind; + this.pos = pos; + this.end = end; + this.flags = 0; + this.parent = undefined; + } ts.objectAllocator = { - getNodeConstructor: function (kind) { - function Node(pos, end) { - this.pos = pos; - this.end = end; - this.flags = 0; - this.parent = undefined; - } - Node.prototype = { kind: kind }; - return Node; - }, + getNodeConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } @@ -765,6 +802,12 @@ var ts; return copiedList; } ts.copyListRemovingItem = copyListRemovingItem; + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; })(ts || (ts = {})); var ts; (function (ts) { @@ -903,8 +946,7 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); - var _tty = require("tty"); - function createWatchedFileSet(interval, chunkSize) { + function createPollingWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } if (chunkSize === void 0) { chunkSize = 30; } var watchedFiles = []; @@ -918,13 +960,13 @@ var ts; if (!watchedFile) { return; } - _fs.stat(watchedFile.fileName, function (err, stats) { + _fs.stat(watchedFile.filePath, function (err, stats) { if (err) { - watchedFile.callback(watchedFile.fileName); + watchedFile.callback(watchedFile.filePath); } else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) { - watchedFile.mtime = getModifiedTime(watchedFile.fileName); - watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0); + watchedFile.mtime = getModifiedTime(watchedFile.filePath); + watchedFile.callback(watchedFile.filePath, watchedFile.mtime.getTime() === 0); } }); } @@ -947,11 +989,11 @@ var ts; nextFileToCheck = nextToCheck; }, interval); } - function addFile(fileName, callback) { + function addFile(filePath, callback) { var file = { - fileName: fileName, + filePath: filePath, callback: callback, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(filePath) }; watchedFiles.push(file); if (watchedFiles.length === 1) { @@ -970,6 +1012,73 @@ var ts; removeFile: removeFile }; } + function createWatchedFileSet() { + var dirWatchers = ts.createFileMap(); + var fileWatcherCallbacks = ts.createFileMap(); + return { addFile: addFile, removeFile: removeFile }; + function reduceDirWatcherRefCountForFile(filePath) { + var dirPath = ts.getDirectoryPath(filePath); + if (dirWatchers.contains(dirPath)) { + var watcher = dirWatchers.get(dirPath); + watcher.referenceCount -= 1; + if (watcher.referenceCount <= 0) { + watcher.close(); + dirWatchers.remove(dirPath); + } + } + } + function addDirWatcher(dirPath) { + if (dirWatchers.contains(dirPath)) { + var watcher_1 = dirWatchers.get(dirPath); + watcher_1.referenceCount += 1; + return; + } + var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher.referenceCount = 1; + dirWatchers.set(dirPath, watcher); + return; + } + function addFileWatcherCallback(filePath, callback) { + if (fileWatcherCallbacks.contains(filePath)) { + fileWatcherCallbacks.get(filePath).push(callback); + } + else { + fileWatcherCallbacks.set(filePath, [callback]); + } + } + function addFile(filePath, callback) { + addFileWatcherCallback(filePath, callback); + addDirWatcher(ts.getDirectoryPath(filePath)); + return { filePath: filePath, callback: callback }; + } + function removeFile(watchedFile) { + removeFileWatcherCallback(watchedFile.filePath, watchedFile.callback); + reduceDirWatcherRefCountForFile(watchedFile.filePath); + } + function removeFileWatcherCallback(filePath, callback) { + if (fileWatcherCallbacks.contains(filePath)) { + var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks.get(filePath)); + if (newCallbacks.length === 0) { + fileWatcherCallbacks.remove(filePath); + } + else { + fileWatcherCallbacks.set(filePath, newCallbacks); + } + } + } + function fileEventHandler(eventName, relativeFileName, baseDirPath) { + var filePath = typeof relativeFileName !== "string" + ? undefined + : ts.toPath(relativeFileName, baseDirPath, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)); + if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks.contains(filePath)) { + for (var _i = 0, _a = fileWatcherCallbacks.get(filePath); _i < _a.length; _i++) { + var fileCallback = _a[_i]; + fileCallback(filePath); + } + } + } + } + var pollingWatchedFileSet = createPollingWatchedFileSet(); var watchedFileSet = createWatchedFileSet(); function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; @@ -977,7 +1086,7 @@ var ts; var platform = _os.platform(); var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; function readFile(fileName, encoding) { - if (!_fs.existsSync(fileName)) { + if (!fileExists(fileName)) { return undefined; } var buffer = _fs.readFileSync(fileName); @@ -1003,10 +1112,37 @@ var ts; if (writeByteOrderMark) { data = "\uFEFF" + data; } - _fs.writeFileSync(fileName, data, "utf8"); + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } } function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path.toLowerCase() : path; + return useCaseSensitiveFileNames ? path : path.toLowerCase(); + } + function fileSystemEntryExists(path, entryKind) { + try { + var stat = _fs.statSync(path); + switch (entryKind) { + case 0: return stat.isFile(); + case 1: return stat.isDirectory(); + } + } + catch (e) { + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1); } function readDirectory(path, extension, exclude) { var result = []; @@ -1046,17 +1182,22 @@ var ts; }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { - if (isNode4OrLater()) { - return _fs.watch(fileName, function (eventName, relativeFileName) { return callback(fileName); }); - } - var watchedFile = watchedFileSet.addFile(fileName, callback); + watchFile: function (filePath, callback) { + var watchSet = isNode4OrLater() ? watchedFileSet : pollingWatchedFileSet; + var watchedFile = watchSet.addFile(filePath, callback); return { - close: function () { return watchedFileSet.removeFile(watchedFile); } + close: function () { return watchSet.removeFile(watchedFile); } }; }, watchDirectory: function (path, callback, recursive) { - return _fs.watch(path, { persistent: true, recursive: !!recursive }, function (eventName, relativeFileName) { + var options; + if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + return _fs.watch(path, options, function (eventName, relativeFileName) { if (eventName === "rename") { callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(path, relativeFileName))); } @@ -1066,12 +1207,8 @@ var ts; resolvePath: function (path) { return _path.resolve(path); }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); - }, + fileExists: fileExists, + directoryExists: directoryExists, createDirectory: function (directoryName) { if (!this.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); @@ -1095,12 +1232,40 @@ var ts; } }; } + function getChakraSystem() { + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, encoding) { + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + if (writeByteOrderMark) { + data = "\uFEFF" + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + readDirectory: ChakraHost.readDirectory, + exit: ChakraHost.quit + }; + } if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { return getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { return getNodeSystem(); } + else if (typeof ChakraHost !== "undefined") { + return getChakraSystem(); + } else { return undefined; } @@ -1126,6 +1291,7 @@ var ts; An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_a_type_annotation_1021", message: "An index signature must have a type annotation." }, An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_must_have_a_type_annotation_1022", message: "An index signature parameter must have a type annotation." }, An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_type_must_be_string_or_number_1023", message: "An index signature parameter type must be 'string' or 'number'." }, + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: { code: 1024, category: ts.DiagnosticCategory.Error, key: "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", message: "'readonly' modifier can only appear on a property declaration or index signature." }, Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility_modifier_already_seen_1028", message: "Accessibility modifier already seen." }, _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{0}' modifier already seen." }, @@ -1139,7 +1305,7 @@ var ts; _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_a_class_declaration_1041", message: "'{0}' modifier cannot be used with a class declaration." }, _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_here_1042", message: "'{0}' modifier cannot be used here." }, _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_data_property_1043", message: "'{0}' modifier cannot appear on a data property." }, - _0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_element_1044", message: "'{0}' modifier cannot appear on a module element." }, + _0_modifier_cannot_appear_on_a_module_or_namespace_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", message: "'{0}' modifier cannot appear on a module or namespace element." }, A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", message: "A '{0}' modifier cannot be used with an interface declaration." }, A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", message: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_be_optional_1047", message: "A rest parameter cannot be optional." }, @@ -1158,8 +1324,11 @@ var ts; Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." }, _0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "{0} is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." }, + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." }, Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", message: "Unexpected token. A constructor, method, accessor, or property was expected." }, + _0_modifier_cannot_appear_on_a_type_member: { code: 1070, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_type_member_1070", message: "'{0}' modifier cannot appear on a type member." }, + _0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." }, A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." }, Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." }, Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher." }, @@ -1215,10 +1384,9 @@ var ts; String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, - Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: ts.DiagnosticCategory.Error, key: "Modifiers_not_permitted_on_index_signature_members_1145", message: "Modifiers not permitted on index signature members." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_1148", message: "Cannot compile modules unless the '--module' flag is provided." }, + Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting__1148", message: "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -1278,7 +1446,7 @@ var ts; Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_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_Speci_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning." }, + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_6_or_higher_1220", message: "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_1221", message: "Generators are not allowed in an ambient context." }, An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An_overload_signature_cannot_be_declared_as_a_generator_1222", message: "An overload signature cannot be declared as a generator." }, @@ -1301,10 +1469,14 @@ var ts; Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", message: "Unable to resolve signature of parameter decorator when called as an expression." }, Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", message: "Unable to resolve signature of property decorator when called as an expression." }, Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", message: "Unable to resolve signature of method decorator when called as an expression." }, - abstract_modifier_can_only_appear_on_a_class_or_method_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_or_method_declaration_1242", message: "'abstract' modifier can only appear on a class or method declaration." }, + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", message: "'abstract' modifier can only appear on a class, method, or property declaration." }, _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, + An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, + A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, + A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, @@ -1318,11 +1490,12 @@ var ts; Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list_2313", message: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." }, + Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, @@ -1332,6 +1505,7 @@ var ts; Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, + Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, @@ -1388,7 +1562,7 @@ var ts; get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", message: "Specialized overload signature is not assignable to any non-specialized signature." }, - Overload_signatures_must_all_be_exported_or_not_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_not_exported_2383", message: "Overload signatures must all be exported or not exported." }, + Overload_signatures_must_all_be_exported_or_non_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_non_exported_2383", message: "Overload signatures must all be exported or non-exported." }, Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", message: "Overload signatures must all be ambient or non-ambient." }, Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_public_private_or_protected_2385", message: "Overload signatures must all be public, private or protected." }, Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_optional_or_required_2386", message: "Overload signatures must all be optional or required." }, @@ -1402,6 +1576,7 @@ var ts; Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, @@ -1420,7 +1595,6 @@ var ts; Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'" }, Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." }, Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0: { code: 2419, category: ts.DiagnosticCategory.Error, key: "Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0_2419", message: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." }, Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." }, A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_implement_another_class_or_interface_2422", message: "A class may only implement another class or interface." }, Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, @@ -1428,7 +1602,7 @@ var ts; Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'" }, - All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_interface_must_have_identical_type_parameters_2428", message: "All declarations of an interface must have identical type parameters." }, + All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." }, Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'" }, In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, @@ -1448,8 +1622,8 @@ var ts; Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_2449", message: "The operand of an increment or decrement operator cannot be a constant." }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_2450", message: "Left-hand side of assignment expression cannot be a constant." }, + The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property_2449", message: "The operand of an increment or decrement operator cannot be a constant or a read-only property." }, + Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property_2450", message: "Left-hand side of assignment expression cannot be a constant or a read-only property." }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, @@ -1482,8 +1656,8 @@ var ts; Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" }, - The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant_2485", message: "The left-hand side of a 'for...of' statement cannot be a previously defined constant." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant_2486", message: "The left-hand side of a 'for...in' statement cannot be a previously defined constant." }, + The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property_2485", message: "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property." }, + The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property_2486", message: "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property." }, Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_of_statement_2487", message: "Invalid left-hand side in 'for...of' statement." }, Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, @@ -1509,12 +1683,13 @@ var ts; Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", message: "Base constructor return type '{0}' is not a class or interface type." }, Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base_constructors_must_all_have_the_same_return_type_2510", message: "Base constructors must all have the same return type." }, Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot_create_an_instance_of_the_abstract_class_0_2511", message: "Cannot create an instance of the abstract class '{0}'." }, - Overload_signatures_must_all_be_abstract_or_not_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_not_abstract_2512", message: "Overload signatures must all be abstract or not abstract." }, + Overload_signatures_must_all_be_abstract_or_non_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", message: "Overload signatures must all be abstract or non-abstract." }, Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", message: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes_containing_abstract_methods_must_be_marked_abstract_2514", message: "Classes containing abstract methods must be marked abstract." }, Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, @@ -1524,7 +1699,9 @@ var ts; A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_must_be_an_object_type_2600", message: "JSX element attributes type '{0}' must be an object type." }, + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, + Property_0_is_incompatible_with_index_signature: { code: 2530, category: ts.DiagnosticCategory.Error, key: "Property_0_is_incompatible_with_index_signature_2530", message: "Property '{0}' is incompatible with index signature." }, + JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'" }, @@ -1540,6 +1717,25 @@ var ts; Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element" }, + Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'" }, + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, + Cannot_re_export_name_that_is_not_defined_in_the_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_name_that_is_not_defined_in_the_module_2661", message: "Cannot re-export name that is not defined in the module." }, + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, + Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope_2665", message: "Module augmentation cannot introduce new names in the top level scope." }, + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: { code: 2672, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", message: "Cannot assign a '{0}' constructor type to a '{1}' constructor type." }, + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: { code: 2673, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", message: "Constructor of class '{0}' is private and only accessible within the class declaration." }, + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: { code: 2674, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", message: "Constructor of class '{0}' is protected and only accessible within the class declaration." }, + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: { code: 2675, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", message: "Cannot extend a class '{0}'. Class constructor is marked as private." }, + Accessors_must_both_be_abstract_or_non_abstract: { code: 2676, category: ts.DiagnosticCategory.Error, key: "Accessors_must_both_be_abstract_or_non_abstract_2676", message: "Accessors must both be abstract or non-abstract." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1624,6 +1820,14 @@ var ts; Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, + Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'" }, + The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'" }, + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." }, + Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, + Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character" }, + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character" }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -1634,6 +1838,7 @@ var ts; Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -1656,7 +1861,7 @@ var ts; Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." }, - Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015_6046", message: "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', or 'es2015'." }, + Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none_6046", message: "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'none'." }, Argument_for_target_option_must_be_ES3_ES5_or_ES2015: { code: 6047, category: ts.DiagnosticCategory.Error, key: "Argument_for_target_option_must_be_ES3_ES5_or_ES2015_6047", message: "Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'." }, Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form or -. For example '{0}' or '{1}'." }, Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." }, @@ -1673,6 +1878,7 @@ var ts; NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "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_6062", message: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Argument_for_moduleResolution_option_must_be_node_or_classic: { code: 6063, category: ts.DiagnosticCategory.Error, key: "Argument_for_moduleResolution_option_must_be_node_or_classic_6063", message: "Argument for '--moduleResolution' option must be 'node' or 'classic'." }, + Option_0_can_only_be_specified_in_tsconfig_json_file: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", message: "Option '{0}' can only be specified in 'tsconfig.json' file." }, Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, @@ -1688,6 +1894,37 @@ var ts; Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, + Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, + Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." }, + Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit_6084", message: "Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit" }, + Enable_tracing_of_the_module_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_module_resolution_process_6085", message: "Enable tracing of the module resolution process." }, + Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" }, + Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." }, + Module_resolution_kind_is_not_specified_using_0: { code: 6088, category: ts.DiagnosticCategory.Message, key: "Module_resolution_kind_is_not_specified_using_0_6088", message: "Module resolution kind is not specified, using '{0}'." }, + Module_name_0_was_successfully_resolved_to_1: { code: 6089, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_successfully_resolved_to_1_6089", message: "======== Module name '{0}' was successfully resolved to '{1}'. ========" }, + Module_name_0_was_not_resolved: { code: 6090, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_not_resolved_6090", message: "======== Module name '{0}' was not resolved. ========" }, + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: { code: 6091, category: ts.DiagnosticCategory.Message, key: "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", message: "'paths' option is specified, looking for a pattern to match module name '{0}'." }, + Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." }, + Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." }, + Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." }, + Loading_module_as_file_Slash_folder_candidate_module_location_0: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_6095", message: "Loading module as file / folder, candidate module location '{0}'." }, + File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." }, + File_0_exist_use_it_as_a_module_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_module_resolution_result_6097", message: "File '{0}' exist - use it as a module resolution result." }, + Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." }, + Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, + package_json_does_not_have_typings_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_typings_field_6100", message: "'package.json' does not have 'typings' field." }, + package_json_has_typings_field_0_that_references_1: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_typings_field_0_that_references_1_6101", message: "'package.json' has 'typings' field '{0}' that references '{1}'." }, + Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, + Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, + Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." }, + Expected_type_of_typings_field_in_package_json_to_be_string_got_0: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_typings_field_in_package_json_to_be_string_got_0_6105", message: "Expected type of 'typings' field in 'package.json' to be 'string', got '{0}'." }, + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'" }, + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'" }, + Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'" }, + Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'" }, + Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'" }, + Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed" }, + Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -1695,6 +1932,7 @@ var ts; _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", message: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, @@ -1725,7 +1963,6 @@ var ts; 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_8014", message: "'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_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, - 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_8017", message: "'decorators' can only be used in a .ts file." }, 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_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, @@ -1735,7 +1972,9 @@ var ts; Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'" }, An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." } + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, + JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." } }; })(ts || (ts = {})); var ts; @@ -1768,7 +2007,7 @@ var ts; "false": 84, "finally": 85, "for": 86, - "from": 133, + "from": 134, "function": 87, "get": 123, "if": 88, @@ -1783,24 +2022,26 @@ var ts; "namespace": 126, "new": 92, "null": 93, - "number": 128, + "number": 129, "package": 109, "private": 110, "protected": 111, "public": 112, - "require": 127, + "readonly": 127, + "require": 128, + "global": 135, "return": 94, - "set": 129, + "set": 130, "static": 113, - "string": 130, + "string": 131, "super": 95, "switch": 96, - "symbol": 131, + "symbol": 132, "this": 97, "throw": 98, "true": 99, "try": 100, - "type": 132, + "type": 133, "typeof": 101, "var": 102, "void": 103, @@ -1809,7 +2050,7 @@ var ts; "yield": 114, "async": 118, "await": 119, - "of": 134, + "of": 136, "{": 15, "}": 16, "(": 17, @@ -1925,7 +2166,8 @@ var ts; var pos = 0; var lineStart = 0; while (pos < text.length) { - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 13: if (text.charCodeAt(pos) === 10) { @@ -2028,6 +2270,9 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; function skipTrivia(text, pos, stopAfterLineBreak) { + if (!(pos >= 0)) { + return pos; + } while (true) { var ch = text.charCodeAt(pos); switch (ch) { @@ -2148,7 +2393,7 @@ var ts; function getCommentRanges(text, pos, trailing) { var result; var collecting = trailing || pos === 0; - while (true) { + while (pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13: @@ -2217,6 +2462,7 @@ var ts; } return result; } + return result; } function getLeadingCommentRanges(text, pos) { return getCommentRanges(text, pos, false); @@ -2244,6 +2490,18 @@ var ts; ch > 127 && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; + function isIdentifier(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1, n = name.length; i < n; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifier = isIdentifier; function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0; } var pos; @@ -2274,6 +2532,7 @@ var ts; scanJsxIdentifier: scanJsxIdentifier, reScanJsxToken: reScanJsxToken, scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, scan: scan, setText: setText, setScriptTarget: setScriptTarget, @@ -2281,7 +2540,8 @@ var ts; setOnError: setOnError, setTextPos: setTextPos, tryScan: tryScan, - lookAhead: lookAhead + lookAhead: lookAhead, + scanRange: scanRange }; function error(message, length) { if (onError) { @@ -2312,7 +2572,7 @@ var ts; error(ts.Diagnostics.Digit_expected); } } - return +(text.substring(start, end)); + return "" + +(text.substring(start, end)); } function scanOctalDigits() { var start = pos; @@ -2353,7 +2613,8 @@ var ts; return value; } function scanString() { - var quote = text.charCodeAt(pos++); + var quote = text.charCodeAt(pos); + pos++; var result = ""; var start = pos; while (true) { @@ -2440,7 +2701,8 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); return ""; } - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 48: return "\0"; @@ -2649,7 +2911,8 @@ var ts; } return pos += 2, token = 31; } - return pos++, token = 49; + pos++; + return token = 49; case 34: case 39: tokenValue = scanString(); @@ -2660,7 +2923,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 62; } - return pos++, token = 40; + pos++; + return token = 40; case 38: if (text.charCodeAt(pos + 1) === 38) { return pos += 2, token = 51; @@ -2668,11 +2932,14 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 66; } - return pos++, token = 46; + pos++; + return token = 46; case 40: - return pos++, token = 17; + pos++; + return token = 17; case 41: - return pos++, token = 18; + pos++; + return token = 18; case 42: if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 59; @@ -2683,7 +2950,8 @@ var ts; } return pos += 2, token = 38; } - return pos++, token = 37; + pos++; + return token = 37; case 43: if (text.charCodeAt(pos + 1) === 43) { return pos += 2, token = 41; @@ -2691,9 +2959,11 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 57; } - return pos++, token = 35; + pos++; + return token = 35; case 44: - return pos++, token = 24; + pos++; + return token = 24; case 45: if (text.charCodeAt(pos + 1) === 45) { return pos += 2, token = 42; @@ -2701,16 +2971,18 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 58; } - return pos++, token = 36; + pos++; + return token = 36; case 46: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = "" + scanNumber(); + tokenValue = scanNumber(); return token = 8; } if (text.charCodeAt(pos + 1) === 46 && text.charCodeAt(pos + 2) === 46) { return pos += 3, token = 22; } - return pos++, token = 21; + pos++; + return token = 21; case 47: if (text.charCodeAt(pos + 1) === 47) { pos += 2; @@ -2756,7 +3028,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 61; } - return pos++, token = 39; + pos++; + return token = 39; case 48: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 || text.charCodeAt(pos + 1) === 120)) { pos += 2; @@ -2801,12 +3074,14 @@ var ts; case 55: case 56: case 57: - tokenValue = "" + scanNumber(); + tokenValue = scanNumber(); return token = 8; case 58: - return pos++, token = 54; + pos++; + return token = 54; case 59: - return pos++, token = 23; + pos++; + return token = 23; case 60: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2831,7 +3106,8 @@ var ts; text.charCodeAt(pos + 2) !== 42) { return pos += 2, token = 26; } - return pos++, token = 25; + pos++; + return token = 25; case 61: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2851,7 +3127,8 @@ var ts; if (text.charCodeAt(pos + 1) === 62) { return pos += 2, token = 34; } - return pos++, token = 56; + pos++; + return token = 56; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -2862,20 +3139,26 @@ var ts; return token = 7; } } - return pos++, token = 27; + pos++; + return token = 27; case 63: - return pos++, token = 53; + pos++; + return token = 53; case 91: - return pos++, token = 19; + pos++; + return token = 19; case 93: - return pos++, token = 20; + pos++; + return token = 20; case 94: if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 68; } - return pos++, token = 48; + pos++; + return token = 48; case 123: - return pos++, token = 15; + pos++; + return token = 15; case 124: if (text.charCodeAt(pos + 1) === 124) { return pos += 2, token = 52; @@ -2883,13 +3166,17 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 67; } - return pos++, token = 47; + pos++; + return token = 47; case 125: - return pos++, token = 16; + pos++; + return token = 16; case 126: - return pos++, token = 50; + pos++; + return token = 50; case 64: - return pos++, token = 55; + pos++; + return token = 55; case 92: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -2898,7 +3185,8 @@ var ts; return token = getIdentifierToken(); } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0; + pos++; + return token = 0; default: if (isIdentifierStart(ch, languageVersion)) { pos++; @@ -2920,7 +3208,8 @@ var ts; continue; } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0; + pos++; + return token = 0; } } } @@ -2936,10 +3225,12 @@ var ts; if (text.charCodeAt(pos + 1) === 61) { return pos += 2, token = 64; } - return pos++, token = 44; + pos++; + return token = 44; } if (text.charCodeAt(pos) === 61) { - return pos++, token = 29; + pos++; + return token = 29; } } return token; @@ -3022,7 +3313,7 @@ var ts; break; } } - return token = 236; + return token = 240; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { @@ -3040,6 +3331,54 @@ var ts; } return token; } + function scanJSDocToken() { + if (pos >= end) { + return token = 1; + } + startPos = pos; + var ch = text.charCodeAt(pos); + while (pos < end) { + ch = text.charCodeAt(pos); + if (isWhiteSpace(ch)) { + pos++; + } + else { + break; + } + } + tokenPos = pos; + switch (ch) { + case 64: + return pos += 1, token = 55; + case 10: + case 13: + return pos += 1, token = 4; + case 42: + return pos += 1, token = 37; + case 123: + return pos += 1, token = 15; + case 125: + return pos += 1, token = 16; + case 91: + return pos += 1, token = 19; + case 93: + return pos += 1, token = 20; + case 61: + return pos += 1, token = 56; + case 44: + return pos += 1, token = 24; + } + if (isIdentifierStart(ch, 2)) { + pos++; + while (isIdentifierPart(text.charCodeAt(pos), 2) && pos < end) { + pos++; + } + return token = 69; + } + else { + return pos += 1, token = 0; + } + } function speculationHelper(callback, isLookahead) { var savePos = pos; var saveStartPos = startPos; @@ -3058,6 +3397,29 @@ var ts; } return result; } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var savePrecedingLineBreak = precedingLineBreak; + var saveTokenValue = tokenValue; + var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + var saveTokenIsUnterminated = tokenIsUnterminated; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + precedingLineBreak = savePrecedingLineBreak; + tokenValue = saveTokenValue; + hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; + tokenIsUnterminated = saveTokenIsUnterminated; + return result; + } function lookAhead(callback) { return speculationHelper(callback, true); } @@ -3142,6 +3504,11 @@ var ts; description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, error: ts.Diagnostics.Argument_for_jsx_must_be_preserve_or_react }, + { + name: "reactNamespace", + type: "string", + description: ts.Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit + }, { name: "listFiles", type: "boolean" @@ -3161,16 +3528,17 @@ var ts; name: "module", shortName: "m", type: { - "commonjs": 1, - "amd": 2, - "system": 4, - "umd": 3, - "es6": 5, - "es2015": 5 + "none": ts.ModuleKind.None, + "commonjs": ts.ModuleKind.CommonJS, + "amd": ts.ModuleKind.AMD, + "system": ts.ModuleKind.System, + "umd": ts.ModuleKind.UMD, + "es6": ts.ModuleKind.ES6, + "es2015": ts.ModuleKind.ES2015 }, description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND, - error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015 + error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none }, { name: "newLine", @@ -3336,8 +3704,8 @@ var ts; { name: "moduleResolution", type: { - "node": 2, - "classic": 1 + "node": ts.ModuleResolutionKind.NodeJs, + "classic": ts.ModuleResolutionKind.Classic }, description: ts.Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, error: ts.Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic @@ -3366,6 +3734,43 @@ var ts; name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "baseUrl", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + name: "paths", + type: "object", + isTSConfigOnly: true + }, + { + name: "rootDirs", + type: "object", + isTSConfigOnly: true, + isFilePath: true + }, + { + name: "traceModuleResolution", + type: "boolean", + description: ts.Diagnostics.Enable_tracing_of_the_module_resolution_process + }, + { + name: "allowJs", + type: "boolean", + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "noImplicitUseStrict", + type: "boolean", + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output } ]; var optionNameMapCache; @@ -3399,7 +3804,8 @@ var ts; function parseStrings(args) { var i = 0; while (i < args.length) { - var s = args[i++]; + var s = args[i]; + i++; if (s.charCodeAt(0) === 64) { parseResponseFile(s.slice(1)); } @@ -3410,28 +3816,36 @@ var ts; } if (ts.hasProperty(optionNameMap, s)) { var opt = optionNameMap[s]; - if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); } - switch (opt.type) { - case "number": - options[opt.name] = parseInt(args[i++]); - break; - case "boolean": - options[opt.name] = true; - break; - case "string": - options[opt.name] = args[i++] || ""; - break; - default: - var map_1 = opt.type; - var key = (args[i++] || "").toLowerCase(); - if (ts.hasProperty(map_1, key)) { - options[opt.name] = map_1[key]; - } - else { - errors.push(ts.createCompilerDiagnostic(opt.error)); - } + else { + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + options[opt.name] = true; + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + default: + var map_1 = opt.type; + var key = (args[i] || "").toLowerCase(); + i++; + if (ts.hasProperty(map_1, key)) { + options[opt.name] = map_1[key]; + } + else { + errors.push(ts.createCompilerDiagnostic(opt.error)); + } + } } } else { @@ -3517,8 +3931,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath) { - var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors; + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { + if (existingOptions === void 0) { existingOptions = {}; } + var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath, configFileName), optionsFromJsonConfigFile = _a.options, errors = _a.errors; + var options = ts.extend(existingOptions, optionsFromJsonConfigFile); return { options: options, fileNames: getFileNames(), @@ -3535,23 +3951,40 @@ var ts; } } else { - var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; - var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); - for (var i = 0; i < sysFiles.length; i++) { - var name_5 = sysFiles[i]; - if (ts.fileExtensionIs(name_5, ".d.ts")) { - var baseName = name_5.substr(0, name_5.length - ".d.ts".length); - if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) { - fileNames.push(name_5); - } + var filesSeen = {}; + var exclude = []; + if (json["exclude"] instanceof Array) { + exclude = json["exclude"]; + } + else { + exclude = ["node_modules"]; + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + exclude.push(outDir); } - else if (ts.fileExtensionIs(name_5, ".ts")) { - if (!ts.contains(sysFiles, name_5 + "x")) { - fileNames.push(name_5); + } + exclude = ts.map(exclude, ts.normalizeSlashes); + var supportedExtensions = ts.getSupportedExtensions(options); + ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); + for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; + var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); + for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { + var fileName = filesInDirWithExtension_1[_a]; + if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { + continue; } - } - else { - fileNames.push(name_5); + if (/\.min\.js$/.test(fileName)) { + continue; + } + if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { + var baseName = fileName.substr(0, fileName.length - extension.length); + if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { + continue; + } + } + filesSeen[fileName] = true; + fileNames.push(fileName); } } } @@ -3559,9 +3992,12 @@ var ts; } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function convertCompilerOptionsFromJson(jsonOptions, basePath) { + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var options = {}; var errors = []; + if (configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json") { + options.allowJs = true; + } if (!jsonOptions) { return { options: options, errors: errors }; } @@ -3584,7 +4020,36 @@ var ts; } } if (opt.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + switch (typeof value) { + case "string": + value = ts.normalizePath(ts.combinePaths(basePath, value)); + break; + case "object": + var paths = []; + var invalidOptionType = false; + if (!ts.isArray(value)) { + invalidOptionType = true; + } + else { + for (var _i = 0, _a = value; _i < _a.length; _i++) { + var element = _a[_i]; + if (typeof element === "string") { + paths.push(ts.normalizePath(ts.combinePaths(basePath, element))); + } + else { + invalidOptionType = true; + break; + } + } + } + if (invalidOptionType) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_should_have_array_of_strings_as_a_value, opt.name)); + } + else { + value = paths; + } + break; + } if (value === "") { value = "."; } @@ -3621,10 +4086,10 @@ var ts; var stringWriters = []; function getSingleLineStringWriter() { if (stringWriters.length === 0) { - var str = ""; - var writeText = function (text) { return str += text; }; + var str_1 = ""; + var writeText = function (text) { return str_1 += text; }; return { - string: function () { return str; }, + string: function () { return str_1; }, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -3632,10 +4097,10 @@ var ts; writeStringLiteral: writeText, writeParameter: writeText, writeSymbol: writeText, - writeLine: function () { return str += " "; }, + writeLine: function () { return str_1 += " "; }, increaseIndent: function () { }, decreaseIndent: function () { }, - clear: function () { return str = ""; }, + clear: function () { return str_1 = ""; }, trackSymbol: function () { }, reportInaccessibleThisError: function () { } }; @@ -3659,7 +4124,7 @@ var ts; if (array1.length !== array2.length) { return false; } - for (var i = 0; i < array1.length; ++i) { + for (var i = 0; i < array1.length; i++) { var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; if (!equals) { return false; @@ -3685,26 +4150,38 @@ var ts; ts.setResolvedModule = setResolvedModule; function containsParseError(node) { aggregateChildData(node); - return (node.parserContextFlags & 64) !== 0; + return (node.flags & 268435456) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.parserContextFlags & 128)) { - var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & 16) !== 0) || + if (!(node.flags & 536870912)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 67108864) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { - node.parserContextFlags |= 64; + node.flags |= 268435456; } - node.parserContextFlags |= 128; + node.flags |= 536870912; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 248) { + while (node && node.kind !== 252) { node = node.parent; } return node; } ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 196: + case 224: + case 203: + case 204: + case 205: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; function getStartPositionOfLine(line, sourceFile) { ts.Debug.assert(line >= 0); return ts.getLineStarts(sourceFile)[line]; @@ -3779,10 +4256,39 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 24576) !== 0 || + return (getCombinedNodeFlags(declaration) & 3072) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isAmbientModule(node) { + return node && node.kind === 222 && + (node.name.kind === 9 || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isBlockScopedContainerTopLevel(node) { + return node.kind === 252 || + node.kind === 222 || + isFunctionLike(node) || + isFunctionBlock(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 131072); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + if (!node || !isAmbientModule(node)) { + return false; + } + switch (node.parent.kind) { + case 252: + return isExternalModule(node.parent); + case 223: + return isAmbientModule(node.parent.parent) && !isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -3790,15 +4296,15 @@ var ts; return current; } switch (current.kind) { + case 252: + case 224: case 248: - case 220: - case 244: - case 218: - case 199: - case 200: - case 201: + case 222: + case 203: + case 204: + case 205: return current; - case 192: + case 196: if (!isFunctionLike(current.parent)) { return current; } @@ -3809,9 +4315,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 211 && + declaration.kind === 215 && declaration.parent && - declaration.parent.kind === 244; + declaration.parent.kind === 248; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; function declarationNameToString(name) { @@ -3847,22 +4353,26 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 248: + case 252: 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 211: - case 163: - case 214: - case 186: case 215: + case 167: case 218: + case 190: + case 219: + case 222: + case 221: + case 251: case 217: - case 247: - case 213: - case 173: + case 177: + case 145: + case 147: + case 148: + case 220: errorNode = node.name; break; } @@ -3879,16 +4389,20 @@ var ts; return file.externalModuleIndicator !== undefined; } ts.isExternalModule = isExternalModule; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; function isDeclarationFile(file) { - return (file.flags & 4096) !== 0; + return file.isDeclarationFile; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 217 && isConst(node); + return node.kind === 221 && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 163 || isBindingPattern(node))) { + while (node && (node.kind === 167 || isBindingPattern(node))) { node = node.parent; } return node; @@ -3896,113 +4410,123 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 211) { + if (node.kind === 215) { node = node.parent; } - if (node && node.kind === 212) { + if (node && node.kind === 216) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 193) { + if (node && node.kind === 197) { flags |= node.flags; } return flags; } ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 16384); + return !!(getCombinedNodeFlags(node) & 2048); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 8192); + return !!(getCombinedNodeFlags(node) & 1024); } ts.isLet = isLet; + function isSuperCallExpression(n) { + return n.kind === 172 && n.expression.kind === 95; + } + ts.isSuperCallExpression = isSuperCallExpression; function isPrologueDirective(node) { - return node.kind === 195 && node.expression.kind === 9; + return node.kind === 199 && node.expression.kind === 9; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getLeadingCommentRangesOfNodeFromText(node, text) { + return ts.getLeadingCommentRanges(text, node.pos); + } + ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; function getJsDocComments(node, sourceFileOfNode) { - var commentRanges = (node.kind === 138 || node.kind === 137) ? - ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) : - getLeadingCommentRangesOfNode(node, sourceFileOfNode); - return ts.filter(commentRanges, isJsDocComment); - function isJsDocComment(comment) { - return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === 42 && - sourceFileOfNode.text.charCodeAt(comment.pos + 2) === 42 && - sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== 47; - } + return getJsDocCommentsFromText(node, sourceFileOfNode.text); } ts.getJsDocComments = getJsDocComments; + function getJsDocCommentsFromText(node, text) { + var commentRanges = (node.kind === 140 || node.kind === 139) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + getLeadingCommentRangesOfNodeFromText(node, text); + return ts.filter(commentRanges, isJsDocComment); + function isJsDocComment(comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 42 && + text.charCodeAt(comment.pos + 3) !== 47; + } + } + ts.getJsDocCommentsFromText = getJsDocCommentsFromText; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isTypeNode(node) { - if (151 <= node.kind && node.kind <= 160) { + if (152 <= node.kind && node.kind <= 164) { return true; } switch (node.kind) { case 117: - case 128: - case 130: - case 120: + case 129: case 131: + case 120: + case 132: return true; case 103: - return node.parent.kind !== 177; - case 9: - return node.parent.kind === 138; - case 188: + return node.parent.kind !== 181; + case 192: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); case 69: - if (node.parent.kind === 135 && node.parent.right === node) { + if (node.parent.kind === 137 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 166 && node.parent.name === node) { + else if (node.parent.kind === 170 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 69 || node.kind === 135 || node.kind === 166, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); - case 135: - case 166: + ts.Debug.assert(node.kind === 69 || node.kind === 137 || node.kind === 170, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + case 137: + case 170: case 97: var parent_1 = node.parent; - if (parent_1.kind === 154) { + if (parent_1.kind === 156) { return false; } - if (151 <= parent_1.kind && parent_1.kind <= 160) { + if (152 <= parent_1.kind && parent_1.kind <= 164) { return true; } switch (parent_1.kind) { - case 188: + case 192: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); - case 137: + case 139: return node === parent_1.constraint; - case 141: - case 140: - case 138: - case 211: - return node === parent_1.type; - case 213: - case 173: - case 174: - case 144: case 143: case 142: - case 145: - case 146: + case 140: + case 215: return node === parent_1.type; + case 217: + case 177: + case 178: + case 146: + case 145: + case 144: case 147: case 148: + return node === parent_1.type; case 149: + case 150: + case 151: return node === parent_1.type; - case 171: + case 175: return node === parent_1.type; - case 168: - case 169: + case 172: + case 173: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 170: + case 174: return false; } } @@ -4013,23 +4537,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 204: + case 208: return visitor(node); - case 220: - case 192: + case 224: case 196: - case 197: - case 198: - case 199: case 200: case 201: + case 202: + case 203: + case 204: case 205: - case 206: - case 241: - case 242: - case 207: case 209: - case 244: + case 210: + case 245: + case 246: + case 211: + case 213: + case 248: return ts.forEachChild(node, traverse); } } @@ -4039,24 +4563,24 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 184: + case 188: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 217: - case 215: + case 221: + case 219: + case 222: + case 220: case 218: - case 216: - case 214: - case 186: + case 190: return; default: if (isFunctionLike(node)) { - var name_6 = node.name; - if (name_6 && name_6.kind === 136) { - traverse(name_6.expression); + var name_5 = node.name; + if (name_5 && name_5.kind === 138) { + traverse(name_5.expression); return; } } @@ -4070,14 +4594,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 163: - case 247: - case 138: - case 245: - case 141: + case 167: + case 251: case 140: - case 246: - case 211: + case 249: + case 143: + case 142: + case 250: + case 215: return true; } } @@ -4085,11 +4609,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - return node && (node.kind === 145 || node.kind === 146); + return node && (node.kind === 147 || node.kind === 148); } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 214 || node.kind === 186); + return node && (node.kind === 218 || node.kind === 190); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -4098,32 +4622,32 @@ var ts; ts.isFunctionLike = isFunctionLike; function isFunctionLikeKind(kind) { switch (kind) { - case 144: - case 173: - case 213: - case 174: - case 143: - case 142: - case 145: case 146: + case 177: + case 217: + case 178: + case 145: + case 144: case 147: case 148: case 149: - case 152: - case 153: + case 150: + case 151: + case 154: + case 155: return true; } } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 143: - case 142: - case 144: case 145: + case 144: case 146: - case 213: - case 173: + case 147: + case 148: + case 217: + case 177: return true; } return false; @@ -4131,26 +4655,34 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 199: - case 200: + case 203: + case 204: + case 205: case 201: - case 197: - case 198: + case 202: return true; - case 207: + case 211: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 192 && isFunctionLike(node.parent); + return node && node.kind === 196 && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 143 && node.parent.kind === 165; + return node && node.kind === 145 && node.parent.kind === 169; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0; + } + ts.isThisTypePredicate = isThisTypePredicate; function getContainingFunction(node) { while (true) { node = node.parent; @@ -4176,91 +4708,95 @@ var ts; return undefined; } switch (node.kind) { - case 136: + case 138: if (isClassLike(node.parent.parent)) { return node; } node = node.parent; break; - case 139: - if (node.parent.kind === 138 && isClassElement(node.parent.parent)) { + case 141: + if (node.parent.kind === 140 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 174: + case 178: if (!includeArrowFunctions) { continue; } - case 213: - case 173: - case 218: - case 141: - case 140: + case 217: + case 177: + case 222: case 143: case 142: - case 144: case 145: + case 144: case 146: case 147: case 148: case 149: - case 217: - case 248: + case 150: + case 151: + case 221: + case 252: return node; } } } ts.getThisContainer = getThisContainer; - function getSuperContainer(node, includeFunctions) { + function getSuperContainer(node, stopOnFunctions) { while (true) { node = node.parent; - if (!node) + if (!node) { return node; + } switch (node.kind) { - case 136: - if (isClassLike(node.parent.parent)) { - return node; - } + case 138: node = node.parent; break; - case 139: - if (node.parent.kind === 138 && isClassElement(node.parent.parent)) { + case 217: + case 177: + case 178: + if (!stopOnFunctions) { + continue; + } + case 143: + case 142: + case 145: + case 144: + case 146: + case 147: + case 148: + return node; + case 141: + if (node.parent.kind === 140 && isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (isClassElement(node.parent)) { node = node.parent; } break; - case 213: - case 173: - case 174: - if (!includeFunctions) { - continue; - } - case 141: - case 140: - case 143: - case 142: - case 144: - case 145: - case 146: - return node; } } } ts.getSuperContainer = getSuperContainer; + function isSuperPropertyOrElementAccess(node) { + return (node.kind === 170 + || node.kind === 171) + && node.expression.kind === 95; + } + ts.isSuperPropertyOrElementAccess = isSuperPropertyOrElementAccess; function getEntityNameFromTypeNode(node) { if (node) { switch (node.kind) { - case 151: + case 153: return node.typeName; - case 188: + case 192: return node.expression; case 69: - case 135: + case 137: return node; } } @@ -4268,7 +4804,7 @@ var ts; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 170) { + if (node.kind === 174) { return node.tag; } return node.expression; @@ -4276,69 +4812,36 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 214: + case 218: return true; - case 141: - return node.parent.kind === 214; - case 138: - return node.parent.body && node.parent.parent.kind === 214; - case 145: - case 146: case 143: - return node.body && node.parent.kind === 214; + return node.parent.kind === 218; + case 147: + case 148: + case 145: + return node.body !== undefined + && node.parent.kind === 218; + case 140: + return node.parent.body !== undefined + && (node.parent.kind === 146 + || node.parent.kind === 145 + || node.parent.kind === 148) + && node.parent.parent.kind === 218; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { - switch (node.kind) { - case 214: - if (node.decorators) { - return true; - } - return false; - case 141: - case 138: - if (node.decorators) { - return true; - } - return false; - case 145: - if (node.body && node.decorators) { - return true; - } - return false; - case 143: - case 146: - if (node.body && node.decorators) { - return true; - } - return false; - } - return false; + return node.decorators !== undefined + && nodeCanBeDecorated(node); } ts.nodeIsDecorated = nodeIsDecorated; - function childIsDecorated(node) { - switch (node.kind) { - case 214: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 143: - case 146: - return ts.forEach(node.parameters, nodeIsDecorated); - } - return false; - } - ts.childIsDecorated = childIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); - } - ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function isPropertyAccessExpression(node) { - return node.kind === 166; + return node.kind === 170; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 167; + return node.kind === 171; } ts.isElementAccessExpression = isElementAccessExpression; function isExpression(node) { @@ -4348,42 +4851,42 @@ var ts; case 99: case 84: case 10: - case 164: - case 165: - case 166: - case 167: case 168: case 169: case 170: - case 189: case 171: case 172: case 173: - case 186: case 174: - case 177: + case 193: case 175: case 176: + case 177: + case 190: + case 178: + case 181: case 179: case 180: - case 181: - case 182: - case 185: case 183: - case 11: - case 187: - case 233: - case 234: case 184: - case 178: + case 185: + case 186: + case 189: + case 187: + case 11: + case 191: + case 237: + case 238: + case 188: + case 182: return true; - case 135: - while (node.parent.kind === 135) { + case 137: + while (node.parent.kind === 137) { node = node.parent; } - return node.parent.kind === 154; + return node.parent.kind === 156; case 69: - if (node.parent.kind === 154) { + if (node.parent.kind === 156) { return true; } case 8: @@ -4391,47 +4894,47 @@ var ts; case 97: var parent_2 = node.parent; switch (parent_2.kind) { - case 211: - case 138: - case 141: + case 215: case 140: - case 247: - case 245: - case 163: + case 143: + case 142: + case 251: + case 249: + case 167: return parent_2.initializer === node; - case 195: - case 196: - case 197: - case 198: - case 204: - case 205: - case 206: - case 241: - case 208: - case 206: - return parent_2.expression === node; case 199: - var forStatement = parent_2; - return (forStatement.initializer === node && forStatement.initializer.kind !== 212) || - forStatement.condition === node || - forStatement.incrementor === node; case 200: case 201: + case 202: + case 208: + case 209: + case 210: + case 245: + case 212: + case 210: + return parent_2.expression === node; + case 203: + var forStatement = parent_2; + return (forStatement.initializer === node && forStatement.initializer.kind !== 216) || + forStatement.condition === node || + forStatement.incrementor === node; + case 204: + case 205: var forInStatement = parent_2; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 212) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 216) || forInStatement.expression === node; - case 171: - case 189: + case 175: + case 193: return node === parent_2.expression; - case 190: + case 194: return node === parent_2.expression; - case 136: + case 138: return node === parent_2.expression; - case 139: - case 240: - case 239: + case 141: + case 244: + case 243: return true; - case 188: + case 192: return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: if (isExpression(parent_2)) { @@ -4453,7 +4956,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 && node.moduleReference.kind === 232; + return node.kind === 225 && node.moduleReference.kind === 236; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -4462,34 +4965,83 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 && node.moduleReference.kind !== 232; + return node.kind === 225 && node.moduleReference.kind !== 236; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJavaScript(file) { + return isInJavaScriptFile(file); + } + ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isInJavaScriptFile(node) { + return node && !!(node.flags & 134217728); + } + ts.isInJavaScriptFile = isInJavaScriptFile; + function isRequireCall(expression, checkArgumentIsStringLiteral) { + var isRequire = expression.kind === 172 && + expression.expression.kind === 69 && + expression.expression.text === "require" && + expression.arguments.length === 1; + return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9); + } + ts.isRequireCall = isRequireCall; + function getSpecialPropertyAssignmentKind(expression) { + if (expression.kind !== 185) { + return 0; + } + var expr = expression; + if (expr.operatorToken.kind !== 56 || expr.left.kind !== 170) { + return 0; + } + var lhs = expr.left; + if (lhs.expression.kind === 69) { + var lhsId = lhs.expression; + if (lhsId.text === "exports") { + return 1; + } + else if (lhsId.text === "module" && lhs.name.text === "exports") { + return 2; + } + } + else if (lhs.expression.kind === 97) { + return 4; + } + else if (lhs.expression.kind === 170) { + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 69 && innerPropertyAccess.name.text === "prototype") { + return 3; + } + } + return 0; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 222) { + if (node.kind === 226) { return node.moduleSpecifier; } - if (node.kind === 221) { + if (node.kind === 225) { var reference = node.moduleReference; - if (reference.kind === 232) { + if (reference.kind === 236) { return reference.expression; } } - if (node.kind === 228) { + if (node.kind === 232) { return node.moduleSpecifier; } + if (node.kind === 222 && node.name.kind === 9) { + return node.name; + } } ts.getExternalModuleName = getExternalModuleName; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 138: + case 140: + case 145: + case 144: + case 250: + case 249: case 143: case 142: - case 246: - case 245: - case 141: - case 140: return node.questionToken !== undefined; } } @@ -4497,49 +5049,83 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 261 && + return node.kind === 265 && node.parameters.length > 0 && - node.parameters[0].type.kind === 263; + node.parameters[0].type.kind === 267; } 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 getJSDocTag(node, kind, checkParentVariableStatement) { + if (!node) { + return undefined; + } + var jsDocComment = getJSDocComment(node, checkParentVariableStatement); + if (!jsDocComment) { + return undefined; + } + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === kind) { + return tag; } } } + function getJSDocComment(node, checkParentVariableStatement) { + if (node.jsDocComment) { + return node.jsDocComment; + } + if (checkParentVariableStatement) { + var isInitializerOfVariableDeclarationInStatement = node.parent.kind === 215 && + node.parent.initializer === node && + node.parent.parent.parent.kind === 197; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined; + if (variableStatementNode) { + return variableStatementNode.jsDocComment; + } + var parent_3 = node.parent; + var isSourceOfAssignmentExpressionStatement = parent_3 && parent_3.parent && + parent_3.kind === 185 && + parent_3.operatorToken.kind === 56 && + parent_3.parent.kind === 199; + if (isSourceOfAssignmentExpressionStatement) { + return parent_3.parent.jsDocComment; + } + var isPropertyAssignmentExpression = parent_3 && parent_3.kind === 249; + if (isPropertyAssignmentExpression) { + return parent_3.jsDocComment; + } + } + return undefined; + } function getJSDocTypeTag(node) { - return getJSDocTag(node, 269); + return getJSDocTag(node, 273, false); } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 268); + return getJSDocTag(node, 272, true); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 270); + return getJSDocTag(node, 274, false); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getCorrespondingJSDocParameterTag(parameter) { if (parameter.name && parameter.name.kind === 69) { var parameterName = parameter.name.text; - var docComment = parameter.parent.jsDocComment; - if (docComment) { - return ts.forEach(docComment.tags, function (t) { - if (t.kind === 267) { - var parameterTag = t; - var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_7.text === parameterName) { - return t; + var jsDocComment = getJSDocComment(parameter.parent, true); + if (jsDocComment) { + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === 271) { + var parameterTag = tag; + var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_6.text === parameterName) { + return parameterTag; } } - }); + } } } + return undefined; } ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; function hasRestParameter(s) { @@ -4548,13 +5134,13 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { if (node) { - if (node.parserContextFlags & 32) { - if (node.type && node.type.kind === 262) { + if (node.flags & 134217728) { + if (node.type && node.type.kind === 266) { return true; } var paramTag = getCorrespondingJSDocParameterTag(node); if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 262; + return paramTag.typeExpression.type.kind === 266; } } return node.dotDotDotToken !== undefined; @@ -4575,7 +5161,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 162 || node.kind === 161); + return !!node && (node.kind === 166 || node.kind === 165); } ts.isBindingPattern = isBindingPattern; function isNodeDescendentOf(node, ancestor) { @@ -4589,7 +5175,7 @@ var ts; ts.isNodeDescendentOf = isNodeDescendentOf; function isInAmbientContext(node) { while (node) { - if (node.flags & (4 | 4096)) { + if (node.flags & 2 || (node.kind === 252 && node.isDeclarationFile)) { return true; } node = node.parent; @@ -4599,34 +5185,34 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 174: - case 163: - case 214: - case 186: - case 144: - case 217: - case 247: - case 230: - case 213: - case 173: - case 145: - case 223: + case 178: + case 167: + case 218: + case 190: + case 146: case 221: - case 226: - case 215: + case 251: + case 234: + case 217: + case 177: + case 147: + case 227: + case 225: + case 230: + case 219: + case 145: + case 144: + case 222: + case 228: + case 140: + case 249: case 143: case 142: - case 218: - case 224: - case 138: - case 245: - case 141: - case 140: - case 146: - case 246: - case 216: - case 137: - case 211: + case 148: + case 250: + case 220: + case 139: + case 215: return true; } return false; @@ -4634,25 +5220,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 203: - case 202: - case 210: - case 197: - case 195: - case 194: - case 200: + case 207: + case 206: + case 214: case 201: case 199: - case 196: - case 207: - case 204: - case 206: - case 208: - case 209: - case 193: case 198: + case 204: case 205: - case 227: + case 203: + case 200: + case 211: + case 208: + case 210: + case 212: + case 213: + case 197: + case 202: + case 209: + case 231: return true; default: return false; @@ -4661,13 +5247,13 @@ var ts; ts.isStatement = isStatement; function isClassElement(n) { switch (n.kind) { - case 144: - case 141: + case 146: case 143: case 145: - case 146: - case 142: - case 149: + case 147: + case 148: + case 144: + case 151: return true; default: return false; @@ -4679,7 +5265,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 226 || parent.kind === 230) { + if (parent.kind === 230 || parent.kind === 234) { if (parent.propertyName) { return true; } @@ -4693,40 +5279,40 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 141: - case 140: case 143: case 142: case 145: - case 146: - case 247: - case 245: - case 166: + case 144: + case 147: + case 148: + case 251: + case 249: + case 170: return parent.name === node; - case 135: + case 137: if (parent.right === node) { - while (parent.kind === 135) { + while (parent.kind === 137) { parent = parent.parent; } - return parent.kind === 154; + return parent.kind === 156; } return false; - case 163: - case 226: - return parent.propertyName === node; + case 167: case 230: + return parent.propertyName === node; + case 234: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 221 || - node.kind === 223 && !!node.name || - node.kind === 224 || - node.kind === 226 || + return node.kind === 225 || + node.kind === 227 && !!node.name || + node.kind === 228 || node.kind === 230 || - node.kind === 227 && node.expression.kind === 69; + node.kind === 234 || + node.kind === 231 && node.expression.kind === 69; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -4776,8 +5362,8 @@ var ts; function getFileReferenceFromReferencePath(comment, commentRange) { var simpleReferenceRegEx = /^\/\/\/\s*/gim; - if (simpleReferenceRegEx.exec(comment)) { - if (isNoDefaultLibRegEx.exec(comment)) { + if (simpleReferenceRegEx.test(comment)) { + if (isNoDefaultLibRegEx.test(comment)) { return { isNoDefaultLib: true }; @@ -4808,7 +5394,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 70 <= token && token <= 134; + return 70 <= token && token <= 136; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -4819,12 +5405,20 @@ var ts; return isFunctionLike(node) && (node.flags & 256) !== 0 && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; + function isStringOrNumericLiteral(kind) { + return kind === 9 || kind === 8; + } + ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && - declaration.name.kind === 136 && - !isWellKnownSymbolSyntactically(declaration.name.expression); + return declaration.name && isDynamicName(declaration.name); } ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 138 && + !isStringOrNumericLiteral(name.expression.kind) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; function isWellKnownSymbolSyntactically(node) { return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); } @@ -4833,7 +5427,7 @@ var ts; if (name.kind === 69 || name.kind === 9 || name.kind === 8) { return name.text; } - if (name.kind === 136) { + if (name.kind === 138) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -4851,7 +5445,7 @@ var ts; return node.kind === 69 && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; - function isModifier(token) { + function isModifierKind(token) { switch (token) { case 115: case 118: @@ -4862,44 +5456,62 @@ var ts; case 112: case 110: case 111: + case 127: case 113: return true; } return false; } - ts.isModifier = isModifier; + ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 138; + return root.kind === 140; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 163) { + while (node.kind === 167) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 218 || n.kind === 248; + return isFunctionLike(n) || n.kind === 222 || n.kind === 252; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneEntityName(node) { - if (node.kind === 69) { - var clone_1 = createSynthesizedNode(69); - clone_1.text = node.text; - return clone_1; + function cloneNode(node, location, flags, parent) { + var clone = location !== undefined + ? ts.createNode(node.kind, location.pos, location.end) + : createSynthesizedNode(node.kind); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; } - else { - var clone_2 = createSynthesizedNode(135); - clone_2.left = cloneEntityName(node.left); - clone_2.left.parent = clone_2; - clone_2.right = cloneEntityName(node.right); - clone_2.right.parent = clone_2; - return clone_2; + if (flags !== undefined) { + clone.flags = flags; } + if (parent !== undefined) { + clone.parent = parent; + } + return clone; + } + ts.cloneNode = cloneNode; + function cloneEntityName(node, parent) { + var clone = cloneNode(node, node, node.flags, parent); + if (isQualifiedName(clone)) { + var left = clone.left, right = clone.right; + clone.left = cloneEntityName(left, clone); + clone.right = cloneNode(right, right, right.flags, parent); + } + return clone; } ts.cloneEntityName = cloneEntityName; + function isQualifiedName(node) { + return node.kind === 137; + } + ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { return node.pos === -1; } @@ -5045,11 +5657,11 @@ var ts; } ts.getIndentSize = getIndentSize; function createTextWriter(newLine) { - var output = ""; - var indent = 0; - var lineStart = true; - var lineCount = 0; - var linePos = 0; + var output; + var indent; + var lineStart; + var lineCount; + var linePos; function write(s) { if (s && s.length) { if (lineStart) { @@ -5059,6 +5671,13 @@ var ts; output += s; } } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } function rawWrite(s) { if (s !== undefined) { if (lineStart) { @@ -5085,25 +5704,35 @@ var ts; lineStart = true; } } - function writeTextOfNode(sourceFile, node) { - write(getSourceTextOfNodeFromSourceFile(sourceFile, node)); + function writeTextOfNode(text, node) { + write(getTextOfNodeFromSourceText(text, node)); } + reset(); return { write: write, rawWrite: rawWrite, writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, - increaseIndent: function () { return indent++; }, - decreaseIndent: function () { return indent--; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, getLine: function () { return lineCount + 1; }, getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, - getText: function () { return output; } + getText: function () { return output; }, + reset: reset }; } ts.createTextWriter = createTextWriter; + function getExternalModuleNameFromPath(host, fileName) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); + return ts.removeFileExtension(relativePath); + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; function getOwnEmitOutputFilePath(sourceFile, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; @@ -5116,6 +5745,72 @@ var ts; return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + onBundledEmit(host); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + if (!isDeclarationFile(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + var extension = ".js"; + if (options.jsx === 1) { + if (isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + extension = ".jsx"; + } + } + else if (sourceFile.languageVariant === 1) { + extension = ".jsx"; + } + } + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined + }; + action(emitFileNames, [sourceFile], false); + } + function onBundledEmit(host) { + var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + (!isExternalModule(sourceFile) || + (getEmitModuleKind(options) && isExternalModule(sourceFile))); }); + if (bundledSources.length) { + var jsFilePath = options.outFile || options.out; + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options) + }; + action(emitFileNames, bundledSources, true); + } + } + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getDeclarationEmitFilePath(jsFilePath, options) { + return options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + } + } + ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); @@ -5124,7 +5819,7 @@ var ts; ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }); } ts.writeFile = writeFile; @@ -5132,9 +5827,13 @@ var ts; return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 144 && nodeIsPresent(member.body)) { + if (member.kind === 146 && nodeIsPresent(member.body)) { return member; } }); @@ -5144,16 +5843,6 @@ var ts; return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; - function shouldEmitToOwnFile(sourceFile, compilerOptions) { - if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) { - return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); - } - return false; - } - return false; - } - ts.shouldEmitToOwnFile = shouldEmitToOwnFile; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -5161,10 +5850,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 145) { + if (accessor.kind === 147) { getAccessor = accessor; } - else if (accessor.kind === 146) { + else if (accessor.kind === 148) { setAccessor = accessor; } else { @@ -5173,8 +5862,8 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 145 || member.kind === 146) - && (member.flags & 64) === (accessor.flags & 64)) { + if ((member.kind === 147 || member.kind === 148) + && (member.flags & 32) === (accessor.flags & 32)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -5184,10 +5873,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 145 && !getAccessor) { + if (member.kind === 147 && !getAccessor) { getAccessor = member; } - if (member.kind === 146 && !setAccessor) { + if (member.kind === 148 && !setAccessor) { setAccessor = member; } } @@ -5202,21 +5891,21 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) { + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && - getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) { + getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { writer.writeLine(); } } ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; - function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) { + function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) { var emitLeadingSpace = !trailingSeparator; ts.forEach(comments, function (comment) { if (emitLeadingSpace) { writer.write(" "); emitLeadingSpace = false; } - writeComment(currentSourceFile, writer, comment, newLine); + writeComment(text, lineMap, writer, comment, newLine); if (comment.hasTrailingNewLine) { writer.writeLine(); } @@ -5229,25 +5918,25 @@ var ts; }); } ts.emitComments = emitComments; - function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) { + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { var leadingComments; var currentDetachedCommentInfo; if (removeComments) { if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment); + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); } } else { - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + leadingComments = ts.getLeadingCommentRanges(text, node.pos); } if (leadingComments) { var detachedComments = []; - var lastComment; + var lastComment = void 0; for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { var comment = leadingComments_1[_i]; if (lastComment) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); if (commentLine >= lastCommentLine + 2) { break; } @@ -5256,37 +5945,37 @@ var ts; lastComment = comment; } if (detachedComments.length) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); - var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } } return currentDetachedCommentInfo; function isPinnedComment(comment) { - return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 33; + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 33; } } ts.emitDetachedComments = emitDetachedComments; - function writeCommentRange(currentSourceFile, writer, comment, newLine) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42) { - var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos); - var lineCount = ts.getLineStarts(currentSourceFile).length; - var firstCommentLineIndent; + function writeCommentRange(text, lineMap, writer, comment, newLine) { + if (text.charCodeAt(comment.pos + 1) === 42) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { var nextLineStart = (currentLine + 1) === lineCount - ? currentSourceFile.text.length + 1 - : getStartPositionOfLine(currentLine + 1, currentSourceFile); + ? text.length + 1 + : lineMap[currentLine + 1]; if (pos !== comment.pos) { if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos); + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos); } var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); - var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); if (spacesToEmit > 0) { var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); @@ -5300,52 +5989,53 @@ var ts; writer.rawWrite(""); } } - writeTrimmedCurrentLine(pos, nextLineStart); + writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart); pos = nextLineStart; } } else { - writer.write(currentSourceFile.text.substring(comment.pos, comment.end)); - } - function writeTrimmedCurrentLine(pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); - var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ""); - if (currentLineText) { - writer.write(currentLineText); - if (end !== comment.end) { - writer.writeLine(); - } - } - else { - writer.writeLiteral(newLine); - } - } - function calculateIndent(pos, end) { - var currentLineIndent = 0; - for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) { - if (currentSourceFile.text.charCodeAt(pos) === 9) { - currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); - } - else { - currentLineIndent++; - } - } - return currentLineIndent; + writer.write(text.substring(comment.pos, comment.end)); } } ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) { + var end = Math.min(comment.end, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + writer.write(currentLineText); + if (end !== comment.end) { + writer.writeLine(); + } + } + else { + writer.writeLiteral(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpace(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9) { + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + currentLineIndent++; + } + } + return currentLineIndent; + } function modifierToFlag(token) { switch (token) { - case 113: return 64; - case 112: return 8; - case 111: return 32; - case 110: return 16; + case 113: return 32; + case 112: return 4; + case 111: return 16; + case 110: return 8; case 115: return 128; - case 82: return 2; - case 122: return 4; - case 74: return 16384; + case 82: return 1; + case 122: return 2; + case 74: return 2048; case 77: return 512; case 118: return 256; + case 127: return 64; } return 0; } @@ -5353,24 +6043,24 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 166: - case 167: - case 169: - case 168: - case 233: - case 234: case 170: - case 164: - case 172: - case 165: - case 186: + case 171: case 173: + case 172: + case 237: + case 238: + case 174: + case 168: + case 176: + case 169: + case 190: + case 177: case 69: case 10: case 8: case 9: case 11: - case 183: + case 187: case 84: case 93: case 97: @@ -5387,7 +6077,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 188 && + return node.kind === 192 && node.parent.token === 83 && isClassLike(node.parent.parent); } @@ -5408,16 +6098,16 @@ var ts; } } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 135 && node.parent.right === node) || - (node.parent.kind === 166 && node.parent.name === node); + return (node.parent.kind === 137 && node.parent.right === node) || + (node.parent.kind === 170 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 165) { + if (kind === 169) { return expression.properties.length === 0; } - if (kind === 164) { + if (kind === 168) { return expression.elements.length === 0; } return false; @@ -5427,14 +6117,10 @@ var ts; return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function isJavaScript(fileName) { - return ts.fileExtensionIs(fileName, ".js"); + function hasJavaScriptFileExtension(fileName) { + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.isJavaScript = isJavaScript; - function isTsx(fileName) { - return ts.fileExtensionIs(fileName, ".tsx"); - } - ts.isTsx = isTsx; + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -5464,6 +6150,39 @@ var ts; } return output; } + ts.stringify = typeof JSON !== "undefined" && JSON.stringify + ? JSON.stringify + : stringifyFallback; + function stringifyFallback(value) { + return value === undefined ? undefined : stringifyValue(value); + } + function stringifyValue(value) { + return typeof value === "string" ? "\"" + escapeString(value) + "\"" + : typeof value === "number" ? isFinite(value) ? String(value) : "null" + : typeof value === "boolean" ? value ? "true" : "false" + : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) + : "null"; + } + function cycleCheck(cb, value) { + ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); + value.__cycle = true; + var result = cb(value); + delete value.__cycle; + return result; + } + function stringifyArray(value) { + return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; + } + function stringifyElement(memo, value) { + return (memo ? memo + "," : memo) + stringifyValue(value); + } + function stringifyObject(value) { + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + } + function stringifyProperty(memo, value, key) { + return value === undefined || typeof value === "function" || key === "__cycle" ? memo + : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); + } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function convertToBase64(input) { var result = ""; @@ -5632,26 +6351,32 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 137) { + if (d && d.kind === 139) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 215) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 219) { return current; } } } } ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return node.flags & 28 && node.parent.kind === 146 && ts.isClassLike(node.parent.parent); + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; })(ts || (ts = {})); var ts; (function (ts) { - var nodeConstructors = new Array(272); ts.parseTime = 0; - function getNodeConstructor(kind) { - return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); - } - ts.getNodeConstructor = getNodeConstructor; + var NodeConstructor; + var SourceFileConstructor; function createNode(kind, pos, end) { - return new (getNodeConstructor(kind))(pos, end); + if (kind === 252) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } } ts.createNode = createNode; function visitNode(cbNode, node) { @@ -5682,26 +6407,26 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 135: + case 137: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 137: + case 139: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 246: + case 250: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 138: - case 141: case 140: - case 245: - case 211: - case 163: + case 143: + case 142: + case 249: + case 215: + case 167: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -5710,24 +6435,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 152: - case 153: - case 147: - case 148: + case 154: + case 155: case 149: + case 150: + case 151: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 143: - case 142: - case 144: case 145: + case 144: case 146: - case 173: - case 213: - case 174: + case 147: + case 148: + case 177: + case 217: + case 178: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -5738,302 +6463,318 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 151: + case 153: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 150: + case 152: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 154: - return visitNode(cbNode, node.exprName); - case 155: - return visitNodes(cbNodes, node.members); case 156: - return visitNode(cbNode, node.elementType); + return visitNode(cbNode, node.exprName); case 157: - return visitNodes(cbNodes, node.elementTypes); + return visitNodes(cbNodes, node.members); case 158: + return visitNode(cbNode, node.elementType); case 159: - return visitNodes(cbNodes, node.types); + return visitNodes(cbNodes, node.elementTypes); case 160: - return visitNode(cbNode, node.type); case 161: + return visitNodes(cbNodes, node.types); case 162: - return visitNodes(cbNodes, node.elements); - case 164: - return visitNodes(cbNodes, node.elements); + return visitNode(cbNode, node.type); case 165: - return visitNodes(cbNodes, node.properties); case 166: + return visitNodes(cbNodes, node.elements); + case 168: + return visitNodes(cbNodes, node.elements); + case 169: + return visitNodes(cbNodes, node.properties); + case 170: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 167: + case 171: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 168: - case 169: + case 172: + case 173: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 170: + case 174: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 171: + case 175: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 172: - return visitNode(cbNode, node.expression); - case 175: - return visitNode(cbNode, node.expression); case 176: return visitNode(cbNode, node.expression); - case 177: - return visitNode(cbNode, node.expression); case 179: - return visitNode(cbNode, node.operand); - case 184: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); - case 178: return visitNode(cbNode, node.expression); case 180: - return visitNode(cbNode, node.operand); + return visitNode(cbNode, node.expression); case 181: + return visitNode(cbNode, node.expression); + case 183: + return visitNode(cbNode, node.operand); + case 188: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 182: + return visitNode(cbNode, node.expression); + case 184: + return visitNode(cbNode, node.operand); + case 185: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 189: + case 193: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 182: + case 186: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 185: + case 189: return visitNode(cbNode, node.expression); - case 192: - case 219: + case 196: + case 223: return visitNodes(cbNodes, node.statements); - case 248: + case 252: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 193: + case 197: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 212: + case 216: return visitNodes(cbNodes, node.declarations); - case 195: + case 199: return visitNode(cbNode, node.expression); - case 196: + case 200: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 197: + case 201: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 198: + case 202: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 199: + case 203: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 200: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 201: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 202: - case 203: - return visitNode(cbNode, node.label); case 204: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); case 205: - return visitNode(cbNode, node.expression) || + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); case 206: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 220: - return visitNodes(cbNodes, node.clauses); - case 241: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 242: - return visitNodes(cbNodes, node.statements); case 207: - return visitNode(cbNode, node.label) || - visitNode(cbNode, node.statement); + return visitNode(cbNode, node.label); case 208: return visitNode(cbNode, node.expression); case 209: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 210: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 224: + return visitNodes(cbNodes, node.clauses); + case 245: + return visitNode(cbNode, node.expression) || + visitNodes(cbNodes, node.statements); + case 246: + return visitNodes(cbNodes, node.statements); + case 211: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 212: + return visitNode(cbNode, node.expression); + case 213: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 244: + case 248: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 139: + case 141: return visitNode(cbNode, node.expression); - case 214: - case 186: + case 218: + case 190: 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 215: + case 219: 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 216: + case 220: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 217: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.members); - case 247: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 218: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); case 221: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); + visitNodes(cbNodes, node.members); + case 251: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); case 222: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 225: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 226: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 223: + case 227: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 224: - return visitNode(cbNode, node.name); - case 225: - case 229: - return visitNodes(cbNodes, node.elements); case 228: + return visitNode(cbNode, node.name); + case 229: + case 233: + return visitNodes(cbNodes, node.elements); + case 232: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 226: case 230: + case 234: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 227: + case 231: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 183: + case 187: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 190: + case 194: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 136: + case 138: return visitNode(cbNode, node.expression); - case 243: + case 247: return visitNodes(cbNodes, node.types); - case 188: + case 192: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 232: + case 236: return visitNode(cbNode, node.expression); - case 231: + case 235: return visitNodes(cbNodes, node.decorators); - case 233: + case 237: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 234: - case 235: + case 238: + case 239: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 238: + case 242: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 239: + case 243: return visitNode(cbNode, node.expression); - case 240: + case 244: return visitNode(cbNode, node.expression); - case 237: + case 241: return visitNode(cbNode, node.tagName); - case 249: - return visitNode(cbNode, node.type); case 253: - return visitNodes(cbNodes, node.types); - case 254: - return visitNodes(cbNodes, node.types); - case 252: - return visitNode(cbNode, node.elementType); - case 256: - return visitNode(cbNode, node.type); - case 255: return visitNode(cbNode, node.type); case 257: - return visitNodes(cbNodes, node.members); - case 259: - return visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeArguments); + return visitNodes(cbNodes, node.types); + case 258: + return visitNodes(cbNodes, node.types); + case 256: + return visitNode(cbNode, node.elementType); case 260: return visitNode(cbNode, node.type); + case 259: + return visitNode(cbNode, node.type); case 261: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 262: - return visitNode(cbNode, node.type); + return visitNodes(cbNodes, node.members); case 263: - return visitNode(cbNode, node.type); + return visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeArguments); case 264: return visitNode(cbNode, node.type); - case 258: + case 265: + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 266: + return visitNode(cbNode, node.type); + case 267: + return visitNode(cbNode, node.type); + case 268: + return visitNode(cbNode, node.type); + case 262: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 265: + case 269: return visitNodes(cbNodes, node.tags); - case 267: + case 271: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 268: + case 272: return visitNode(cbNode, node.typeExpression); - case 269: + case 273: return visitNode(cbNode, node.typeExpression); - case 270: + case 274: return visitNodes(cbNodes, node.typeParameters); } } ts.forEachChild = forEachChild; - function createSourceFile(fileName, sourceText, languageVersion, setParentNodes) { + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } var start = new Date().getTime(); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); ts.parseTime += new Date().getTime() - start; return result; } ts.createSourceFile = createSourceFile; + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js": + return 1; + case ".jsx": + return 2; + case ".ts": + return 3; + case ".tsx": + return 4; + default: + return 3; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); } @@ -6049,7 +6790,9 @@ var ts; var Parser; (function (Parser) { var scanner = ts.createScanner(2, true); - var disallowInAndDecoratorContext = 1 | 4; + var disallowInAndDecoratorContext = 4194304 | 16777216; + var NodeConstructor; + var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; @@ -6061,14 +6804,20 @@ var ts; var parsingContext; var contextFlags; var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) { - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); - var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes, scriptKind) { + scriptKind = scriptKind ? scriptKind : getScriptKindFromFileName(fileName); + initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); return result; } Parser.parseSourceFile = parseSourceFile; - function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) { + function getLanguageVariant(scriptKind) { + return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 ? 1 : 0; + } + function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; @@ -6076,12 +6825,12 @@ var ts; identifiers = {}; identifierCount = 0; nodeCount = 0; - contextFlags = ts.isJavaScript(fileName) ? 32 : 0; + contextFlags = scriptKind === 1 || scriptKind === 2 ? 134217728 : 0; parseErrorBeforeNextFinishedNode = false; scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(ts.isTsx(fileName) ? 1 : 0); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); } function clearState() { scanner.setText(""); @@ -6092,8 +6841,9 @@ var ts; syntaxCursor = undefined; sourceText = undefined; } - function parseSourceFileWorker(fileName, languageVersion, setParentNodes) { - sourceFile = createSourceFile(fileName, languageVersion); + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + sourceFile.flags = contextFlags; token = nextToken(); processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); @@ -6107,35 +6857,22 @@ var ts; if (setParentNodes) { fixupParentReferences(sourceFile); } - if (ts.isJavaScript(fileName)) { - addJSDocComments(); - } return sourceFile; } - function addJSDocComments() { - forEachChild(sourceFile, visit); - return; - function visit(node) { - switch (node.kind) { - case 193: - case 213: - case 138: - addJSDocComment(node); - } - forEachChild(node, visit); - } - } function addJSDocComment(node) { - var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); - if (comments) { - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var comment = comments_1[_i]; - var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDocComment) { - node.jsDocComment = jsDocComment; + if (contextFlags & 134217728) { + var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); + if (comments) { + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (jsDocComment) { + node.jsDocComment = jsDocComment; + } } } } + return node; } function fixupParentReferences(sourceFile) { var parent = sourceFile; @@ -6152,16 +6889,16 @@ var ts; } } Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion) { - var sourceFile = createNode(248, 0); - sourceFile.pos = 0; - sourceFile.end = sourceText.length; + function createSourceFile(fileName, languageVersion, scriptKind) { + var sourceFile = new SourceFileConstructor(252, 0, sourceText.length); + nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 : 0; - sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 : 0; + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.scriptKind = scriptKind; return sourceFile; } function setContextFlag(val, flag) { @@ -6173,16 +6910,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 1); + setContextFlag(val, 4194304); } function setYieldContext(val) { - setContextFlag(val, 2); + setContextFlag(val, 8388608); } function setDecoratorContext(val) { - setContextFlag(val, 4); + setContextFlag(val, 16777216); } function setAwaitContext(val) { - setContextFlag(val, 8); + setContextFlag(val, 33554432); } function doOutsideOfContext(context, func) { var contextFlagsToClear = context & contextFlags; @@ -6205,46 +6942,40 @@ var ts; return func(); } function allowInAnd(func) { - return doOutsideOfContext(1, func); + return doOutsideOfContext(4194304, func); } function disallowInAnd(func) { - return doInsideOfContext(1, func); + return doInsideOfContext(4194304, func); } function doInYieldContext(func) { - return doInsideOfContext(2, func); - } - function doOutsideOfYieldContext(func) { - return doOutsideOfContext(2, func); + return doInsideOfContext(8388608, func); } function doInDecoratorContext(func) { - return doInsideOfContext(4, func); + return doInsideOfContext(16777216, func); } function doInAwaitContext(func) { - return doInsideOfContext(8, func); + return doInsideOfContext(33554432, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(8, func); + return doOutsideOfContext(33554432, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(2 | 8, func); - } - function doOutsideOfYieldAndAwaitContext(func) { - return doOutsideOfContext(2 | 8, func); + return doInsideOfContext(8388608 | 33554432, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(2); + return inContext(8388608); } function inDisallowInContext() { - return inContext(1); + return inContext(4194304); } function inDecoratorContext() { - return inContext(4); + return inContext(16777216); } function inAwaitContext() { - return inContext(8); + return inContext(33554432); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -6271,9 +7002,6 @@ var ts; function nextToken() { return token = scanner.scan(); } - function getTokenPos(pos) { - return ts.skipTrivia(sourceText, pos); - } function reScanGreaterToken() { return token = scanner.reScanGreaterToken(); } @@ -6383,16 +7111,16 @@ var ts; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return new (nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)))(pos, pos); + return new NodeConstructor(kind, pos, pos); } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; if (contextFlags) { - node.parserContextFlags = contextFlags; + node.flags |= contextFlags; } if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.parserContextFlags |= 16; + node.flags |= 67108864; } return node; } @@ -6454,7 +7182,7 @@ var ts; return token === 9 || token === 8 || ts.tokenIsIdentifierOrKeyword(token); } function parseComputedPropertyName() { - var node = createNode(136); + var node = createNode(138); parseExpected(19); node.expression = allowInAnd(parseExpression); parseExpected(20); @@ -6463,6 +7191,13 @@ var ts; function parseContextualModifier(t) { return token === t && tryParse(nextTokenCanFollowModifier); } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } function nextTokenCanFollowModifier() { if (token === 74) { return nextToken() === 81; @@ -6481,14 +7216,10 @@ var ts; nextToken(); return canFollowModifier(); } - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); + return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifier(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { return token === 19 @@ -6513,7 +7244,7 @@ var ts; case 2: return token === 71 || token === 77; case 4: - return isStartOfTypeMember(); + return lookAhead(isTypeMemberStart); case 5: return lookAhead(isClassMemberStart) || (token === 23 && !inErrorRecovery); case 6: @@ -6521,7 +7252,7 @@ var ts; case 12: return token === 19 || token === 37 || isLiteralPropertyName(); case 9: - return isLiteralPropertyName(); + return token === 19 || isLiteralPropertyName(); case 7: if (token === 15) { return lookAhead(isValidHeritageClauseObjectLiteral); @@ -6703,7 +7434,7 @@ var ts; if (ts.containsParseError(node)) { return undefined; } - var nodeContextFlags = node.parserContextFlags & 31; + var nodeContextFlags = node.flags & 62914560; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -6750,14 +7481,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 144: - case 149: - case 145: case 146: - case 141: - case 191: - return true; + case 151: + case 147: + case 148: case 143: + case 195: + return true; + case 145: var methodDeclaration = node; var nameIsConstructor = methodDeclaration.name.kind === 69 && methodDeclaration.name.originalKeywordKind === 121; @@ -6769,8 +7500,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 241: - case 242: + case 245: + case 246: return true; } } @@ -6779,65 +7510,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 213: - case 193: - case 192: + case 217: + case 197: case 196: - case 195: + case 200: + case 199: + case 212: case 208: - case 204: + case 210: + case 207: case 206: + case 204: + case 205: case 203: case 202: - case 200: - case 201: - case 199: - case 198: - case 205: - case 194: case 209: - case 207: - case 197: - case 210: - case 222: - case 221: - case 228: - case 227: - case 218: + case 198: + case 213: + case 211: + case 201: case 214: - case 215: - case 217: - case 216: + case 226: + case 225: + case 232: + case 231: + case 222: + case 218: + case 219: + case 221: + case 220: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 247; + return node.kind === 251; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 148: + case 150: + case 144: + case 151: case 142: case 149: - case 140: - case 147: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 211) { + if (node.kind !== 215) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 138) { + if (node.kind !== 140) { return false; } var parameter = node; @@ -6882,7 +7613,7 @@ var ts; } } ; - function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimeter) { + function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; @@ -6900,7 +7631,7 @@ var ts; break; } parseExpected(24); - if (considerSemicolonAsDelimeter && token === 23 && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token === 23 && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -6937,7 +7668,7 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); while (parseOptional(21)) { - var node = createNode(135, entity.pos); + var node = createNode(137, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -6954,8 +7685,8 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(183); - template.head = parseLiteralNode(); + var template = createNode(187); + template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); var templateSpans = []; templateSpans.pos = getNodePos(); @@ -6967,12 +7698,12 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(190); + var span = createNode(194); span.expression = allowInAnd(parseExpression); var literal; if (token === 16) { reScanTemplateToken(); - literal = parseLiteralNode(); + literal = parseTemplateLiteralFragment(); } else { literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); @@ -6980,8 +7711,17 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(164, true); + } function parseLiteralNode(internName) { - var node = createNode(token); + return parseLiteralLikeNode(token, internName); + } + function parseTemplateLiteralFragment() { + return parseLiteralLikeNode(token, false); + } + function parseLiteralLikeNode(kind, internName) { + var node = createNode(kind); var text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -6996,34 +7736,39 @@ var ts; if (node.kind === 8 && sourceText.charCodeAt(tokenPos) === 48 && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - node.flags |= 32768; + node.isOctalLiteral = true; } return node; } - function parseTypeReferenceOrTypePredicate() { + function parseTypeReference() { var typeName = parseEntityName(false, ts.Diagnostics.Type_expected); - if (typeName.kind === 69 && token === 124 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var node_1 = createNode(150, typeName.pos); - node_1.parameterName = typeName; - node_1.type = parseType(); - return finishNode(node_1); - } - var node = createNode(151, typeName.pos); + var node = createNode(153, typeName.pos); node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); } return finishNode(node); } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(152, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(163); + nextToken(); + return finishNode(node); + } function parseTypeQuery() { - var node = createNode(154); + var node = createNode(156); parseExpected(101); node.exprName = parseEntityName(true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(137); + var node = createNode(139); node.name = parseIdentifier(); if (parseOptional(83)) { if (isStartOfType() || !isStartOfExpression()) { @@ -7042,14 +7787,12 @@ var ts; } function parseParameterType() { if (parseOptional(54)) { - return token === 9 - ? parseLiteralNode(true) - : parseType(); + return parseType(); } return undefined; } function isStartOfParameter() { - return token === 22 || isIdentifierOrPattern() || ts.isModifier(token) || token === 55; + return token === 22 || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55; } function setModifiers(node, modifiers) { if (modifiers) { @@ -7058,18 +7801,18 @@ var ts; } } function parseParameter() { - var node = createNode(138); + var node = createNode(140); node.decorators = parseDecorators(); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifier(token)) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { nextToken(); } node.questionToken = parseOptionalToken(53); node.type = parseParameterType(); node.initializer = parseBindingElementInitializer(true); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseBindingElementInitializer(inParameter) { return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); @@ -7083,10 +7826,10 @@ var ts; signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); if (returnTokenRequired) { parseExpected(returnToken); - signature.type = parseType(); + signature.type = parseTypeOrTypePredicate(); } else if (parseOptional(returnToken)) { - signature.type = parseType(); + signature.type = parseTypeOrTypePredicate(); } } function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { @@ -7113,7 +7856,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 148) { + if (kind === 150) { parseExpected(92); } fillSignature(54, false, false, false, node); @@ -7131,7 +7874,7 @@ var ts; if (token === 22 || token === 20) { return true; } - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -7153,7 +7896,7 @@ var ts; return token === 54 || token === 24 || token === 20; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(149, fullStart); + var node = createNode(151, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.parameters = parseBracketedList(16, parseParameter, 19, 20); @@ -7161,12 +7904,12 @@ var ts; parseTypeMemberSemicolon(); return finishNode(node); } - function parsePropertyOrMethodSignature() { - var fullStart = scanner.getStartPos(); + function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53); if (token === 17 || token === 25) { - var method = createNode(142, fullStart); + var method = createNode(144, fullStart); + setModifiers(method, modifiers); method.name = name; method.questionToken = questionToken; fillSignature(54, false, false, false, method); @@ -7174,86 +7917,63 @@ var ts; return finishNode(method); } else { - var property = createNode(140, fullStart); + var property = createNode(142, fullStart); + setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); + if (token === 56) { + property.initializer = parseNonParameterInitializer(); + } parseTypeMemberSemicolon(); return finishNode(property); } } - function isStartOfTypeMember() { - switch (token) { - case 17: - case 25: - case 19: - return true; - default: - if (ts.isModifier(token)) { - var result = lookAhead(isStartOfIndexSignatureDeclaration); - if (result) { - return result; - } - } - return isLiteralPropertyName() && lookAhead(isTypeMemberWithLiteralPropertyName); + function isTypeMemberStart() { + var idToken; + if (token === 17 || token === 25) { + return true; } - } - function isStartOfIndexSignatureDeclaration() { - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { + idToken = token; nextToken(); } - return isIndexSignature(); - } - function isTypeMemberWithLiteralPropertyName() { - nextToken(); - return token === 17 || - token === 25 || - token === 53 || - token === 54 || - canParseSemicolon(); + if (token === 19) { + return true; + } + if (isLiteralPropertyName()) { + idToken = token; + nextToken(); + } + if (idToken) { + return token === 17 || + token === 25 || + token === 53 || + token === 54 || + canParseSemicolon(); + } + return false; } function parseTypeMember() { - switch (token) { - case 17: - case 25: - return parseSignatureMember(147); - case 19: - return isIndexSignature() - ? parseIndexSignatureDeclaration(scanner.getStartPos(), undefined, undefined) - : parsePropertyOrMethodSignature(); - case 92: - if (lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(148); - } - case 9: - case 8: - return parsePropertyOrMethodSignature(); - default: - if (ts.isModifier(token)) { - var result = tryParse(parseIndexSignatureWithModifiers); - if (result) { - return result; - } - } - if (ts.tokenIsIdentifierOrKeyword(token)) { - return parsePropertyOrMethodSignature(); - } + if (token === 17 || token === 25) { + return parseSignatureMember(149); } - } - function parseIndexSignatureWithModifiers() { - var fullStart = scanner.getStartPos(); - var decorators = parseDecorators(); + if (token === 92 && lookAhead(isStartOfConstructSignature)) { + return parseSignatureMember(150); + } + var fullStart = getNodePos(); var modifiers = parseModifiers(); - return isIndexSignature() - ? parseIndexSignatureDeclaration(fullStart, decorators, modifiers) - : undefined; + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); + } + return parsePropertyOrMethodSignature(fullStart, modifiers); } function isStartOfConstructSignature() { nextToken(); return token === 17 || token === 25; } function parseTypeLiteral() { - var node = createNode(155); + var node = createNode(157); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -7269,12 +7989,12 @@ var ts; return members; } function parseTupleType() { - var node = createNode(157); + var node = createNode(159); node.elementTypes = parseBracketedList(19, parseType, 19, 20); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(160); + var node = createNode(162); parseExpected(17); node.type = parseType(); parseExpected(18); @@ -7282,7 +8002,7 @@ var ts; } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 153) { + if (kind === 155) { parseExpected(92); } fillSignature(34, false, false, false, node); @@ -7295,15 +8015,25 @@ var ts; function parseNonArrayType() { switch (token) { case 117: - case 130: - case 128: - case 120: case 131: + case 129: + case 120: + case 132: var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReferenceOrTypePredicate(); + return node || parseTypeReference(); + case 9: + return parseStringLiteralTypeNode(); case 103: - case 97: return parseTokenNode(); + case 97: { + var thisKeyword = parseThisTypeNode(); + if (token === 124 && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } case 101: return parseTypeQuery(); case 15: @@ -7313,16 +8043,16 @@ var ts; case 17: return parseParenthesizedType(); default: - return parseTypeReferenceOrTypePredicate(); + return parseTypeReference(); } } function isStartOfType() { switch (token) { case 117: - case 130: - case 128: - case 120: case 131: + case 129: + case 120: + case 132: case 103: case 97: case 101: @@ -7330,6 +8060,7 @@ var ts; case 19: case 25: case 92: + case 9: return true; case 17: return lookAhead(isStartOfParenthesizedOrFunctionType); @@ -7345,7 +8076,7 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(19)) { parseExpected(20); - var node = createNode(156, type.pos); + var node = createNode(158, type.pos); node.elementType = type; type = finishNode(node); } @@ -7367,10 +8098,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(159, parseArrayTypeOrHigher, 46); + return parseUnionOrIntersectionType(161, parseArrayTypeOrHigher, 46); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(158, parseIntersectionTypeOrHigher, 47); + return parseUnionOrIntersectionType(160, parseIntersectionTypeOrHigher, 47); } function isStartOfFunctionType() { if (token === 25) { @@ -7378,16 +8109,29 @@ var ts; } return token === 17 && lookAhead(isUnambiguouslyStartOfFunctionType); } + function skipParameterStart() { + if (ts.isModifierKind(token)) { + parseModifiers(); + } + if (isIdentifier()) { + nextToken(); + return true; + } + if (token === 19 || token === 15) { + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } function isUnambiguouslyStartOfFunctionType() { nextToken(); if (token === 18 || token === 22) { return true; } - if (isIdentifier() || ts.isModifier(token)) { - nextToken(); + if (skipParameterStart()) { if (token === 54 || token === 24 || - token === 53 || token === 56 || - isIdentifier() || ts.isModifier(token)) { + token === 53 || token === 56) { return true; } if (token === 18) { @@ -7399,15 +8143,35 @@ var ts; } return false; } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(152, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token === 124 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } function parseType() { - return doOutsideOfContext(10, parseTypeWorker); + return doOutsideOfContext(41943040, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(152); + return parseFunctionOrConstructorType(154); } if (token === 92) { - return parseFunctionOrConstructorType(153); + return parseFunctionOrConstructorType(155); } return parseUnionTypeOrHigher(); } @@ -7471,9 +8235,6 @@ var ts; token !== 55 && isStartOfExpression(); } - function allowInAndParseExpression() { - return allowInAnd(parseExpression); - } function parseExpression() { var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { @@ -7529,7 +8290,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(184); + var node = createNode(188); nextToken(); if (!scanner.hasPrecedingLineBreak() && (token === 37 || isStartOfExpression())) { @@ -7543,8 +8304,8 @@ var ts; } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 34, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(174, identifier.pos); - var parameter = createNode(138, identifier.pos); + var node = createNode(178, identifier.pos); + var parameter = createNode(140, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = [parameter]; @@ -7655,7 +8416,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(174); + var node = createNode(178); setModifiers(node, parseModifiersForArrowFunction()); var isAsync = !!(node.flags & 256); fillSignature(54, false, isAsync, !allowAmbiguity, node); @@ -7687,7 +8448,7 @@ var ts; if (!questionToken) { return leftOperand; } - var node = createNode(182, leftOperand.pos); + var node = createNode(186, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -7700,7 +8461,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 90 || t === 134; + return t === 90 || t === 136; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -7778,39 +8539,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(181, left.pos); + var node = createNode(185, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(189, left.pos); + var node = createNode(193, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(179); + var node = createNode(183); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(175); + var node = createNode(179); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(176); + var node = createNode(180); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(177); + var node = createNode(181); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -7825,7 +8586,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(178); + var node = createNode(182); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -7843,9 +8604,8 @@ var ts; var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === 38) { - var diagnostic; var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 171) { + if (simpleUnaryExpression.kind === 175) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -7893,7 +8653,7 @@ var ts; } function parseIncrementExpression() { if (token === 41 || token === 42) { - var node = createNode(179); + var node = createNode(183); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -7905,7 +8665,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 41 || token === 42) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(180, expression.pos); + var node = createNode(184, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -7928,31 +8688,44 @@ var ts; if (token === 17 || token === 21 || token === 19) { return expression; } - var node = createNode(166, expression.pos); + var node = createNode(170, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 69) { + return lhs.text === rhs.text; + } + return lhs.right.text === rhs.right.text && + tagNamesAreEquivalent(lhs.left, rhs.left); + } function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 235) { - var node = createNode(233, opening.pos); + if (opening.kind === 239) { + var node = createNode(237, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 234); + ts.Debug.assert(opening.kind === 238); result = opening; } if (inExpressionContext && token === 25) { var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(181, result.pos); + var badNode = createNode(185, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -7964,13 +8737,13 @@ var ts; return result; } function parseJsxText() { - var node = createNode(236, scanner.getStartPos()); + var node = createNode(240, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token) { - case 236: + case 240: return parseJsxText(); case 15: return parseJsxExpression(false); @@ -7990,7 +8763,7 @@ var ts; break; } else if (token === 1) { - parseErrorAtCurrentToken(ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } result.push(parseJsxChild()); @@ -8006,7 +8779,7 @@ var ts; var attributes = parseList(13, parseJsxAttribute); var node; if (token === 27) { - node = createNode(235, fullStart); + node = createNode(239, fullStart); scanJsxText(); } else { @@ -8018,7 +8791,7 @@ var ts; parseExpected(27, undefined, false); scanJsxText(); } - node = createNode(234, fullStart); + node = createNode(238, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -8029,7 +8802,7 @@ var ts; var elementName = parseIdentifierName(); while (parseOptional(21)) { scanJsxIdentifier(); - var node = createNode(135, elementName.pos); + var node = createNode(137, elementName.pos); node.left = elementName; node.right = parseIdentifierName(); elementName = finishNode(node); @@ -8037,10 +8810,10 @@ var ts; return elementName; } function parseJsxExpression(inExpressionContext) { - var node = createNode(240); + var node = createNode(244); parseExpected(15); if (token !== 16) { - node.expression = parseExpression(); + node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { parseExpected(16); @@ -8056,7 +8829,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(238); + var node = createNode(242); node.name = parseIdentifierName(); if (parseOptional(56)) { switch (token) { @@ -8071,7 +8844,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(239); + var node = createNode(243); parseExpected(15); parseExpected(22); node.expression = parseExpression(); @@ -8079,7 +8852,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(237); + var node = createNode(241); parseExpected(26); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -8092,7 +8865,7 @@ var ts; return finishNode(node); } function parseTypeAssertion() { - var node = createNode(171); + var node = createNode(175); parseExpected(25); node.type = parseType(); parseExpected(27); @@ -8103,7 +8876,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(21); if (dotToken) { - var propertyAccess = createNode(166, expression.pos); + var propertyAccess = createNode(170, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); @@ -8111,7 +8884,7 @@ var ts; continue; } if (!inDecoratorContext() && parseOptional(19)) { - var indexedAccess = createNode(167, expression.pos); + var indexedAccess = createNode(171, expression.pos); indexedAccess.expression = expression; if (token !== 20) { indexedAccess.argumentExpression = allowInAnd(parseExpression); @@ -8125,7 +8898,7 @@ var ts; continue; } if (token === 11 || token === 12) { - var tagExpression = createNode(170, expression.pos); + var tagExpression = createNode(174, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 11 ? parseLiteralNode() @@ -8144,7 +8917,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(168, expression.pos); + var callExpr = createNode(172, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -8152,7 +8925,7 @@ var ts; continue; } else if (token === 17) { - var callExpr = createNode(168, expression.pos); + var callExpr = createNode(172, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -8247,41 +9020,42 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(172); + var node = createNode(176); parseExpected(17); node.expression = allowInAnd(parseExpression); parseExpected(18); return finishNode(node); } function parseSpreadElement() { - var node = createNode(185); + var node = createNode(189); parseExpected(22); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 22 ? parseSpreadElement() : - token === 24 ? createNode(187) : + token === 24 ? createNode(191) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(164); + var node = createNode(168); parseExpected(19); - if (scanner.hasPrecedingLineBreak()) - node.flags |= 1024; + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); parseExpected(20); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(123)) { - return parseAccessorDeclaration(145, fullStart, decorators, modifiers); + return parseAccessorDeclaration(147, fullStart, decorators, modifiers); } - else if (parseContextualModifier(129)) { - return parseAccessorDeclaration(146, fullStart, decorators, modifiers); + else if (parseContextualModifier(130)) { + return parseAccessorDeclaration(148, fullStart, decorators, modifiers); } return undefined; } @@ -8295,7 +9069,6 @@ var ts; } var asteriskToken = parseOptionalToken(37); var tokenIsIdentifier = isIdentifier(); - var nameToken = token; var propertyName = parsePropertyName(); var questionToken = parseOptionalToken(53); if (asteriskToken || token === 17 || token === 25) { @@ -8303,7 +9076,7 @@ var ts; } var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 || token === 16 || token === 56); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(246, fullStart); + var shorthandDeclaration = createNode(250, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; var equalsToken = parseOptionalToken(56); @@ -8311,22 +9084,23 @@ var ts; shorthandDeclaration.equalsToken = equalsToken; shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return finishNode(shorthandDeclaration); + return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(245, fullStart); + var propertyAssignment = createNode(249, fullStart); + propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(54); propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return finishNode(propertyAssignment); + return addJSDocComment(finishNode(propertyAssignment)); } } function parseObjectLiteralExpression() { - var node = createNode(165); + var node = createNode(169); parseExpected(15); if (scanner.hasPrecedingLineBreak()) { - node.flags |= 1024; + node.multiLine = true; } node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); parseExpected(16); @@ -8337,7 +9111,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(false); } - var node = createNode(173); + var node = createNode(177); setModifiers(node, parseModifiers()); parseExpected(87); node.asteriskToken = parseOptionalToken(37); @@ -8353,13 +9127,13 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(true); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(169); + var node = createNode(173); parseExpected(92); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -8369,7 +9143,7 @@ var ts; return finishNode(node); } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(192); + var node = createNode(196); if (parseExpected(15, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(1, parseStatement); parseExpected(16); @@ -8397,12 +9171,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(194); + var node = createNode(198); parseExpected(23); return finishNode(node); } function parseIfStatement() { - var node = createNode(196); + var node = createNode(200); parseExpected(88); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -8412,7 +9186,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(197); + var node = createNode(201); parseExpected(79); node.statement = parseStatement(); parseExpected(104); @@ -8423,7 +9197,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(198); + var node = createNode(202); parseExpected(104); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -8446,21 +9220,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(90)) { - var forInStatement = createNode(200, pos); + var forInStatement = createNode(204, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(18); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(134)) { - var forOfStatement = createNode(201, pos); + else if (parseOptional(136)) { + var forOfStatement = createNode(205, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(18); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(199, pos); + var forStatement = createNode(203, pos); forStatement.initializer = initializer; parseExpected(23); if (token !== 23 && token !== 18) { @@ -8478,7 +9252,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 203 ? 70 : 75); + parseExpected(kind === 207 ? 70 : 75); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -8486,7 +9260,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(204); + var node = createNode(208); parseExpected(94); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -8495,7 +9269,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(205); + var node = createNode(209); parseExpected(105); parseExpected(17); node.expression = allowInAnd(parseExpression); @@ -8504,7 +9278,7 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(241); + var node = createNode(245); parseExpected(71); node.expression = allowInAnd(parseExpression); parseExpected(54); @@ -8512,7 +9286,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(242); + var node = createNode(246); parseExpected(77); parseExpected(54); node.statements = parseList(3, parseStatement); @@ -8522,12 +9296,12 @@ var ts; return token === 71 ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(206); + var node = createNode(210); parseExpected(96); parseExpected(17); node.expression = allowInAnd(parseExpression); parseExpected(18); - var caseBlock = createNode(220, scanner.getStartPos()); + var caseBlock = createNode(224, scanner.getStartPos()); parseExpected(15); caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); parseExpected(16); @@ -8535,14 +9309,14 @@ var ts; return finishNode(node); } function parseThrowStatement() { - var node = createNode(208); + var node = createNode(212); parseExpected(98); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(209); + var node = createNode(213); parseExpected(100); node.tryBlock = parseBlock(false); node.catchClause = token === 72 ? parseCatchClause() : undefined; @@ -8553,7 +9327,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(244); + var result = createNode(248); parseExpected(72); if (parseExpected(17)) { result.variableDeclaration = parseVariableDeclaration(); @@ -8563,7 +9337,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(210); + var node = createNode(214); parseExpected(76); parseSemicolon(); return finishNode(node); @@ -8572,16 +9346,16 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 69 && parseOptional(54)) { - var labeledStatement = createNode(207, fullStart); + var labeledStatement = createNode(211, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); - return finishNode(labeledStatement); + return addJSDocComment(finishNode(labeledStatement)); } else { - var expressionStatement = createNode(195, fullStart); + var expressionStatement = createNode(199, fullStart); expressionStatement.expression = expression; parseSemicolon(); - return finishNode(expressionStatement); + return addJSDocComment(finishNode(expressionStatement)); } } function nextTokenIsIdentifierOrKeywordOnSameLine() { @@ -8607,7 +9381,7 @@ var ts; case 81: return true; case 107: - case 132: + case 133: return nextTokenIsIdentifierOnSameLine(); case 125: case 126: @@ -8618,11 +9392,14 @@ var ts; case 110: case 111: case 112: + case 127: nextToken(); if (scanner.hasPrecedingLineBreak()) { return false; } continue; + case 135: + return nextToken() === 15; case 89: nextToken(); return token === 9 || token === 37 || @@ -8679,12 +9456,14 @@ var ts; case 107: case 125: case 126: - case 132: + case 133: + case 135: return true; case 112: case 110: case 111: case 113: + case 127: return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); default: return isStartOfExpression(); @@ -8723,9 +9502,9 @@ var ts; case 86: return parseForOrForInOrForOfStatement(); case 75: - return parseBreakOrContinueStatement(202); + return parseBreakOrContinueStatement(206); case 70: - return parseBreakOrContinueStatement(203); + return parseBreakOrContinueStatement(207); case 94: return parseReturnStatement(); case 105: @@ -8744,7 +9523,7 @@ var ts; return parseDeclaration(); case 118: case 107: - case 132: + case 133: case 125: case 126: case 122: @@ -8757,6 +9536,8 @@ var ts; case 112: case 115: case 113: + case 127: + case 135: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -8779,10 +9560,11 @@ var ts; return parseClassDeclaration(fullStart, decorators, modifiers); case 107: return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 132: + case 133: return parseTypeAliasDeclaration(fullStart, decorators, modifiers); case 81: return parseEnumDeclaration(fullStart, decorators, modifiers); + case 135: case 125: case 126: return parseModuleDeclaration(fullStart, decorators, modifiers); @@ -8795,7 +9577,7 @@ var ts; parseExportDeclaration(fullStart, decorators, modifiers); default: if (decorators || modifiers) { - var node = createMissingNode(231, true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(235, true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -8816,16 +9598,16 @@ var ts; } function parseArrayBindingElement() { if (token === 24) { - return createNode(187); + return createNode(191); } - var node = createNode(163); + var node = createNode(167); node.dotDotDotToken = parseOptionalToken(22); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(163); + var node = createNode(167); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 54) { @@ -8840,14 +9622,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(161); + var node = createNode(165); parseExpected(15); node.elements = parseDelimitedList(9, parseObjectBindingElement); parseExpected(16); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(162); + var node = createNode(166); parseExpected(19); node.elements = parseDelimitedList(10, parseArrayBindingElement); parseExpected(20); @@ -8866,7 +9648,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(211); + var node = createNode(215); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -8875,21 +9657,21 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(212); + var node = createNode(216); switch (token) { case 102: break; case 108: - node.flags |= 8192; + node.flags |= 1024; break; case 74: - node.flags |= 16384; + node.flags |= 2048; break; default: ts.Debug.fail(); } nextToken(); - if (token === 134 && lookAhead(canFollowContextualOfKeyword)) { + if (token === 136 && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -8904,15 +9686,15 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 18; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(193, fullStart); + var node = createNode(197, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(213, fullStart); + var node = createNode(217, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(87); @@ -8922,19 +9704,19 @@ var ts; var isAsync = !!(node.flags & 256); fillSignature(54, isGenerator, isAsync, false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(144, pos); + var node = createNode(146, pos); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(121); fillSignature(54, false, false, false, node); node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(143, fullStart); + var method = createNode(145, fullStart); method.decorators = decorators; setModifiers(method, modifiers); method.asteriskToken = asteriskToken; @@ -8944,18 +9726,18 @@ var ts; var isAsync = !!(method.flags & 256); fillSignature(54, isGenerator, isAsync, false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); - return finishNode(method); + return addJSDocComment(finishNode(method)); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(141, fullStart); + var property = createNode(143, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = modifiers && modifiers.flags & 64 + property.initializer = modifiers && modifiers.flags & 32 ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(2 | 1, parseNonParameterInitializer); + : doOutsideOfContext(8388608 | 4194304, parseNonParameterInitializer); parseSemicolon(); return finishNode(property); } @@ -8988,6 +9770,7 @@ var ts; case 110: case 111: case 113: + case 127: return true; default: return false; @@ -8998,7 +9781,7 @@ var ts; if (token === 55) { return true; } - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { idToken = token; if (isClassMemberModifier(idToken)) { return true; @@ -9016,7 +9799,7 @@ var ts; return true; } if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 129 || idToken === 123) { + if (!ts.isKeyword(idToken) || idToken === 130 || idToken === 123) { return true; } switch (token) { @@ -9041,9 +9824,9 @@ var ts; } if (!decorators) { decorators = []; - decorators.pos = scanner.getStartPos(); + decorators.pos = decoratorStart; } - var decorator = createNode(139, decoratorStart); + var decorator = createNode(141, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -9052,14 +9835,21 @@ var ts; } return decorators; } - function parseModifiers() { + function parseModifiers(permitInvalidConstAsModifier) { var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token; - if (!parseAnyContextualModifier()) { - break; + if (token === 74 && permitInvalidConstAsModifier) { + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } } if (!modifiers) { modifiers = []; @@ -9092,13 +9882,13 @@ var ts; } function parseClassElement() { if (token === 23) { - var result = createNode(191); + var result = createNode(195); nextToken(); return finishNode(result); } var fullStart = getNodePos(); var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var modifiers = parseModifiers(true); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; @@ -9117,16 +9907,16 @@ var ts; return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_8 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_8, undefined); + var name_7 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 186); + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 190); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 214); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 218); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); @@ -9159,12 +9949,9 @@ var ts; } return undefined; } - function parseHeritageClausesWorker() { - return parseList(20, parseHeritageClause); - } function parseHeritageClause() { if (token === 83 || token === 106) { - var node = createNode(243); + var node = createNode(247); node.token = token; nextToken(); node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); @@ -9173,7 +9960,7 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(188); + var node = createNode(192); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 25) { node.typeArguments = parseBracketedList(18, parseType, 25, 27); @@ -9187,7 +9974,7 @@ var ts; return parseList(5, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(215, fullStart); + var node = createNode(219, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(107); @@ -9198,10 +9985,10 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216, fullStart); + var node = createNode(220, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - parseExpected(132); + parseExpected(133); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); parseExpected(56); @@ -9210,13 +9997,13 @@ var ts; return finishNode(node); } function parseEnumMember() { - var node = createNode(247, scanner.getStartPos()); + var node = createNode(251, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(217, fullStart); + var node = createNode(221, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(81); @@ -9231,7 +10018,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(219, scanner.getStartPos()); + var node = createNode(223, scanner.getStartPos()); if (parseExpected(15)) { node.statements = parseList(1, parseStatement); parseExpected(16); @@ -9242,29 +10029,38 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(218, fullStart); - var namespaceFlag = flags & 65536; + var node = createNode(222, fullStart); + var namespaceFlag = flags & 4096; node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 2 | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 1 | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(218, fullStart); + var node = createNode(222, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.name = parseLiteralNode(true); + if (token === 135) { + node.name = parseIdentifier(); + node.flags |= 131072; + } + else { + node.name = parseLiteralNode(true); + } node.body = parseModuleBlock(); return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (parseOptional(126)) { - flags |= 65536; + if (token === 135) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(126)) { + flags |= 4096; } else { parseExpected(125); @@ -9275,7 +10071,7 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 127 && + return token === 128 && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -9284,19 +10080,14 @@ var ts; function nextTokenIsSlash() { return nextToken() === 39; } - function nextTokenIsCommaOrFromKeyword() { - nextToken(); - return token === 24 || - token === 133; - } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(89); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 24 && token !== 133) { - var importEqualsDeclaration = createNode(221, fullStart); + if (token !== 24 && token !== 134) { + var importEqualsDeclaration = createNode(225, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -9306,27 +10097,27 @@ var ts; return finishNode(importEqualsDeclaration); } } - var importDeclaration = createNode(222, fullStart); + var importDeclaration = createNode(226, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); if (identifier || token === 37 || token === 15) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(133); + parseExpected(134); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(importDeclaration); } function parseImportClause(identifier, fullStart) { - var importClause = createNode(223, fullStart); + var importClause = createNode(227, fullStart); if (identifier) { importClause.name = identifier; } if (!importClause.name || parseOptional(24)) { - importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(225); + importClause.namedBindings = token === 37 ? parseNamespaceImport() : parseNamedImportsOrExports(229); } return finishNode(importClause); } @@ -9336,22 +10127,25 @@ var ts; : parseEntityName(false); } function parseExternalModuleReference() { - var node = createNode(232); - parseExpected(127); + var node = createNode(236); + parseExpected(128); parseExpected(17); node.expression = parseModuleSpecifier(); parseExpected(18); return finishNode(node); } function parseModuleSpecifier() { - var result = parseExpression(); - if (result.kind === 9) { + if (token === 9) { + var result = parseLiteralNode(); internIdentifier(result.text); + return result; + } + else { + return parseExpression(); } - return result; } function parseNamespaceImport() { - var namespaceImport = createNode(224); + var namespaceImport = createNode(228); parseExpected(37); parseExpected(116); namespaceImport.name = parseIdentifier(); @@ -9359,14 +10153,14 @@ var ts; } function parseNamedImportsOrExports(kind) { var node = createNode(kind); - node.elements = parseBracketedList(21, kind === 225 ? parseImportSpecifier : parseExportSpecifier, 15, 16); + node.elements = parseBracketedList(21, kind === 229 ? parseImportSpecifier : parseExportSpecifier, 15, 16); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(230); + return parseImportOrExportSpecifier(234); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(226); + return parseImportOrExportSpecifier(230); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -9385,23 +10179,23 @@ var ts; else { node.name = identifierName; } - if (kind === 226 && checkIdentifierIsKeyword) { + if (kind === 230 && checkIdentifierIsKeyword) { parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); + var node = createNode(232, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(37)) { - parseExpected(133); + parseExpected(134); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(229); - if (token === 133 || (token === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(133); + node.exportClause = parseNamedImportsOrExports(233); + if (token === 134 || (token === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(134); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -9409,7 +10203,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(227, fullStart); + var node = createNode(231, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(56)) { @@ -9429,11 +10223,13 @@ var ts; var amdModuleName; while (true) { var kind = triviaScanner.scan(); - if (kind === 5 || kind === 4 || kind === 3) { - continue; - } if (kind !== 2) { - break; + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } } var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; var comment = sourceText.substring(range.pos, range.end); @@ -9478,11 +10274,11 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 2 - || node.kind === 221 && node.moduleReference.kind === 232 - || node.kind === 222 - || node.kind === 227 - || node.kind === 228 + return node.flags & 1 + || node.kind === 225 && node.moduleReference.kind === 236 + || node.kind === 226 + || node.kind === 231 + || node.kind === 232 ? node : undefined; }); @@ -9507,17 +10303,17 @@ var ts; } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState("file.js", content, 2, undefined); - var jsDocTypeExpression = parseJSDocTypeExpression(start, length); + initializeState("file.js", content, 2, undefined, 1); + scanner.setText(content, start, length); + token = scanner.scan(); + var jsDocTypeExpression = parseJSDocTypeExpression(); 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(249); + function parseJSDocTypeExpression() { + var result = createNode(253, scanner.getTokenPos()); parseExpected(15); result.type = parseJSDocTopLevelType(); parseExpected(16); @@ -9528,12 +10324,12 @@ var ts; function parseJSDocTopLevelType() { var type = parseJSDocType(); if (token === 47) { - var unionType = createNode(253, type.pos); + var unionType = createNode(257, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === 56) { - var optionalType = createNode(260, type.pos); + var optionalType = createNode(264, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -9544,20 +10340,20 @@ var ts; var type = parseBasicTypeExpression(); while (true) { if (token === 19) { - var arrayType = createNode(252, type.pos); + var arrayType = createNode(256, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20); type = finishNode(arrayType); } else if (token === 53) { - var nullableType = createNode(255, type.pos); + var nullableType = createNode(259, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } else if (token === 49) { - var nonNullableType = createNode(256, type.pos); + var nonNullableType = createNode(260, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -9591,37 +10387,37 @@ var ts; case 97: return parseJSDocThisType(); case 117: - case 130: - case 128: - case 120: case 131: + case 129: + case 120: + case 132: case 103: return parseTokenNode(); } return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(264); + var result = createNode(268); nextToken(); parseExpected(54); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(263); + var result = createNode(267); nextToken(); parseExpected(54); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(262); + var result = createNode(266); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(261); + var result = createNode(265); nextToken(); parseExpected(17); result.parameters = parseDelimitedList(22, parseJSDocParameter); @@ -9634,26 +10430,28 @@ var ts; return finishNode(result); } function parseJSDocParameter() { - var parameter = createNode(138); + var parameter = createNode(140); parameter.type = parseJSDocType(); + if (parseOptional(56)) { + parameter.questionToken = createNode(56); + } return finishNode(parameter); } - function parseJSDocOptionalType(type) { - var result = createNode(260, type.pos); - nextToken(); - result.type = type; - return finishNode(result); - } function parseJSDocTypeReference() { - var result = createNode(259); + var result = createNode(263); result.name = parseSimplePropertyName(); - while (parseOptional(21)) { - if (token === 25) { - result.typeArguments = parseTypeArguments(); - break; - } - else { - result.name = parseQualifiedName(result.name); + if (token === 25) { + result.typeArguments = parseTypeArguments(); + } + else { + while (parseOptional(21)) { + if (token === 25) { + result.typeArguments = parseTypeArguments(); + break; + } + else { + result.name = parseQualifiedName(result.name); + } } } return finishNode(result); @@ -9674,13 +10472,13 @@ var ts; } } function parseQualifiedName(left) { - var result = createNode(135, left.pos); + var result = createNode(137, left.pos); result.left = left; result.right = parseIdentifierName(); return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(257); + var result = createNode(261); nextToken(); result.members = parseDelimitedList(24, parseJSDocRecordMember); checkForTrailingComma(result.members); @@ -9688,7 +10486,7 @@ var ts; return finishNode(result); } function parseJSDocRecordMember() { - var result = createNode(258); + var result = createNode(262); result.name = parseSimplePropertyName(); if (token === 54) { nextToken(); @@ -9697,13 +10495,13 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(256); + var result = createNode(260); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(254); + var result = createNode(258); nextToken(); result.types = parseDelimitedList(25, parseJSDocType); checkForTrailingComma(result.types); @@ -9717,7 +10515,7 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(253); + var result = createNode(257); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); parseExpected(18); @@ -9735,7 +10533,7 @@ var ts; return types; } function parseJSDocAllType() { - var result = createNode(250); + var result = createNode(254); nextToken(); return finishNode(result); } @@ -9748,29 +10546,35 @@ var ts; token === 27 || token === 56 || token === 47) { - var result = createNode(251, pos); + var result = createNode(255, pos); return finishNode(result); } else { - var result = createNode(255, pos); + var result = createNode(259, pos); result.type = parseJSDocType(); return finishNode(result); } } function parseIsolatedJSDocComment(content, start, length) { - initializeState("file.js", content, 2, undefined); - var jsDocComment = parseJSDocComment(undefined, start, length); + initializeState("file.js", content, 2, undefined, 1); + sourceFile = { languageVariant: 0, text: content }; + var jsDocComment = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var saveToken = token; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { - fixupParentReferences(comment); comment.parent = parent; } + token = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; } JSDocParser.parseJSDocComment = parseJSDocComment; @@ -9783,60 +10587,64 @@ var ts; 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 result; + if (content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42) { + scanner.scanRange(start + 3, length - 5, function () { 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) { + nextJSDocToken(); + while (token !== 1) { + switch (token) { + case 55: + if (canParseTag) { + parseTag(); + } + seenAsterisk = false; + break; + case 4: + canParseTag = true; + seenAsterisk = false; + break; + case 37: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 69: canParseTag = false; - } - seenAsterisk = true; - continue; + break; + case 1: + break; } - canParseTag = false; + nextJSDocToken(); } - } + result = createJSDocComment(); + }); } - return createJSDocComment(); + return result; function createJSDocComment() { if (!tags) { return undefined; } - var result = createNode(265, start); + var result = createNode(269, start); result.tags = tags; return finishNode(result, end); } function skipWhitespace() { - while (pos < end && ts.isWhiteSpace(content.charCodeAt(pos))) { - pos++; + while (token === 5 || token === 4) { + nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(content.charCodeAt(pos - 1) === 64); - var atToken = createNode(55, pos - 1); - atToken.end = pos; - var tagName = scanIdentifier(); + ts.Debug.assert(token === 55); + var atToken = createNode(55, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifier(); if (!tagName) { return; } @@ -9860,10 +10668,10 @@ var ts; return undefined; } function handleUnknownTag(atToken, tagName) { - var result = createNode(266, atToken.pos); + var result = createNode(270, atToken.pos); result.atToken = atToken; result.tagName = tagName; - return finishNode(result, pos); + return finishNode(result); } function addTag(tag) { if (tag) { @@ -9876,12 +10684,10 @@ var ts; } } function tryParseTypeExpression() { - skipWhitespace(); - if (content.charCodeAt(pos) !== 123) { + if (token !== 15) { return undefined; } - var typeExpression = parseJSDocTypeExpression(pos, end - pos); - pos = typeExpression.end; + var typeExpression = parseJSDocTypeExpression(); return typeExpression; } function handleParamTag(atToken, tagName) { @@ -9889,17 +10695,20 @@ var ts; skipWhitespace(); var name; var isBracketed; - if (content.charCodeAt(pos) === 91) { - pos++; - skipWhitespace(); - name = scanIdentifier(); + if (parseOptionalToken(19)) { + name = parseJSDocIdentifier(); isBracketed = true; + if (parseOptionalToken(56)) { + parseExpression(); + } + parseExpected(20); } - else { - name = scanIdentifier(); + else if (token === 69) { + name = parseJSDocIdentifier(); } if (!name) { - parseErrorAtPosition(pos, 0, ts.Diagnostics.Identifier_expected); + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; } var preName, postName; if (typeExpression) { @@ -9911,84 +10720,81 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(267, atToken.pos); + var result = createNode(271, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; result.typeExpression = typeExpression; result.postParameterName = postName; result.isBracketed = isBracketed; - return finishNode(result, pos); + return finishNode(result); } function handleReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 268; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 272; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(268, atToken.pos); + var result = createNode(272, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); - return finishNode(result, pos); + return finishNode(result); } function handleTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 269; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 273; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(269, atToken.pos); + var result = createNode(273, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); - return finishNode(result, pos); + return finishNode(result); } function handleTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 270; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 274; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } var typeParameters = []; - typeParameters.pos = pos; + typeParameters.pos = scanner.getStartPos(); while (true) { - skipWhitespace(); - var startPos = pos; - var name_9 = scanIdentifier(); - if (!name_9) { - parseErrorAtPosition(startPos, 0, ts.Diagnostics.Identifier_expected); + var name_8 = parseJSDocIdentifier(); + if (!name_8) { + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(137, name_9.pos); - typeParameter.name = name_9; - finishNode(typeParameter, pos); + var typeParameter = createNode(139, name_8.pos); + typeParameter.name = name_8; + finishNode(typeParameter); typeParameters.push(typeParameter); - skipWhitespace(); - if (content.charCodeAt(pos) !== 44) { + if (token === 24) { + nextJSDocToken(); + } + else { break; } - pos++; } - typeParameters.end = pos; - var result = createNode(270, atToken.pos); + var result = createNode(274, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; - return finishNode(result, pos); + finishNode(result); + typeParameters.end = result.end; + return result; } - 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) { + function nextJSDocToken() { + return token = scanner.scanJSDocToken(); + } + function parseJSDocIdentifier() { + if (token !== 69) { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); return undefined; } - var result = createNode(69, startPos); - result.text = content.substring(startPos, pos); - return finishNode(result, pos); + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(69, pos); + result.text = content.substring(pos, end); + finishNode(result, end); + nextJSDocToken(); + return result; } } JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; @@ -10003,7 +10809,7 @@ var ts; return sourceFile; } if (sourceFile.statements.length === 0) { - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true); + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); } var incrementalSourceFile = sourceFile; ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); @@ -10017,7 +10823,7 @@ var ts; ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); return result; } IncrementalParser.updateSourceFile = updateSourceFile; @@ -10086,12 +10892,12 @@ var ts; } function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { - var pos = node.pos; + var pos_2 = node.pos; forEachChild(node, function (child) { - ts.Debug.assert(child.pos >= pos); - pos = child.end; + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; }); - ts.Debug.assert(pos <= node.end); + ts.Debug.assert(pos_2 <= node.end); } } function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { @@ -10287,32 +11093,32 @@ var ts; : 4; } function getModuleInstanceState(node) { - if (node.kind === 215 || node.kind === 216) { + if (node.kind === 219 || node.kind === 220) { return 0; } else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 222 || node.kind === 221) && !(node.flags & 2)) { + else if ((node.kind === 226 || node.kind === 225) && !(node.flags & 1)) { return 0; } - else if (node.kind === 219) { - var state = 0; + else if (node.kind === 223) { + var state_1 = 0; ts.forEachChild(node, function (n) { switch (getModuleInstanceState(n)) { case 0: return false; case 2: - state = 2; + state_1 = 2; return false; case 1: - state = 1; + state_1 = 1; return true; } }); - return state; + return state_1; } - else if (node.kind === 218) { + else if (node.kind === 222) { return getModuleInstanceState(node.body); } else { @@ -10340,6 +11146,10 @@ var ts; var labelStack; var labelIndexMap; var implicitLabels; + var hasClassExtends; + var hasAsyncFunctions; + var hasDecorators; + var hasParameterDecorators; var inStrictMode; var symbolCount = 0; var Symbol; @@ -10355,6 +11165,8 @@ var ts; file.symbolCount = symbolCount; file.classifiableNames = classifiableNames; } + file = undefined; + options = undefined; parent = undefined; container = undefined; blockScopeContainer = undefined; @@ -10364,6 +11176,10 @@ var ts; labelStack = undefined; labelIndexMap = undefined; implicitLabels = undefined; + hasClassExtends = false; + hasAsyncFunctions = false; + hasDecorators = false; + hasParameterDecorators = false; } return bindSourceFile; function createSymbol(flags, name) { @@ -10383,40 +11199,66 @@ var ts; if (symbolFlags & 6240 && !symbol.members) { symbol.members = {}; } - if (symbolFlags & 107455 && !symbol.valueDeclaration) { - symbol.valueDeclaration = node; + if (symbolFlags & 107455) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 222)) { + symbol.valueDeclaration = node; + } } } function getDeclarationName(node) { if (node.name) { - if (node.kind === 218 && node.name.kind === 9) { - return "\"" + node.name.text + "\""; + if (ts.isAmbientModule(node)) { + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; } - if (node.name.kind === 136) { + if (node.name.kind === 138) { var nameExpression = node.name.expression; + if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + return nameExpression.text; + } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } return node.name.text; } switch (node.kind) { - case 144: + case 146: return "__constructor"; - case 152: - case 147: - return "__call"; - case 153: - case 148: - return "__new"; + case 154: case 149: + return "__call"; + case 155: + case 150: + return "__new"; + case 151: return "__index"; - case 228: + case 232: return "__export"; - case 227: + case 231: return node.isExportEquals ? "export=" : "default"; - case 213: - case 214: + case 185: + switch (ts.getSpecialPropertyAssignmentKind(node)) { + case 2: + return "export="; + case 1: + case 4: + return node.left.name.text; + case 3: + return node.left.expression.name.text; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 217: + case 218: return node.flags & 512 ? "default" : undefined; + case 265: + return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; + case 140: + ts.Debug.assert(node.parent.kind === 265); + var functionType = node.parent; + var index = ts.indexOf(functionType.parameters, node); + return "p" + index; } } function getDisplayName(node) { @@ -10438,18 +11280,18 @@ var ts; if (node.name) { node.name.parent = node; } - var message = symbol.flags & 2 + var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(symbol.declarations, function (declaration) { if (declaration.flags & 512) { - message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } }); ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -10461,9 +11303,9 @@ var ts; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 2; + var hasExportModifier = ts.getCombinedNodeFlags(node) & 1; if (symbolFlags & 8388608) { - if (node.kind === 230 || (node.kind === 221 && hasExportModifier)) { + if (node.kind === 234 || (node.kind === 225 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -10471,7 +11313,7 @@ var ts; } } else { - if (hasExportModifier || container.flags & 131072) { + if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192)) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | (symbolFlags & 793056 ? 2097152 : 0) | (symbolFlags & 1536 ? 4194304 : 0); @@ -10509,11 +11351,12 @@ var ts; var savedHasExplicitReturn; var kind = node.kind; var flags = node.flags; - flags &= ~1572864; - if (kind === 215) { + flags &= ~98304; + flags &= ~3932160; + if (kind === 219) { seenThisKeyword = false; } - var saveState = kind === 248 || kind === 219 || ts.isFunctionLikeKind(kind); + var saveState = kind === 252 || kind === 223 || ts.isFunctionLikeKind(kind); if (saveState) { savedReachabilityState = currentReachabilityState; savedLabelStack = labelStack; @@ -10524,15 +11367,32 @@ var ts; hasExplicitReturn = false; labelStack = labelIndexMap = implicitLabels = undefined; } + if (ts.isInJavaScriptFile(node) && node.jsDocComment) { + bind(node.jsDocComment); + } bindReachableStatement(node); if (currentReachabilityState === 2 && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { - flags |= 524288; + flags |= 32768; if (hasExplicitReturn) { - flags |= 1048576; + flags |= 65536; } } - if (kind === 215) { - flags = seenThisKeyword ? flags | 262144 : flags & ~262144; + if (kind === 219) { + flags = seenThisKeyword ? flags | 16384 : flags & ~16384; + } + if (kind === 252) { + if (hasClassExtends) { + flags |= 262144; + } + if (hasDecorators) { + flags |= 524288; + } + if (hasParameterDecorators) { + flags |= 1048576; + } + if (hasAsyncFunctions) { + flags |= 2097152; + } } node.flags = flags; if (saveState) { @@ -10552,40 +11412,40 @@ var ts; return; } switch (node.kind) { - case 198: + case 202: bindWhileStatement(node); break; - case 197: + case 201: bindDoStatement(node); break; - case 199: + case 203: bindForStatement(node); break; - case 200: - case 201: + case 204: + case 205: bindForInOrForOfStatement(node); break; - case 196: + case 200: bindIfStatement(node); break; - case 204: case 208: + case 212: bindReturnOrThrow(node); break; - case 203: - case 202: + case 207: + case 206: bindBreakOrContinueStatement(node); break; - case 209: + case 213: bindTryStatement(node); break; - case 206: + case 210: bindSwitchStatement(node); break; - case 220: + case 224: bindCaseBlock(node); break; - case 207: + case 211: bindLabeledStatement(node); break; default: @@ -10647,14 +11507,14 @@ var ts; } function bindReturnOrThrow(n) { bind(n.expression); - if (n.kind === 204) { + if (n.kind === 208) { hasExplicitReturn = true; } currentReachabilityState = 4; } function bindBreakOrContinueStatement(n) { bind(n.label); - var isValidJump = jumpToLabel(n.label, n.kind === 203 ? currentReachabilityState : 4); + var isValidJump = jumpToLabel(n.label, n.kind === 207 ? currentReachabilityState : 4); if (isValidJump) { currentReachabilityState = 4; } @@ -10675,7 +11535,7 @@ var ts; var postSwitchLabel = pushImplicitLabel(); bind(n.expression); bind(n.caseBlock); - var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242; }); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 246; }); var postSwitchState = hasDefault && currentReachabilityState !== 2 ? 4 : preSwitchState; popImplicitLabel(postSwitchLabel, postSwitchState); } @@ -10700,37 +11560,38 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 186: - case 214: - case 215: - case 217: - case 155: - case 165: + case 190: + case 218: + case 219: + case 221: + case 169: + case 157: + case 261: return 1; + case 149: + case 150: + case 151: + case 145: + case 144: + case 217: + case 146: case 147: case 148: - case 149: - case 143: - case 142: - case 213: - case 144: - case 145: - case 146: - case 152: - case 153: - case 173: - case 174: - case 218: - case 248: - case 216: - return 5; - case 244: - case 199: - case 200: - case 201: + case 154: + case 155: + case 177: + case 178: + case 222: + case 252: case 220: + return 5; + case 248: + case 203: + case 204: + case 205: + case 224: return 2; - case 192: + case 196: return ts.isFunctionLike(node.parent) ? 0 : 2; } return 0; @@ -10746,38 +11607,40 @@ var ts; } function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 218: + case 222: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 248: + case 252: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 186: - case 214: + case 190: + case 218: return declareClassMember(node, symbolFlags, symbolExcludes); - case 217: + case 221: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 155: - case 165: - case 215: + case 157: + case 169: + case 219: + case 261: return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 152: - case 153: + case 154: + case 155: + case 149: + case 150: + case 151: + case 145: + case 144: + case 146: case 147: case 148: - case 149: - case 143: - case 142: - case 144: - case 145: - case 146: - case 213: - case 173: - case 174: - case 216: + case 217: + case 177: + case 178: + case 265: + case 220: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 64 + return node.flags & 32 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -10787,11 +11650,11 @@ var ts; : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 248 ? node : node.body; - if (body.kind === 248 || body.kind === 219) { + var body = node.kind === 252 ? node : node.body; + if (body.kind === 252 || body.kind === 223) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; - if (stat.kind === 228 || stat.kind === 227) { + if (stat.kind === 232 || stat.kind === 231) { return true; } } @@ -10800,15 +11663,18 @@ var ts; } function setExportContextFlag(node) { if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 131072; + node.flags |= 8192; } else { - node.flags &= ~131072; + node.flags &= ~8192; } } function bindModuleDeclaration(node) { setExportContextFlag(node); - if (node.name.kind === 9) { + if (ts.isAmbientModule(node)) { + if (node.flags & 1) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } declareSymbolAndAddToSymbolTable(node, 512, 106639); } else { @@ -10850,7 +11716,7 @@ var ts; continue; } var identifier = prop.name; - var currentKind = prop.kind === 245 || prop.kind === 246 || prop.kind === 143 + var currentKind = prop.kind === 249 || prop.kind === 250 || prop.kind === 145 ? 1 : 2; var existingKind = seen[identifier.text]; @@ -10872,10 +11738,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 218: + case 222: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 248: + case 252: if (ts.isExternalModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -10954,7 +11820,7 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.flags & 32768) { + if (inStrictMode && node.isOctalLiteral) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } @@ -10997,17 +11863,17 @@ var ts; } function updateStrictMode(node) { switch (node.kind) { - case 248: - case 219: + case 252: + case 223: updateStrictModeStatementList(node.statements); return; - case 192: + case 196: if (ts.isFunctionLike(node.parent)) { updateStrictModeStatementList(node.statements); } return; - case 214: - case 186: + case 218: + case 190: inStrictMode = true; return; } @@ -11032,103 +11898,145 @@ var ts; switch (node.kind) { case 69: return checkStrictModeIdentifier(node); - case 181: + case 185: + if (ts.isInJavaScriptFile(node)) { + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1: + bindExportsPropertyAssignment(node); + break; + case 2: + bindModuleExportsAssignment(node); + break; + case 3: + bindPrototypePropertyAssignment(node); + break; + case 4: + bindThisPropertyAssignment(node); + break; + case 0: + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + } return checkStrictModeBinaryExpression(node); - case 244: + case 248: return checkStrictModeCatchClause(node); - case 175: + case 179: return checkStrictModeDeleteExpression(node); case 8: return checkStrictModeNumericLiteral(node); - case 180: + case 184: return checkStrictModePostfixUnaryExpression(node); - case 179: + case 183: return checkStrictModePrefixUnaryExpression(node); - case 205: + case 209: return checkStrictModeWithStatement(node); - case 97: + case 163: seenThisKeyword = true; return; - case 137: + case 152: + return checkTypePredicate(node); + case 139: return declareSymbolAndAddToSymbolTable(node, 262144, 530912); - case 138: - return bindParameter(node); - case 211: - case 163: - return bindVariableDeclarationOrBindingElement(node); - case 141: case 140: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); - case 245: - case 246: - return bindPropertyOrMethodOrAccessor(node, 4, 107455); - case 247: - return bindPropertyOrMethodOrAccessor(node, 8, 107455); - case 147: - case 148: - case 149: - return declareSymbolAndAddToSymbolTable(node, 131072, 0); + return bindParameter(node); + case 215: + case 167: + return bindVariableDeclarationOrBindingElement(node); case 143: case 142: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); - case 213: - checkStrictModeFunctionName(node); - return declareSymbolAndAddToSymbolTable(node, 16, 106927); - case 144: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 262: + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); + case 249: + case 250: + return bindPropertyOrMethodOrAccessor(node, 4, 107455); + case 251: + return bindPropertyOrMethodOrAccessor(node, 8, 107455); + case 149: + case 150: + case 151: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 145: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); - case 146: - return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 152: - case 153: - return bindFunctionOrConstructorType(node); - case 155: - return bindAnonymousDeclaration(node, 2048, "__type"); - case 165: - return bindObjectLiteralExpression(node); - case 173: - case 174: - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.text : "__function"; - return bindAnonymousDeclaration(node, 16, bindingName); - case 186: - case 214: - return bindClassLikeDeclaration(node); - case 215: - return bindBlockScopedDeclaration(node, 64, 792960); - case 216: - return bindBlockScopedDeclaration(node, 524288, 793056); + case 144: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); case 217: - return bindEnumDeclaration(node); + return bindFunctionDeclaration(node); + case 146: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 147: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 148: + return bindPropertyOrMethodOrAccessor(node, 65536, 74687); + case 154: + case 155: + case 265: + return bindFunctionOrConstructorType(node); + case 157: + case 261: + return bindAnonymousDeclaration(node, 2048, "__type"); + case 169: + return bindObjectLiteralExpression(node); + case 177: + case 178: + return bindFunctionExpression(node); + case 172: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + case 190: case 218: - return bindModuleDeclaration(node); + return bindClassLikeDeclaration(node); + case 219: + return bindBlockScopedDeclaration(node, 64, 792960); + case 220: + return bindBlockScopedDeclaration(node, 524288, 793056); case 221: - case 224: - case 226: - case 230: - return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); - case 223: - return bindImportClause(node); + return bindEnumDeclaration(node); + case 222: + return bindModuleDeclaration(node); + case 225: case 228: - return bindExportDeclaration(node); + case 230: + case 234: + return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); case 227: + return bindImportClause(node); + case 232: + return bindExportDeclaration(node); + case 231: return bindExportAssignment(node); - case 248: + case 252: return bindSourceFileIfExternalModule(); } } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 69) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 163) { + seenThisKeyword = true; + } + bind(type); + } function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (ts.isExternalModule(file)) { - bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); + bindSourceFileAsExternalModule(); } } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } function bindExportAssignment(node) { + var boundExpression = node.kind === 231 ? node.expression : node.right; if (!container.symbol || !container.symbol.exports) { bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } - else if (node.expression.kind === 69) { + else if (boundExpression.kind === 69 && node.kind === 231) { declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608); } else { @@ -11148,8 +12056,57 @@ var ts; declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); } } + function setCommonJsModuleIndicator(node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + } + function bindExportsPropertyAssignment(node) { + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 7340032, 0); + } + function bindModuleExportsAssignment(node) { + setCommonJsModuleIndicator(node); + bindExportAssignment(node); + } + function bindThisPropertyAssignment(node) { + if (container.kind === 177 || container.kind === 217) { + container.symbol.members = container.symbol.members || {}; + declareSymbol(container.symbol.members, container.symbol, node, 4, 107455 & ~4); + } + } + function bindPrototypePropertyAssignment(node) { + var leftSideOfAssignment = node.left; + var classPrototype = leftSideOfAssignment.expression; + var constructorFunction = classPrototype.expression; + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + var funcSymbol = container.locals[constructorFunction.text]; + if (!funcSymbol || !(funcSymbol.flags & 16)) { + return; + } + if (!funcSymbol.members) { + funcSymbol.members = {}; + } + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 107455); + } + function bindCallExpression(node) { + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { + setCommonJsModuleIndicator(node); + } + } function bindClassLikeDeclaration(node) { - if (node.kind === 214) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { + hasClassExtends = true; + } + if (ts.nodeIsDecorated(node)) { + hasDecorators = true; + } + } + if (node.kind === 218) { bindBlockScopedDeclaration(node, 32, 899519); } else { @@ -11192,6 +12149,12 @@ var ts; } } function bindParameter(node) { + if (!ts.isDeclarationFile(file) && + !ts.isInAmbientContext(node) && + ts.nodeIsDecorated(node)) { + hasDecorators = true; + hasParameterDecorators = true; + } if (inStrictMode) { checkStrictModeEvalOrArguments(node, node.name); } @@ -11201,14 +12164,39 @@ var ts; else { declareSymbolAndAddToSymbolTable(node, 1, 107455); } - if (node.flags & 56 && - node.parent.kind === 144 && - ts.isClassLike(node.parent.parent)) { + if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); } } + function bindFunctionDeclaration(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + } + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, 16, 106927); + } + function bindFunctionExpression(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.text : "__function"; + return bindAnonymousDeclaration(node, 16, bindingName); + } function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + if (ts.nodeIsDecorated(node)) { + hasDecorators = true; + } + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -11268,16 +12256,16 @@ var ts; function checkUnreachable(node) { switch (currentReachabilityState) { case 4: - var reportError = ts.isStatement(node) || - node.kind === 214 || - (node.kind === 218 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 217 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + var reportError = (ts.isStatement(node) && node.kind !== 198) || + node.kind === 218 || + (node.kind === 222 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 221 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); if (reportError) { currentReachabilityState = 8; var reportUnreachableCode = !options.allowUnreachableCode && !ts.isInAmbientContext(node) && - (node.kind !== 193 || - ts.getCombinedNodeFlags(node.declarationList) & 24576 || + (node.kind !== 197 || + ts.getCombinedNodeFlags(node.declarationList) & 3072 || ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); if (reportUnreachableCode) { errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); @@ -11310,15 +12298,18 @@ var ts; var nextNodeId = 1; var nextMergeId = 1; function getNodeId(node) { - if (!node.id) - node.id = nextNodeId++; + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } return node.id; } ts.getNodeId = getNodeId; ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { - symbol.id = nextSymbolId++; + symbol.id = nextSymbolId; + nextSymbolId++; } return symbol.id; } @@ -11334,9 +12325,11 @@ var ts; var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 ? 5 : 0; + var modulekind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; var emitResolver = createResolver(); var undefinedSymbol = createSymbol(4 | 67108864, "undefined"); + undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 | 67108864, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -11345,9 +12338,11 @@ var ts; getTypeCount: function () { return typeCount; }, isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, getDiagnostics: getDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, + getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: getPropertyOfType, @@ -11358,6 +12353,7 @@ var ts; getSymbolsInScope: getSymbolsInScope, getSymbolAtLocation: getSymbolAtLocation, getShorthandAssignmentValueSymbol: getShorthandAssignmentValueSymbol, + getExportSpecifierLocalTargetSymbol: getExportSpecifierLocalTargetSymbol, getTypeAtLocation: getTypeOfNode, typeToString: typeToString, getSymbolDisplayBuilder: getSymbolDisplayBuilder, @@ -11389,8 +12385,8 @@ var ts; var undefinedType = createIntrinsicType(32 | 2097152, "undefined"); var nullType = createIntrinsicType(64 | 2097152, "null"); var unknownType = createIntrinsicType(1, "unknown"); - var circularType = createIntrinsicType(1, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyUnionType = emptyObjectType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -11398,24 +12394,25 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var enumNumberIndexInfo = createIndexInfo(stringType, true); var globals = {}; var globalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; var globalObjectType; var globalFunctionType; var globalArrayType; + var globalReadonlyArrayType; var globalStringType; var globalNumberType; var globalBooleanType; var globalRegExpType; var globalTemplateStringsArrayType; var globalESSymbolType; - var jsxElementType; - var jsxIntrinsicElementsType; var globalIterableType; var globalIteratorType; var globalIterableIteratorType; var anyArrayType; + var anyReadonlyArrayType; var getGlobalClassDecoratorType; var getGlobalParameterDecoratorType; var getGlobalPropertyDecoratorType; @@ -11428,15 +12425,11 @@ var ts; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; var jsxElementClassType; + var deferredNodes; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; var stringLiteralTypes = {}; - var emitExtends = false; - var emitDecorate = false; - var emitParam = false; - var emitAwaiter = false; - var emitGenerator = false; var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -11462,19 +12455,31 @@ var ts; "symbol": { type: esSymbolType, flags: 16777216 + }, + "undefined": { + type: undefinedType, + flags: 2097152 } }; + var jsxElementType; + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", ElementClass: "ElementClass", ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - Element: "Element" + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" }; var subtypeRelation = {}; var assignableRelation = {}; var identityRelation = {}; var _displayBuilder; + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -11528,8 +12533,10 @@ var ts; return result; } function recordMergedSymbol(target, source) { - if (!source.mergeId) - source.mergeId = nextMergeId++; + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { @@ -11553,8 +12560,11 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (!target.valueDeclaration && source.valueDeclaration) + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 222 && source.valueDeclaration.kind !== 222))) { target.valueDeclaration = source.valueDeclaration; + } ts.forEach(source.declarations, function (node) { target.declarations.push(node); }); @@ -11571,13 +12581,13 @@ var ts; recordMergedSymbol(target, source); } else { - var message = target.flags & 2 || source.flags & 2 + var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message, symbolToString(source)); + error(node.name ? node.name : node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message, symbolToString(source)); + error(node.name ? node.name : node, message_2, symbolToString(source)); }); } } @@ -11606,6 +12616,45 @@ var ts; } } } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.valueDeclaration !== moduleAugmentation) { + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found); + if (!mainModule) { + return; + } + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1536) { + mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + for (var id in source) { + if (ts.hasProperty(source, id)) { + if (ts.hasProperty(target, id)) { + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } + } + } + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } function getSymbolLinks(symbol) { if (symbol.flags & 67108864) return symbol; @@ -11616,11 +12665,8 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } - function getSourceFile(node) { - return ts.getAncestor(node, 248); - } function isGlobalSourceFile(node) { - return node.kind === 248 && !ts.isExternalModule(node); + return node.kind === 252 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -11637,6 +12683,16 @@ var ts; } } } + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); @@ -11648,18 +12704,18 @@ var ts; return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); } if (declaration.pos <= usage.pos) { - return declaration.kind !== 211 || + return declaration.kind !== 215 || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } return isUsedInFunctionOrNonStaticProperty(declaration, usage); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); - if (declaration.parent.parent.kind === 193 || - declaration.parent.parent.kind === 199) { + if (declaration.parent.parent.kind === 197 || + declaration.parent.parent.kind === 203) { return isSameScopeDescendentOf(usage, declaration, container); } - else if (declaration.parent.parent.kind === 201 || - declaration.parent.parent.kind === 200) { + else if (declaration.parent.parent.kind === 205 || + declaration.parent.parent.kind === 204) { var expression = declaration.parent.parent.expression; return isSameScopeDescendentOf(usage, expression, container); } @@ -11675,8 +12731,8 @@ var ts; return true; } var initializerOfNonStaticProperty = current.parent && - current.parent.kind === 141 && - (current.parent.flags & 64) === 0 && + current.parent.kind === 143 && + (current.parent.flags & 32) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -11695,47 +12751,62 @@ var ts; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { - if (!(meaning & 793056) || - !(result.flags & (793056 & ~262144)) || - !ts.isFunctionLike(location) || - lastLocation === location.body) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + if (meaning & result.flags & 793056 && lastLocation.kind !== 269) { + useResult = result.flags & 262144 + ? lastLocation === location.type || + lastLocation.kind === 140 || + lastLocation.kind === 139 + : false; + } + if (meaning & 107455 && result.flags & 1) { + useResult = + lastLocation.kind === 140 || + (lastLocation === location.type && + result.valueDeclaration.kind === 140); + } + } + if (useResult) { break loop; } - result = undefined; + else { + result = undefined; + } } } switch (location.kind) { - case 248: - if (!ts.isExternalModule(location)) + case 252: + if (!ts.isExternalOrCommonJsModule(location)) break; - case 218: + case 222: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 248 || - (location.kind === 218 && location.name.kind === 9)) { + if (location.kind === 252 || ts.isAmbientModule(location)) { + if (result = moduleExports["default"]) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { + break loop; + } + result = undefined; + } if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 && - ts.getDeclarationOfKind(moduleExports[name], 230)) { + ts.getDeclarationOfKind(moduleExports[name], 234)) { break; } - 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 217: + case 221: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; - case 141: - case 140: - if (ts.isClassLike(location.parent) && !(location.flags & 64)) { + case 143: + case 142: + if (ts.isClassLike(location.parent) && !(location.flags & 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -11744,17 +12815,17 @@ var ts; } } break; - case 214: - case 186: - case 215: + case 218: + case 190: + case 219: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { - if (lastLocation && lastLocation.flags & 64) { + if (lastLocation && lastLocation.flags & 32) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } break loop; } - if (location.kind === 186 && meaning & 32) { + if (location.kind === 190 && meaning & 32) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -11762,28 +12833,28 @@ var ts; } } break; - case 136: + case 138: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 215) { + if (ts.isClassLike(grandparent) || grandparent.kind === 219) { 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 143: - case 142: - case 144: case 145: + case 144: case 146: - case 213: - case 174: + case 147: + case 148: + case 217: + case 178: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 173: + case 177: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -11796,8 +12867,8 @@ var ts; } } break; - case 139: - if (location.parent && location.parent.kind === 138) { + case 141: + if (location.parent && location.parent.kind === 140) { location = location.parent; } if (location.parent && ts.isClassElement(location.parent)) { @@ -11813,7 +12884,9 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } return undefined; } @@ -11832,11 +12905,40 @@ var ts; } return result; } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!errorLocation || (errorLocation.kind === 69 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + return false; + } + var container = ts.getThisContainer(errorLocation, true); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); + return true; + } + if (location === container && !(location.flags & 32)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 211), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 215), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -11853,10 +12955,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 221) { + if (node.kind === 225) { return node; } - while (node && node.kind !== 222) { + while (node && node.kind !== 226) { node = node.parent; } return node; @@ -11866,7 +12968,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 232) { + if (node.moduleReference.kind === 236) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -11875,9 +12977,12 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); - if (!exportDefaultSymbol) { + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } return exportDefaultSymbol; } } @@ -11885,14 +12990,6 @@ var ts; var moduleSpecifier = node.parent.parent.moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } - function getMemberOfModuleVariable(moduleSymbol, name) { - if (moduleSymbol.flags & 3) { - var typeAnnotation = moduleSymbol.valueDeclaration.type; - if (typeAnnotation) { - return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); - } - } - } function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { if (valueSymbol.flags & (793056 | 1536)) { return valueSymbol; @@ -11928,15 +13025,15 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_10 = specifier.propertyName || specifier.name; - if (name_10.text) { - var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); - var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_10.text); + var name_9 = specifier.propertyName || specifier.name; + if (name_9.text) { + var symbolFromModule = getExportOfModule(targetSymbol, name_9.text); + var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_9.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_10, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_10)); + error(name_9, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_9)); } return symbol; } @@ -11955,17 +13052,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 221: + case 225: return getTargetOfImportEqualsDeclaration(node); - case 223: - return getTargetOfImportClause(node); - case 224: - return getTargetOfNamespaceImport(node); - case 226: - return getTargetOfImportSpecifier(node); - case 230: - return getTargetOfExportSpecifier(node); case 227: + return getTargetOfImportClause(node); + case 228: + return getTargetOfNamespaceImport(node); + case 230: + return getTargetOfImportSpecifier(node); + case 234: + return getTargetOfExportSpecifier(node); + case 231: return getTargetOfExportAssignment(node); } } @@ -12007,10 +13104,10 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 227) { + if (node.kind === 231) { checkExpressionCached(node.expression); } - else if (node.kind === 230) { + else if (node.kind === 234) { checkExpressionCached(node.propertyName || node.name); } else if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -12020,17 +13117,17 @@ var ts; } function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 221); + importDeclaration = ts.getAncestor(entityName, 225); ts.Debug.assert(importDeclaration !== undefined); } if (entityName.kind === 69 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 69 || entityName.parent.kind === 135) { + if (entityName.kind === 69 || entityName.parent.kind === 137) { return resolveEntityName(entityName, 1536); } else { - ts.Debug.assert(entityName.parent.kind === 221); + ts.Debug.assert(entityName.parent.kind === 225); return resolveEntityName(entityName, 107455 | 793056 | 1536); } } @@ -12049,9 +13146,9 @@ var ts; return undefined; } } - else if (name.kind === 135 || name.kind === 166) { - var left = name.kind === 135 ? name.left : name.expression; - var right = name.kind === 135 ? name.right : name.name; + else if (name.kind === 137 || name.kind === 170) { + var left = name.kind === 137 ? name.left : name.expression; + var right = name.kind === 137 ? name.right : name.name; var namespace = resolveEntityName(left, 1536, ignoreErrors); if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) { return undefined; @@ -12071,11 +13168,13 @@ var ts; return symbol.flags & meaning ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError) { if (moduleReferenceExpression.kind !== 9) { return; } var moduleReferenceLiteral = moduleReferenceExpression; - var searchPath = ts.getDirectoryPath(getSourceFile(location).fileName); var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); if (moduleName === undefined) { return; @@ -12084,22 +13183,27 @@ var ts; if (!isRelative) { var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); if (symbol) { - return symbol; + return getMergedSymbol(symbol); } } - var resolvedModule = ts.getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReferenceLiteral.text); var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - return sourceFile.symbol; + return getMergedSymbol(sourceFile.symbol); } - error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - return; + if (moduleNotFoundError) { + error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; } - error(moduleReferenceLiteral, ts.Diagnostics.Cannot_find_module_0, moduleName); + if (moduleNotFoundError) { + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + } + return undefined; } function resolveExternalModuleSymbol(moduleSymbol) { - return moduleSymbol && resolveSymbol(moduleSymbol.exports["export="]) || moduleSymbol; + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports["export="])) || moduleSymbol; } function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression) { var symbol = resolveExternalModuleSymbol(moduleSymbol); @@ -12109,8 +13213,8 @@ var ts; } return symbol; } - function getExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports["export="]; + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports["export="] !== undefined; } function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); @@ -12122,35 +13226,58 @@ var ts; var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } - function extendExportSymbols(target, source) { + function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; + if (lookupTable && exportNode) { + lookupTable[id] = { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }; + } + } + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + if (!lookupTable[id].exportsWithDuplicate) { + lookupTable[id].exportsWithDuplicate = [exportNode]; + } + else { + lookupTable[id].exportsWithDuplicate.push(exportNode); + } } } } function getExportsForModule(moduleSymbol) { - var result; var visitedSymbols = []; - visit(moduleSymbol); - return result || moduleSymbol.exports; + return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { - if (symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol)) { - visitedSymbols.push(symbol); - if (symbol !== moduleSymbol) { - if (!result) { - result = cloneSymbolTable(moduleSymbol.exports); - } - extendExportSymbols(result, symbol.exports); - } - var exportStars = symbol.exports["__export"]; - if (exportStars) { - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - visit(resolveExternalModuleName(node, node.moduleSpecifier)); - } - } + if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { + return; } + visitedSymbols.push(symbol); + var symbols = cloneSymbolTable(symbol.exports); + var exportStars = symbol.exports["__export"]; + if (exportStars) { + var nestedSymbols = {}; + var lookupTable = {}; + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); + } + for (var id in lookupTable) { + var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + continue; + } + for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { + var node = exportsWithDuplicate_1[_b]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable[id].specifierText, id)); + } + } + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; } } function getMergedSymbol(symbol) { @@ -12184,14 +13311,15 @@ var ts; var members = node.members; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var member = members_1[_i]; - if (member.kind === 144 && ts.nodeIsPresent(member.body)) { + if (member.kind === 146 && ts.nodeIsPresent(member.body)) { return member; } } } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount++; + result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -12226,19 +13354,19 @@ var ts; } return result || emptyArray; } - function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { + function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; type.properties = getNamedMembers(members); type.callSignatures = callSignatures; type.constructSignatures = constructSignatures; - if (stringIndexType) - type.stringIndexType = stringIndexType; - if (numberIndexType) - type.numberIndexType = numberIndexType; + if (stringIndexInfo) + type.stringIndexInfo = stringIndexInfo; + if (numberIndexInfo) + type.numberIndexInfo = numberIndexInfo; return type; } - function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { - return setObjectTypeMembers(createObjectType(65536, symbol), members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setObjectTypeMembers(createObjectType(65536, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -12249,17 +13377,17 @@ var ts; } } switch (location_1.kind) { - case 248: - if (!ts.isExternalModule(location_1)) { + case 252: + if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 218: + case 222: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 214: - case 215: + case 218: + case 219: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -12292,7 +13420,7 @@ var ts; return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230)) { + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 234)) { if (!useOnlyExternalAliasing || ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); @@ -12321,7 +13449,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 234)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -12376,8 +13504,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 218 && declaration.name.kind === 9) || - (declaration.kind === 248 && ts.isExternalModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 252 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -12389,7 +13516,7 @@ var ts; if (!isDeclarationVisible(declaration)) { var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 2) && + !(anyImportSyntax.flags & 1) && isDeclarationVisible(anyImportSyntax.parent)) { getNodeLinks(declaration).isVisible = true; if (aliasesToMakeVisible) { @@ -12409,11 +13536,11 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 154) { + if (entityName.parent.kind === 156) { meaning = 107455 | 1048576; } - else if (entityName.kind === 135 || entityName.kind === 166 || - entityName.parent.kind === 221) { + else if (entityName.kind === 137 || entityName.kind === 170 || + entityName.parent.kind === 225) { meaning = 1536; } else { @@ -12443,9 +13570,9 @@ var ts; ts.releaseStringWriter(writer); return result; } - function signatureToString(signature, enclosingDeclaration, flags) { + function signatureToString(signature, enclosingDeclaration, flags, kind) { var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); var result = writer.string(); ts.releaseStringWriter(writer); return result; @@ -12461,18 +13588,39 @@ var ts; } return result; } + function typePredicateToString(typePredicate, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + return result; + } + function visibilityToString(flags) { + if (flags === 8) { + return "private"; + } + if (flags === 16) { + return "protected"; + } + return "public"; + } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048) { var node = type.symbol.declarations[0].parent; - while (node.kind === 160) { + while (node.kind === 162) { node = node.parent; } - if (node.kind === 216) { + if (node.kind === 220) { return getSymbolOfNode(node); } } return undefined; } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 223 && + ts.isExternalModuleAugmentation(node.parent.parent); + } function getSymbolDisplayBuilder() { function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { @@ -12481,10 +13629,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 186: + case 190: return "(Anonymous class)"; - case 173: - case 174: + case 177: + case 178: return "(Anonymous function)"; } } @@ -12575,7 +13723,7 @@ var ts; writeAnonymousType(type, flags); } else if (type.flags & 256) { - writer.writeStringLiteral(type.text); + writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } else { writePunctuation(writer, 15); @@ -12603,11 +13751,13 @@ var ts; } if (pos < end) { writePunctuation(writer, 25); - writeType(typeArguments[pos++], 0); + writeType(typeArguments[pos], 0); + pos++; while (pos < end) { writePunctuation(writer, 24); writeSpace(writer); - writeType(typeArguments[pos++], 0); + writeType(typeArguments[pos], 0); + pos++; } writePunctuation(writer, 27); } @@ -12626,12 +13776,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_3 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_4 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_3); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_4); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_3, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_4, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -12686,11 +13836,11 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 64; })); + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 32; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 248 || declaration.parent.kind === 219; + return declaration.parent.kind === 252 || declaration.parent.kind === 223; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return !!(flags & 2) || @@ -12703,17 +13853,38 @@ var ts; writeSpace(writer); buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); } - function getIndexerParameterName(type, indexKind, fallbackName) { - var declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); - if (!declaration) { - return fallbackName; + function writeIndexSignature(info, keyword) { + if (info) { + if (info.isReadonly) { + writeKeyword(writer, 127); + writeSpace(writer); + } + writePunctuation(writer, 19); + writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); + writePunctuation(writer, 54); + writeSpace(writer); + writeKeyword(writer, keyword); + writePunctuation(writer, 20); + writePunctuation(writer, 54); + writeSpace(writer); + writeType(info.type, 0); + writePunctuation(writer, 23); + writer.writeLine(); + } + } + function writePropertyWithModifiers(prop) { + if (isReadonlySymbol(prop)) { + writeKeyword(writer, 127); + writeSpace(writer); + } + buildSymbolDisplay(prop, writer); + if (prop.flags & 536870912) { + writePunctuation(writer, 53); } - ts.Debug.assert(declaration.parameters.length !== 0); - return ts.declarationNameToString(declaration.parameters[0].name); } function writeLiteralType(type, flags) { var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) { + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { writePunctuation(writer, 15); writePunctuation(writer, 16); @@ -12723,7 +13894,7 @@ var ts; if (flags & 64) { writePunctuation(writer, 17); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { writePunctuation(writer, 18); } @@ -12735,7 +13906,7 @@ var ts; } writeKeyword(writer, 92); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, symbolStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); if (flags & 64) { writePunctuation(writer, 18); } @@ -12749,44 +13920,18 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - writeKeyword(writer, 92); - writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); - writePunctuation(writer, 23); - writer.writeLine(); - } - if (resolved.stringIndexType) { - writePunctuation(writer, 19); - writer.writeParameter(getIndexerParameterName(resolved, 0, "x")); - writePunctuation(writer, 54); - writeSpace(writer); - writeKeyword(writer, 130); - writePunctuation(writer, 20); - writePunctuation(writer, 54); - writeSpace(writer); - writeType(resolved.stringIndexType, 0); - writePunctuation(writer, 23); - writer.writeLine(); - } - if (resolved.numberIndexType) { - writePunctuation(writer, 19); - writer.writeParameter(getIndexerParameterName(resolved, 1, "x")); - writePunctuation(writer, 54); - writeSpace(writer); - writeKeyword(writer, 128); - writePunctuation(writer, 20); - writePunctuation(writer, 54); - writeSpace(writer); - writeType(resolved.numberIndexType, 0); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } + writeIndexSignature(resolved.stringIndexInfo, 131); + writeIndexSignature(resolved.numberIndexInfo, 129); for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); @@ -12794,20 +13939,14 @@ var ts; var signatures = getSignaturesOfType(t, 0); for (var _f = 0, signatures_1 = signatures; _f < signatures_1.length; _f++) { var signature = signatures_1[_f]; - buildSymbolDisplay(p, writer); - if (p.flags & 536870912) { - writePunctuation(writer, 53); - } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + writePropertyWithModifiers(p); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); writePunctuation(writer, 23); writer.writeLine(); } } else { - buildSymbolDisplay(p, writer); - if (p.flags & 536870912) { - writePunctuation(writer, 53); - } + writePropertyWithModifiers(p); writePunctuation(writer, 54); writeSpace(writer); writeType(t, 0); @@ -12820,10 +13959,10 @@ var ts; inObjectTypeLiteral = saveInObjectTypeLiteral; } } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaraiton, flags) { + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { var targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); } } function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { @@ -12886,6 +14025,18 @@ var ts; } writePunctuation(writer, 18); } + function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 97); + } + writeSpace(writer); + writeKeyword(writer, 124); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8) { writeSpace(writer); @@ -12895,20 +14046,19 @@ var ts; writePunctuation(writer, 54); } writeSpace(writer); - var returnType; if (signature.typePredicate) { - writer.writeParameter(signature.typePredicate.parameterName); - writeSpace(writer); - writeKeyword(writer, 124); - writeSpace(writer); - returnType = signature.typePredicate.type; + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); } else { - returnType = getReturnTypeOfSignature(signature); + var returnType = getReturnTypeOfSignature(signature); + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1) { + writeKeyword(writer, 92); + writeSpace(writer); + } if (signature.target && (flags & 32)) { buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); } @@ -12922,6 +14072,7 @@ var ts; buildSymbolDisplay: buildSymbolDisplay, buildTypeDisplay: buildTypeDisplay, buildTypeParameterDisplay: buildTypeParameterDisplay, + buildTypePredicateDisplay: buildTypePredicateDisplay, buildParameterDisplay: buildParameterDisplay, buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, @@ -12931,114 +14082,6 @@ var ts; }); } function isDeclarationVisible(node) { - function getContainingExternalModule(node) { - for (; node; node = node.parent) { - if (node.kind === 218) { - if (node.name.kind === 9) { - return node; - } - } - else if (node.kind === 248) { - return ts.isExternalModule(node) ? node : undefined; - } - } - ts.Debug.fail("getContainingModule cant reach here"); - } - function isUsedInExportAssignment(node) { - var externalModule = getContainingExternalModule(node); - var exportAssignmentSymbol; - var resolvedExportSymbol; - if (externalModule) { - var externalModuleSymbol = getSymbolOfNode(externalModule); - exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - var symbolOfNode = getSymbolOfNode(node); - if (isSymbolUsedInExportAssignment(symbolOfNode)) { - return true; - } - if (symbolOfNode.flags & 8388608) { - return isSymbolUsedInExportAssignment(resolveAlias(symbolOfNode)); - } - } - function isSymbolUsedInExportAssignment(symbol) { - if (exportAssignmentSymbol === symbol) { - return true; - } - if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608)) { - resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol); - if (resolvedExportSymbol === symbol) { - return true; - } - return ts.forEach(resolvedExportSymbol.declarations, function (current) { - while (current) { - if (current === node) { - return true; - } - current = current.parent; - } - }); - } - } - } - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 163: - return isDeclarationVisible(node.parent.parent); - case 211: - if (ts.isBindingPattern(node.name) && - !node.name.elements.length) { - return false; - } - case 218: - case 214: - case 215: - case 216: - case 213: - case 217: - case 221: - var parent_4 = getDeclarationContainer(node); - if (!(ts.getCombinedNodeFlags(node) & 2) && - !(node.kind !== 221 && parent_4.kind !== 248 && ts.isInAmbientContext(parent_4))) { - return isGlobalSourceFile(parent_4); - } - return isDeclarationVisible(parent_4); - case 141: - case 140: - case 145: - case 146: - case 143: - case 142: - if (node.flags & (16 | 32)) { - return false; - } - case 144: - case 148: - case 147: - case 149: - case 138: - case 219: - case 152: - case 153: - case 155: - case 151: - case 156: - case 157: - case 158: - case 159: - case 160: - return isDeclarationVisible(node.parent); - case 223: - case 224: - case 226: - return false; - case 137: - case 248: - return true; - case 227: - return false; - default: - ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); - } - } if (node) { var links = getNodeLinks(node); if (links.isVisible === undefined) { @@ -13046,13 +14089,77 @@ var ts; } return links.isVisible; } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 167: + return isDeclarationVisible(node.parent.parent); + case 215: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + return false; + } + case 222: + case 218: + case 219: + case 220: + case 217: + case 221: + case 225: + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent_5 = getDeclarationContainer(node); + if (!(ts.getCombinedNodeFlags(node) & 1) && + !(node.kind !== 225 && parent_5.kind !== 252 && ts.isInAmbientContext(parent_5))) { + return isGlobalSourceFile(parent_5); + } + return isDeclarationVisible(parent_5); + case 143: + case 142: + case 147: + case 148: + case 145: + case 144: + if (node.flags & (8 | 16)) { + return false; + } + case 146: + case 150: + case 149: + case 151: + case 140: + case 223: + case 154: + case 155: + case 157: + case 153: + case 158: + case 159: + case 160: + case 161: + case 162: + return isDeclarationVisible(node.parent); + case 227: + case 228: + case 230: + return false; + case 139: + case 252: + return true; + case 231: + return false; + default: + ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); + } + } } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 227) { + if (node.parent && node.parent.kind === 231) { exportSymbol = resolveName(node.parent, node.text, 107455 | 793056 | 1536 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 230) { + else if (node.parent.kind === 234) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -13074,7 +14181,9 @@ var ts; var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793056 | 1536, ts.Diagnostics.Cannot_find_name_0, firstIdentifier); - buildVisibleNodeList(importSymbol.declarations); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } } }); } @@ -13127,10 +14236,23 @@ var ts; } function getDeclarationContainer(node) { node = ts.getRootDeclaration(node); - return node.kind === 211 ? node.parent.parent.parent : node.parent; + while (node) { + switch (node.kind) { + case 215: + case 216: + case 230: + case 229: + case 228: + case 227: + node = node.parent; + break; + default: + return node.parent; + } + } } function getTypeOfPrototypeProperty(prototype) { - var classType = getDeclaredTypeOfSymbol(prototype.parent); + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; } function getTypeOfPropertyOfType(type, name) { @@ -13144,6 +14266,23 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); } + function getTextOfPropertyName(name) { + switch (name.kind) { + case 69: + return name.text; + case 9: + case 8: + return name.text; + case 138: + if (ts.isStringOrNumericLiteral(name.expression.kind)) { + return name.expression.text; + } + } + return undefined; + } + function isComputedNonLiteralName(name) { + return name.kind === 138 && !ts.isStringOrNumericLiteral(name.expression.kind); + } function getTypeForBindingElement(declaration) { var pattern = declaration.parent; var parentType = getTypeForBindingElementParent(pattern.parent); @@ -13157,13 +14296,17 @@ var ts; return parentType; } var type; - if (pattern.kind === 161) { - var name_11 = declaration.propertyName || declaration.name; - type = getTypeOfPropertyOfType(parentType, name_11.text) || - isNumericLiteralName(name_11.text) && getIndexTypeOfType(parentType, 1) || + if (pattern.kind === 165) { + var name_10 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_10)) { + return anyType; + } + var text = getTextOfPropertyName(name_10); + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11)); + error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10)); return unknownType; } } @@ -13190,11 +14333,44 @@ var ts; } return type; } - function getTypeForVariableLikeDeclaration(declaration) { - if (declaration.parent.parent.kind === 200) { - return anyType; + function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return getTypeFromTypeNode(jsDocType); } - if (declaration.parent.parent.kind === 201) { + } + function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + var typeTag = ts.getJSDocTypeTag(declaration); + if (typeTag && typeTag.typeExpression) { + return typeTag.typeExpression.type; + } + if (declaration.kind === 215 && + declaration.parent.kind === 216 && + declaration.parent.parent.kind === 197) { + var annotation = ts.getJSDocTypeTag(declaration.parent.parent); + if (annotation && annotation.typeExpression) { + return annotation.typeExpression.type; + } + } + else if (declaration.kind === 140) { + var paramTag = ts.getCorrespondingJSDocParameterTag(declaration); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type; + } + } + return undefined; + } + function getTypeForVariableLikeDeclaration(declaration) { + if (declaration.flags & 134217728) { + var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (type && type !== unknownType) { + return type; + } + } + if (declaration.parent.parent.kind === 204) { + return stringType; + } + if (declaration.parent.parent.kind === 205) { return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -13203,10 +14379,10 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 138) { + if (declaration.kind === 140) { var func = declaration.parent; - if (func.kind === 146 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 145); + if (func.kind === 148 && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 147); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } @@ -13219,7 +14395,7 @@ var ts; if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } - if (declaration.kind === 246) { + if (declaration.kind === 250) { return checkIdentifier(declaration.name); } if (ts.isBindingPattern(declaration.name)) { @@ -13238,10 +14414,16 @@ var ts; } function getTypeFromObjectBindingPattern(pattern, includePatternInType) { var members = {}; + var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { - var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); var name = e.propertyName || e.name; - var symbol = createSymbol(flags, name.text); + if (isComputedNonLiteralName(name)) { + hasComputedProperties = true; + return; + } + var text = getTextOfPropertyName(name); + var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); + var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; @@ -13250,6 +14432,9 @@ var ts; if (includePatternInType) { result.pattern = pattern; } + if (hasComputedProperties) { + result.flags |= 67108864; + } return result; } function getTypeFromArrayBindingPattern(pattern, includePatternInType) { @@ -13257,7 +14442,7 @@ var ts; if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } - var elementTypes = ts.map(elements, function (e) { return e.kind === 187 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return e.kind === 191 ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { var result = createNewTupleType(elementTypes); result.pattern = pattern; @@ -13266,7 +14451,7 @@ var ts; return createTupleType(elementTypes); } function getTypeFromBindingPattern(pattern, includePatternInType) { - return pattern.kind === 161 + return pattern.kind === 165 ? getTypeFromObjectBindingPattern(pattern, includePatternInType) : getTypeFromArrayBindingPattern(pattern, includePatternInType); } @@ -13276,12 +14461,15 @@ var ts; if (reportErrors) { reportErrorsFromWidening(declaration, type); } - return declaration.kind !== 245 ? getWidenedType(type) : type; + if (declaration.kind === 249) { + return type; + } + return getWidenedType(type); } type = declaration.dotDotDotToken ? anyArrayType : anyType; if (reportErrors && compilerOptions.noImplicitAny) { var root = ts.getRootDeclaration(declaration); - if (!isPrivateWithinAmbient(root) && !(root.kind === 138 && isPrivateWithinAmbient(root.parent))) { + if (!isPrivateWithinAmbient(root) && !(root.kind === 140 && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } } @@ -13294,12 +14482,20 @@ var ts; return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 244) { + if (declaration.parent.kind === 248) { return links.type = anyType; } - if (declaration.kind === 227) { + if (declaration.kind === 231) { return links.type = checkExpression(declaration.expression); } + if (declaration.kind === 185) { + return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + if (declaration.kind === 170) { + if (declaration.parent.kind === 185) { + return links.type = checkExpressionCached(declaration.parent.right); + } + } if (!pushTypeResolution(symbol, 0)) { return unknownType; } @@ -13322,7 +14518,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 145) { + if (accessor.kind === 147) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -13338,9 +14534,9 @@ var ts; if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var getter = ts.getDeclarationOfKind(symbol, 145); - var setter = ts.getDeclarationOfKind(symbol, 146); - var type; + var getter = ts.getDeclarationOfKind(symbol, 147); + var setter = ts.getDeclarationOfKind(symbol, 148); + var type = void 0; var getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { type = getterReturnType; @@ -13365,7 +14561,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 145); + var getter_1 = ts.getDeclarationOfKind(symbol, 147); 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)); } } @@ -13454,9 +14650,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 214 || node.kind === 186 || - node.kind === 213 || node.kind === 173 || - node.kind === 143 || node.kind === 174) { + if (node.kind === 218 || node.kind === 190 || + node.kind === 217 || node.kind === 177 || + node.kind === 145 || node.kind === 178) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -13465,15 +14661,15 @@ var ts; } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 215); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 219); return appendOuterTypeParameters(undefined, declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 215 || node.kind === 214 || - node.kind === 186 || node.kind === 216) { + if (node.kind === 219 || node.kind === 218 || + node.kind === 190 || node.kind === 220) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -13498,8 +14694,8 @@ var ts; 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); }); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); + signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; } @@ -13528,9 +14724,6 @@ var ts; } return type.resolvedBaseConstructorType; } - function hasClassBaseType(type) { - return !!ts.forEach(getBaseTypes(type), function (t) { return !!(t.symbol.flags & 32); }); - } function getBaseTypes(type) { var isClass = type.symbol.flags & 32; var isInterface = type.symbol.flags & 64; @@ -13549,17 +14742,19 @@ var ts; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - var baseContructorType = getBaseConstructorTypeOfClass(type); - if (!(baseContructorType.flags & 80896)) { + var baseConstructorType = getBaseConstructorTypeOfClass(type); + if (!(baseConstructorType.flags & 80896)) { return; } var baseTypeNode = getBaseTypeNodeOfClass(type); var baseType; - if (baseContructorType.symbol && baseContructorType.symbol.flags & 32) { - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol); + var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && + areAllOuterTypeParametersApplied(originalBaseType)) { + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol); } else { - var constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return; @@ -13584,11 +14779,20 @@ var ts; type.resolvedBaseTypes.push(baseType); } } + function areAllOuterTypeParametersApplied(type) { + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 219 && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -13617,8 +14821,8 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215) { - if (declaration.flags & 262144) { + if (declaration.kind === 219) { + if (declaration.flags & 16384) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); @@ -13655,7 +14859,7 @@ var ts; type.typeArguments = type.typeParameters; type.thisType = createType(512 | 33554432); type.thisType.symbol = symbol; - type.thisType.constraint = getTypeWithThisArgument(type); + type.thisType.constraint = type; } } return links.declaredType; @@ -13666,7 +14870,7 @@ var ts; if (!pushTypeResolution(symbol, 2)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 216); + var declaration = ts.getDeclarationOfKind(symbol, 220); var type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -13697,7 +14901,7 @@ var ts; if (!links.declaredType) { var type = createType(512); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 137).constraint) { + if (!ts.getDeclarationOfKind(symbol, 139).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -13744,16 +14948,16 @@ var ts; function isIndependentType(node) { switch (node.kind) { case 117: - case 130: - case 128: - case 120: case 131: + case 129: + case 120: + case 132: case 103: - case 9: + case 164: return true; - case 156: + case 158: return isIndependentType(node.elementType); - case 151: + case 153: return isIndependentTypeReference(node); } return false; @@ -13762,7 +14966,7 @@ var ts; return node.type && isIndependentType(node.type) || !node.type && !node.initializer; } function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 144 && (!node.type || !isIndependentType(node.type))) { + if (node.kind !== 146 && (!node.type || !isIndependentType(node.type))) { return false; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -13778,12 +14982,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 141: - case 140: - return isIndependentVariableLikeDeclaration(declaration); case 143: case 142: + return isIndependentVariableLikeDeclaration(declaration); + case 145: case 144: + case 146: return isIndependentFunctionLikeDeclaration(declaration); } } @@ -13814,22 +15018,14 @@ var ts; } } } - function addInheritedSignatures(signatures, baseSignatures) { - if (baseSignatures) { - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var signature = baseSignatures_1[_i]; - signatures.push(signature); - } - } - } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; type.declaredProperties = getNamedMembers(symbol.members); type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]); type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]); - type.declaredStringIndexType = getIndexTypeOfSymbol(symbol, 0); - type.declaredNumberIndexType = getIndexTypeOfSymbol(symbol, 1); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); } return type; } @@ -13844,15 +15040,15 @@ var ts; var members = source.symbol.members; var callSignatures = source.declaredCallSignatures; var constructSignatures = source.declaredConstructSignatures; - var stringIndexType = source.declaredStringIndexType; - var numberIndexType = source.declaredNumberIndexType; + var stringIndexInfo = source.declaredStringIndexInfo; + var numberIndexInfo = source.declaredNumberIndexInfo; if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); - stringIndexType = instantiateType(source.declaredStringIndexType, mapper); - numberIndexType = instantiateType(source.declaredNumberIndexType, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } var baseTypes = getBaseTypes(source); if (baseTypes.length) { @@ -13866,11 +15062,11 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1)); - stringIndexType = stringIndexType || getIndexTypeOfType(instantiatedBaseType, 0); - numberIndexType = numberIndexType || getIndexTypeOfType(instantiatedBaseType, 1); + stringIndexInfo = stringIndexInfo || getIndexInfoOfType(instantiatedBaseType, 0); + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type) { resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); @@ -13898,17 +15094,17 @@ var ts; return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - if (!hasClassBaseType(classType)) { - return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; + } var baseTypeNode = getBaseTypeNodeOfClass(classType); var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { - var baseSig = baseSignatures_2[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -13933,12 +15129,12 @@ var ts; var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); var members = createTupleTypeMemberSymbols(type.elementTypes); addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); } function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreReturnTypes, compareTypesIdentical)) { return s; } } @@ -13989,73 +15185,71 @@ var ts; } return result || emptyArray; } - function getUnionIndexType(types, kind) { + function getUnionIndexInfo(types, kind) { var indexTypes = []; + var isAnyReadonly = false; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; - var indexType = getIndexTypeOfType(type, kind); - if (!indexType) { + var indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { return undefined; } - indexTypes.push(indexType); + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return getUnionType(indexTypes); + return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); } function resolveUnionTypeMembers(type) { var callSignatures = getUnionSignatures(type.types, 0); var constructSignatures = getUnionSignatures(type.types, 1); - var stringIndexType = getUnionIndexType(type.types, 0); - var numberIndexType = getUnionIndexType(type.types, 1); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + var stringIndexInfo = getUnionIndexInfo(type.types, 0); + var numberIndexInfo = getUnionIndexInfo(type.types, 1); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1, type2) { return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } function resolveIntersectionTypeMembers(type) { var callSignatures = emptyArray; var constructSignatures = emptyArray; - var stringIndexType = undefined; - var numberIndexType = undefined; + var stringIndexInfo = undefined; + var numberIndexInfo = undefined; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0)); constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(t, 1)); - stringIndexType = intersectTypes(stringIndexType, getIndexTypeOfType(t, 0)); - numberIndexType = intersectTypes(numberIndexType, getIndexTypeOfType(t, 1)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; - var members; - var callSignatures; - var constructSignatures; - var stringIndexType; - var numberIndexType; if (type.target) { - members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); - constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); - stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0), type.mapper); - numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1), type.mapper); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); + var callSignatures = instantiateList(getSignaturesOfType(type.target, 0), type.mapper, instantiateSignature); + var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1), type.mapper, instantiateSignature); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048) { - members = symbol.members; - callSignatures = getSignaturesOfSymbol(members["__call"]); - constructSignatures = getSignaturesOfSymbol(members["__new"]); - stringIndexType = getIndexTypeOfSymbol(symbol, 0); - numberIndexType = getIndexTypeOfSymbol(symbol, 1); + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members["__call"]); + var constructSignatures = getSignaturesOfSymbol(members["__new"]); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { - members = emptySymbols; - callSignatures = emptyArray; - constructSignatures = emptyArray; + var members = emptySymbols; + var constructSignatures = emptyArray; if (symbol.flags & 1952) { members = getExportsOfSymbol(symbol); } - if (symbol.flags & (16 | 8192)) { - callSignatures = getSignaturesOfSymbol(symbol); - } if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); @@ -14068,10 +15262,12 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } - stringIndexType = undefined; - numberIndexType = (symbol.flags & 384) ? stringType : undefined; + var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; + setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + if (symbol.flags & (16 | 8192)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -14130,14 +15326,19 @@ var ts; type = getApparentType(type); return type.flags & 49152 ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function getApparentTypeOfTypeParameter(type) { + if (!type.resolvedApparentType) { + var constraintType = getConstraintOfTypeParameter(type); + while (constraintType && constraintType.flags & 512) { + constraintType = getConstraintOfTypeParameter(constraintType); + } + type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); + } + return type.resolvedApparentType; + } function getApparentType(type) { if (type.flags & 512) { - do { - type = getConstraintOfTypeParameter(type); - } while (type && type.flags & 512); - if (!type) { - type = emptyObjectType; - } + type = getApparentTypeOfTypeParameter(type); } if (type.flags & 258) { type = globalStringType; @@ -14156,12 +15357,14 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; + var commonFlags = (containingType.flags & 32768) ? 536870912 : 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 | 32))) { + if (prop && !(getDeclarationFlagsFromSymbol(prop) & (8 | 16))) { + commonFlags &= prop.flags; if (!props) { props = [prop]; } @@ -14189,7 +15392,10 @@ var ts; } propTypes.push(getTypeOfSymbol(prop)); } - var result = createSymbol(4 | 67108864 | 268435456, name); + var result = createSymbol(4 | + 67108864 | + 268435456 | + commonFlags, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & 16384 ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -14239,31 +15445,44 @@ var ts; function getSignaturesOfType(type, kind) { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function typeHasConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & (80896 | 16384)) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.constructSignatures.length > 0; - } - return false; - } - function typeHasCallOrConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & 130048) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; - } - return false; - } - function getIndexTypeOfStructuredType(type, kind) { + function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 130048) { var resolved = resolveStructuredTypeMembers(type); - return kind === 0 ? resolved.stringIndexType : resolved.numberIndexType; + return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } function getIndexTypeOfType(type, kind) { return getIndexTypeOfStructuredType(getApparentType(type), kind); } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectLiteralType(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.name)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + return getUnionType(propTypes); + } + return undefined; + } + function getTypeParametersFromJSDocTemplate(declaration) { + if (declaration.flags & 134217728) { + var templateTag = ts.getJSDocTemplateTag(declaration); + if (templateTag) { + return getTypeParametersFromDeclaration(templateTag.typeParameters); + } + } + return undefined; + } function getTypeParametersFromDeclaration(typeParameterDeclarations) { var result = []; ts.forEach(typeParameterDeclarations, function (node) { @@ -14284,33 +15503,73 @@ var ts; return result; } function isOptionalParameter(node) { + if (node.flags & 134217728) { + if (node.type && node.type.kind === 264) { + return true; + } + var paramTag = ts.getCorrespondingJSDocParameterTag(node); + if (paramTag) { + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 264; + } + } + } if (ts.hasQuestionToken(node)) { return true; } if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = signatureDeclaration.parameters.indexOf(node); + var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } return false; } + function createTypePredicateFromTypePredicateNode(node) { + if (node.parameterName.kind === 69) { + var parameterName = node.parameterName; + return { + kind: 1, + parameterName: parameterName ? parameterName.text : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0, + type: getTypeFromTypeNode(node.type) + }; + } + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { - var classType = declaration.kind === 144 ? + var classType = declaration.kind === 146 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; + declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : + getTypeParametersFromJSDocTemplate(declaration); var parameters = []; var hasStringLiterals = false; var minArgumentCount = -1; - for (var i = 0, n = declaration.parameters.length; i < n; i++) { + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var returnType = undefined; + var typePredicate = undefined; + for (var i = isJSConstructSignature ? 1 : 0, n = declaration.parameters.length; i < n; i++) { var param = declaration.parameters[i]; - parameters.push(param.symbol); - if (param.type && param.type.kind === 9) { + var paramSymbol = param.symbol; + if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.name, 107455, undefined, undefined); + paramSymbol = resolvedSymbol; + } + parameters.push(paramSymbol); + if (param.type && param.type.kind === 164) { hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken) { @@ -14325,25 +15584,28 @@ var ts; if (minArgumentCount < 0) { minArgumentCount = declaration.parameters.length; } - var returnType; - var typePredicate; - if (classType) { + if (isJSConstructSignature) { + minArgumentCount--; + returnType = getTypeFromTypeNode(declaration.parameters[0].type); + } + else if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); - if (declaration.type.kind === 150) { - 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) - }; + if (declaration.type.kind === 152) { + typePredicate = createTypePredicateFromTypePredicateNode(declaration.type); } } else { - if (declaration.kind === 145 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 146); + if (declaration.flags & 134217728) { + var type = getReturnTypeFromJSDocComment(declaration); + if (type && type !== unknownType) { + returnType = type; + } + } + if (declaration.kind === 147 && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 148); returnType = getAnnotatedAccessorType(setter); } if (!returnType && ts.nodeIsMissing(declaration.body)) { @@ -14361,19 +15623,20 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 152: - case 153: - case 213: - case 143: - case 142: + case 154: + case 155: + case 217: + case 145: case 144: + case 146: + case 149: + case 150: + case 151: case 147: case 148: - case 149: - case 145: - case 146: - case 173: - case 174: + case 177: + case 178: + case 265: if (i > 0 && node.body) { var previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { @@ -14385,12 +15648,22 @@ var ts; } return result; } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3)) { return unknownType; } - var type; + var type = void 0; if (signature.target) { type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } @@ -14443,7 +15716,7 @@ var ts; } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 144 || signature.declaration.kind === 148; + var isConstructor = signature.declaration.kind === 146 || signature.declaration.kind === 150; var type = createObjectType(65536 | 262144); type.members = emptySymbols; type.properties = emptyArray; @@ -14457,7 +15730,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 128 : 130; + var syntaxKind = kind === 1 ? 129 : 131; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -14473,26 +15746,51 @@ var ts; } return undefined; } - function getIndexTypeOfSymbol(symbol, kind) { - var declaration = getIndexDeclarationOfSymbol(symbol, kind); - return declaration - ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType - : undefined; + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; } - function getConstraintOfTypeParameter(type) { - if (!type.constraint) { - if (type.target) { - var targetConstraint = getConstraintOfTypeParameter(type.target); - type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (declaration.flags & 64) !== 0, declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 139).constraint; + } + function hasConstraintReferenceTo(type, target) { + var checked; + while (type && !(type.flags & 33554432) && type.flags & 512 && !ts.contains(checked, type)) { + if (type === target) { + return true; + } + (checked || (checked = [])).push(type); + var constraintDeclaration = getConstraintDeclaration(type); + type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration); + } + return false; + } + function getConstraintOfTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 137).constraint); + var constraintDeclaration = getConstraintDeclaration(typeParameter); + var constraint = getTypeFromTypeNode(constraintDeclaration); + if (hasConstraintReferenceTo(constraint, typeParameter)) { + error(constraintDeclaration, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + constraint = unknownType; + } + typeParameter.constraint = constraint; } } - return type.constraint === noConstraintType ? undefined : type.constraint; + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 137).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 139).parent); } function getTypeListId(types) { if (types) { @@ -14533,40 +15831,6 @@ var ts; } return type; } - function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode, typeParameterSymbol) { - var links = getNodeLinks(typeReferenceNode); - if (links.isIllegalTypeReferenceInConstraint !== undefined) { - return links.isIllegalTypeReferenceInConstraint; - } - var currentNode = typeReferenceNode; - while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { - currentNode = currentNode.parent; - } - links.isIllegalTypeReferenceInConstraint = currentNode.kind === 137; - return links.isIllegalTypeReferenceInConstraint; - } - function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { - var typeParameterSymbol; - function check(n) { - if (n.kind === 151 && n.typeName.kind === 69) { - 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; }); - } - } - if (links.isIllegalTypeReferenceInConstraint) { - error(typeParameter, ts.Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); - } - } - ts.forEachChild(n, check); - } - if (typeParameter.constraint) { - typeParameterSymbol = getSymbolOfNode(typeParameter); - check(typeParameter.constraint); - } - } function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(symbol); var typeParameters = type.localTypeParameters; @@ -14603,26 +15867,68 @@ var ts; 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 getTypeReferenceName(node) { + switch (node.kind) { + case 153: + return node.typeName; + case 263: + return node.name; + case 192: + if (ts.isSupportedExpressionWithTypeArguments(node)) { + return node.expression; + } + } + return undefined; + } + function resolveTypeReferenceName(node, typeReferenceName) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, 793056) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + if (symbol === unknownSymbol) { + return unknownType; + } + if (symbol.flags & (32 | 64)) { + return getTypeFromClassOrInterfaceReference(node, symbol); + } + if (symbol.flags & 524288) { + return getTypeFromTypeAliasReference(node, symbol); + } + if (symbol.flags & 107455 && node.kind === 263) { + return getTypeOfSymbol(symbol); + } + return getTypeFromNonGenericTypeReference(node, symbol); + } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - var typeNameOrExpression = node.kind === 151 ? 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); + var symbol = void 0; + var type = void 0; + if (node.kind === 263) { + var typeReferenceName = getTypeReferenceName(node); + symbol = resolveTypeReferenceName(node, typeReferenceName); + type = getTypeReferenceType(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + else { + var typeNameOrExpression = node.kind === 153 ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056) || unknownSymbol; + 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; } @@ -14641,9 +15947,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 214: - case 215: - case 217: + case 218: + case 219: + case 221: return declaration; } } @@ -14675,10 +15981,6 @@ var ts; if (arity === void 0) { arity = 0; } return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } - function tryGetGlobalType(name, arity) { - if (arity === void 0) { arity = 0; } - return getTypeOfGlobalSymbol(getGlobalSymbol(name, 793056, undefined), arity); - } function getExportedTypeFromNamespace(namespace, name) { var namespaceSymbol = getGlobalSymbol(namespace, 1536, undefined); var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056); @@ -14779,7 +16081,7 @@ var ts; } function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { - return emptyObjectType; + return emptyUnionType; } var typeSet = []; addTypesToSet(typeSet, types, 16384); @@ -14845,27 +16147,43 @@ var ts; } return links.resolvedType; } - function getStringLiteralType(node) { - if (ts.hasProperty(stringLiteralTypes, node.text)) { - return stringLiteralTypes[node.text]; + function getStringLiteralTypeForText(text) { + if (ts.hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; } - var type = stringLiteralTypes[node.text] = createType(256); - type.text = ts.getTextOfNode(node); + var type = stringLiteralTypes[text] = createType(256); + type.text = text; return type; } - function getTypeFromStringLiteral(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralType(node); + links.resolvedType = getStringLiteralTypeForText(node.text); + } + return links.resolvedType; + } + function getTypeFromJSDocVariadicType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + function getTypeFromJSDocTupleType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var types = ts.map(node.types, getTypeFromTypeNode); + links.resolvedType = createTupleType(types); } return links.resolvedType; } function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 215)) { - if (!(container.flags & 64) && - (container.kind !== 144 || ts.isNodeDescendentOf(node, container.body))) { + if (parent && (ts.isClassLike(parent) || parent.kind === 219)) { + if (!(container.flags & 32) && + (container.kind !== 146 || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -14882,47 +16200,63 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 117: + case 254: + case 255: return anyType; - case 130: + case 131: return stringType; - case 128: + case 129: return numberType; case 120: return booleanType; - case 131: + case 132: return esSymbolType; case 103: return voidType; - case 97: + case 163: return getTypeFromThisTypeNode(node); - case 9: - return getTypeFromStringLiteral(node); - case 151: - return getTypeFromTypeReference(node); - case 150: - return booleanType; - case 188: - return getTypeFromTypeReference(node); - case 154: - return getTypeFromTypeQueryNode(node); - case 156: - return getTypeFromArrayTypeNode(node); - case 157: - return getTypeFromTupleTypeNode(node); - case 158: - return getTypeFromUnionTypeNode(node); - case 159: - return getTypeFromIntersectionTypeNode(node); - case 160: - return getTypeFromTypeNode(node.type); - case 152: + case 164: + return getTypeFromStringLiteralTypeNode(node); case 153: + case 263: + return getTypeFromTypeReference(node); + case 152: + return booleanType; + case 192: + return getTypeFromTypeReference(node); + case 156: + return getTypeFromTypeQueryNode(node); + case 158: + case 256: + return getTypeFromArrayTypeNode(node); + case 159: + return getTypeFromTupleTypeNode(node); + case 160: + case 257: + return getTypeFromUnionTypeNode(node); + case 161: + return getTypeFromIntersectionTypeNode(node); + case 162: + case 259: + case 260: + case 267: + case 268: + case 264: + return getTypeFromTypeNode(node.type); + case 154: case 155: + case 157: + case 265: + case 261: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 69: - case 135: + case 137: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); + case 258: + return getTypeFromJSDocTupleType(node); + case 266: + return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -14979,18 +16313,22 @@ var ts; return t; }; } - function createInferenceMapper(context) { - var mapper = function (t) { - for (var i = 0; i < context.typeParameters.length; i++) { - if (t === context.typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); + function getInferenceMapper(context) { + if (!context.mapper) { + var mapper = function (t) { + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (t === typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } } - } - return t; - }; - mapper.context = context; - return mapper; + return t; + }; + mapper.context = context; + context.mapper = mapper; + } + return context.mapper; } function identityMapper(type) { return type; @@ -14998,31 +16336,41 @@ var ts; function combineTypeMappers(mapper1, mapper2) { return function (t) { return instantiateType(mapper1(t), mapper2); }; } - function instantiateTypeParameter(typeParameter, mapper) { + function cloneTypeParameter(typeParameter) { var result = createType(512); result.symbol = typeParameter.symbol; - if (typeParameter.constraint) { - result.constraint = instantiateType(typeParameter.constraint, mapper); + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; } else { - result.target = typeParameter; - result.mapper = mapper; + return { + kind: 0, + type: instantiateType(predicate.type, mapper) + }; } - return result; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } } if (signature.typePredicate) { - freshTypePredicate = { - parameterName: signature.typePredicate.parameterName, - parameterIndex: signature.typePredicate.parameterIndex, - type: instantiateType(signature.typePredicate.type, mapper) - }; + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; @@ -15085,28 +16433,31 @@ var ts; } return type; } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 173: - case 174: + case 177: + case 178: return isContextSensitiveFunctionLikeDeclaration(node); - case 165: + case 169: return ts.forEach(node.properties, isContextSensitive); - case 164: + case 168: return ts.forEach(node.elements, isContextSensitive); - case 182: + case 186: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 181: + case 185: return node.operatorToken.kind === 52 && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 245: + case 249: return isContextSensitive(node.initializer); - case 143: - case 142: + case 145: + case 144: return isContextSensitiveFunctionLikeDeclaration(node); - case 172: + case 176: return isContextSensitive(node.expression); } return false; @@ -15131,9 +16482,12 @@ var ts; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined); } - function compareTypes(source, target) { + function compareTypesIdentical(source, target) { return checkTypeRelatedTo(source, target, identityRelation, undefined) ? -1 : 0; } + function compareTypesAssignable(source, target) { + return checkTypeRelatedTo(source, target, assignableRelation, undefined) ? -1 : 0; + } function isTypeSubtypeOf(source, target) { return checkTypeSubtypeOf(source, target, undefined); } @@ -15146,10 +16500,116 @@ var ts; function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } - function isSignatureAssignableTo(source, target) { - var sourceType = getOrCreateTypeFromSignature(source); - var targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, undefined); + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; + } + function compareSignaturesRelated(source, target, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + if (source === target) { + return -1; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return 0; + } + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1; + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + var sourceParams = source.parameters; + var targetParams = target.parameters; + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(sourceParams[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(targetParams[i]) : getRestTypeOfSignature(target); + var related = compareTypes(t, s, false) || compareTypes(s, t, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name); + } + return 0; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return 0; + } + } + else { + result &= compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + if (source.kind === 1) { + var sourceIdentifierPredicate = source; + var targetIdentifierPredicate = target; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, undefined)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { var errorInfo; @@ -15159,18 +16619,12 @@ var ts; var expandingFlags; var depth = 0; var overflow = false; - var elaborateErrors = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, errorNode !== undefined, headMessage); + var result = isRelatedTo(source, target, !!errorNode, headMessage); if (overflow) { error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { - if (errorInfo.next === undefined) { - errorInfo = undefined; - elaborateErrors = true; - isRelatedTo(source, target, errorNode !== undefined, headMessage); - } if (containingMessageChain) { errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } @@ -15178,6 +16632,7 @@ var ts; } return result !== 0; function reportError(message, arg0, arg1, arg2) { + ts.Debug.assert(!!errorNode); errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } function reportRelationError(message, source, target) { @@ -15204,6 +16659,11 @@ var ts; return -1; if (source.flags & 128 && target === numberType) return -1; + if (source.flags & 128 && target.flags & 128) { + if (result = enumRelatedTo(source, target)) { + return result; + } + } if (source.flags & 256 && target === stringType) return -1; if (relation === assignableRelation) { @@ -15212,6 +16672,9 @@ var ts; if (source === numberType && target.flags & 128) return -1; } + if (source.flags & 8 && target.flags & 8) { + return -1; + } if (source.flags & 1048576) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -15263,10 +16726,10 @@ var ts; return result; } } - var apparentType = getApparentType(source); - if (apparentType.flags & (80896 | 32768) && target.flags & 80896) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; - if (result = objectTypeRelatedTo(apparentType, source, target, reportStructuralErrors)) { + var apparentSource = getApparentType(source); + if (apparentSource.flags & (80896 | 32768) && target.flags & 80896) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726); + if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; } @@ -15287,9 +16750,6 @@ var ts; } return objectTypeRelatedTo(source, source, target, false); } - if (source.flags & 512 && target.flags & 512) { - return typeParameterIdenticalTo(source, target); - } if (source.flags & 16384 && target.flags & 16384 || source.flags & 32768 && target.flags & 32768) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -15304,7 +16764,7 @@ var ts; if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if (relation === assignableRelation && (type === globalObjectType || resolved.properties.length === 0) || - resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) { + resolved.stringIndexInfo || resolved.numberIndexInfo || getPropertyOfType(type, name)) { return true; } } @@ -15319,11 +16779,12 @@ var ts; return false; } function hasExcessProperties(source, target, reportErrors) { - if (someConstituentTypeHasKind(target, 80896)) { + if (!(target.flags & 67108864) && maybeTypeOfKind(target, 80896)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { if (reportErrors) { + ts.Debug.assert(!!errorNode); errorNode = prop.valueDeclaration; reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } @@ -15398,8 +16859,9 @@ var ts; if (sources.length !== targets.length && relation === identityRelation) { return 0; } + var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1; - for (var i = 0; i < targets.length; i++) { + for (var i = 0; i < length; i++) { var related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return 0; @@ -15408,26 +16870,17 @@ var ts; } return result; } - function typeParameterIdenticalTo(source, target) { - if (source.symbol.name !== target.symbol.name) { - return 0; - } - if (source.constraint === target.constraint) { - return -1; - } - if (source.constraint === noConstraintType || target.constraint === noConstraintType) { - return 0; - } - return isIdenticalTo(source.constraint, target.constraint); - } - function objectTypeRelatedTo(apparentSource, originalSource, target, reportErrors) { + function objectTypeRelatedTo(source, originalSource, target, reportErrors) { if (overflow) { return 0; } - var id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { - if (!elaborateErrors || (related === 3)) { + if (reportErrors && related === 2) { + relation[id] = 3; + } + else { return related === 1 ? -1 : 0; } } @@ -15448,13 +16901,13 @@ var ts; maybeStack = []; expandingFlags = 0; } - sourceStack[depth] = apparentSource; + sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; maybeStack[depth][id] = 1; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; @@ -15463,15 +16916,15 @@ var ts; result = 1; } else { - result = propertiesRelatedTo(apparentSource, target, reportErrors); + result = propertiesRelatedTo(source, target, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 0, reportErrors); + result &= signaturesRelatedTo(source, target, 0, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 1, reportErrors); + result &= signaturesRelatedTo(source, target, 1, reportErrors); if (result) { - result &= stringIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= indexTypesRelatedTo(source, originalSource, target, 0, reportErrors); if (result) { - result &= numberIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= indexTypesRelatedTo(source, originalSource, target, 1, reportErrors); } } } @@ -15511,23 +16964,23 @@ var ts; else if (!(targetProp.flags & 134217728)) { var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); - if (sourcePropFlags & 16 || targetPropFlags & 16) { + if (sourcePropFlags & 8 || targetPropFlags & 8) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & 16 && targetPropFlags & 16) { + if (sourcePropFlags & 8 && targetPropFlags & 8) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 16 ? source : target), typeToString(sourcePropFlags & 16 ? target : source)); + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 ? source : target), typeToString(sourcePropFlags & 8 ? target : source)); } } return 0; } } - else if (targetPropFlags & 32) { + else if (targetPropFlags & 16) { var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; - var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); + var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; + var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); @@ -15535,7 +16988,7 @@ var ts; return 0; } } - else if (sourcePropFlags & 32) { + else if (sourcePropFlags & 16) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -15593,140 +17046,41 @@ var ts; } var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 && sourceSignatures.length && targetSignatures.length) { + if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0; + } + } var result = -1; var saveErrorInfo = errorInfo; - if (kind === 1) { - var sourceSig = sourceSignatures[0]; - var targetSig = targetSignatures[0]; - result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); - if (result !== -1) { - return result; - } - } outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; - if (!t.hasStringLiterals || target.flags & 262144) { - var localErrors = reportErrors; - var checkedAbstractAssignability = false; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - if (!s.hasStringLiterals || source.flags & 262144) { - var related = signatureRelatedTo(s, t, localErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; - } - localErrors = false; - } + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; } - return 0; + shouldElaborateErrors = false; } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } return result; - function abstractSignatureRelatedTo(source, sourceSig, target, targetSig) { - if (sourceSig && targetSig) { - var sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - var targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); - if (!sourceDecl) { - return -1; - } - var sourceErasedSignature = getErasedSignature(sourceSig); - var targetErasedSignature = getErasedSignature(targetSig); - var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128; - if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0; - } - } - return -1; - } } function signatureRelatedTo(source, target, reportErrors) { - if (source === target) { - return -1; - } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return 0; - } - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var checkCount; - if (source.hasRestParameter && target.hasRestParameter) { - checkCount = sourceMax > targetMax ? sourceMax : targetMax; - sourceMax--; - targetMax--; - } - else if (source.hasRestParameter) { - sourceMax--; - checkCount = targetMax; - } - else if (target.hasRestParameter) { - targetMax--; - checkCount = sourceMax; - } - else { - checkCount = sourceMax < targetMax ? sourceMax : targetMax; - } - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1; - for (var i = 0; i < checkCount; i++) { - var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); - var saveErrorInfo = errorInfo; - var related = isRelatedTo(s, t, reportErrors); - if (!related) { - related = isRelatedTo(t, s, false); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); - } - return 0; - } - errorInfo = saveErrorInfo; - } - 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 targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) - return result; - var sourceReturnType = getReturnTypeOfSignature(source); - return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); + return compareSignaturesRelated(source, target, false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -15735,8 +17089,8 @@ var ts; return 0; } var result = -1; - for (var i = 0, len = sourceSignatures.length; i < len; ++i) { - var related = compareSignatures(sourceSignatures[i], targetSignatures[i], false, false, isRelatedTo); + for (var i = 0, len = sourceSignatures.length; i < len; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, isRelatedTo); if (!related) { return 0; } @@ -15744,78 +17098,123 @@ var ts; } return result; } - function stringIndexTypesRelatedTo(source, originalSource, target, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(0, source, target); - } - var targetType = getIndexTypeOfType(target, 0); - if (targetType) { - if ((targetType.flags & 1) && !(originalSource.flags & 16777726)) { - return -1; - } - var sourceType = getIndexTypeOfType(source, 0); - if (!sourceType) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.name)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0; } - return 0; + result &= related; } - var related = isRelatedTo(sourceType, targetType, reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return 0; - } - return related; } - return -1; + return result; } - function numberIndexTypesRelatedTo(source, originalSource, target, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(1, source, target); + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); } - var targetType = getIndexTypeOfType(target, 1); - if (targetType) { - if ((targetType.flags & 1) && !(originalSource.flags & 16777726)) { - return -1; - } - var sourceStringType = getIndexTypeOfType(source, 0); - var sourceNumberType = getIndexTypeOfType(source, 1); - if (!(sourceStringType || sourceNumberType)) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); - } - return 0; - } - var related; - if (sourceStringType && sourceNumberType) { - related = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors); - } - else { - related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); - } - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return 0; - } - return related; - } - return -1; + return related; } - function indexTypesIdenticalTo(indexKind, source, target) { - var targetType = getIndexTypeOfType(target, indexKind); - var sourceType = getIndexTypeOfType(source, indexKind); - if (!sourceType && !targetType) { + function indexTypesRelatedTo(source, originalSource, target, kind, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || ((targetInfo.type.flags & 1) && !(originalSource.flags & 16777726))) { return -1; } - if (sourceType && targetType) { - return isRelatedTo(sourceType, targetType); + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 && getIndexInfoOfType(source, 0); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isObjectLiteralType(source)) { + var related = -1; + if (kind === 0) { + var sourceNumberInfo = getIndexInfoOfType(source, 1); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } return 0; } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0; + } + function enumRelatedTo(source, target) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & 128 || + target.symbol.flags & 128) { + return 0; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8)) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, undefined, 128)); + return 0; + } + } + } + return -1; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = sourceSignature.declaration.flags & (8 | 16); + var targetAccessibility = targetSignature.declaration.flags & (8 | 16); + if (targetAccessibility === 8) { + return true; + } + if (targetAccessibility === 16 && sourceAccessibility !== 8) { + return true; + } + if (targetAccessibility !== 16 && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function isAbstractConstructorType(type) { + if (type.flags & 65536) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && declaration.flags & 128) { + return true; + } + } + } + return false; } function isDeeplyNestedGeneric(type, stack, depth) { if (type.flags & (4096 | 131072) && depth >= 5) { @@ -15833,14 +17232,14 @@ var ts; return false; } function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypes) !== 0; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; } function compareProperties(sourceProp, targetProp, compareTypes) { if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (16 | 32); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (16 | 32); + var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (8 | 16); + var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (8 | 16); if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -15854,39 +17253,36 @@ var ts; return 0; } } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0; + } return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } - function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + function isMatchingSignature(source, target, partialMatch) { + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + function compareSignaturesIdentical(source, target, partialMatch, ignoreReturnTypes, compareTypes) { if (source === target) { return -1; } - if (source.parameters.length !== target.parameters.length || - source.minArgumentCount !== target.minArgumentCount || - source.hasRestParameter !== target.hasRestParameter) { - if (!partialMatch || - source.parameters.length < target.parameters.length && !source.hasRestParameter || - source.minArgumentCount > target.minArgumentCount) { - return 0; - } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0; } - var result = -1; - if (source.typeParameters && target.typeParameters) { - if (source.typeParameters.length !== target.typeParameters.length) { - return 0; - } - for (var i = 0, len = source.typeParameters.length; i < len; ++i) { - var related = compareTypes(source.typeParameters[i], target.typeParameters[i]); - if (!related) { - return 0; - } - result &= related; - } - } - else if (source.typeParameters || target.typeParameters) { + if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) { return 0; } source = getErasedSignature(source); target = getErasedSignature(target); + var result = -1; var targetLen = target.parameters.length; for (var i = 0; i < targetLen; i++) { var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); @@ -15947,14 +17343,23 @@ var ts; return type.flags & 4096 && type.target === globalArrayType; } function isArrayLikeType(type) { - return !(type.flags & (32 | 64)) && isTypeAssignableTo(type, anyArrayType); + return type.flags & 4096 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & (32 | 64)) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } + function isStringLiteralType(type) { + return type.flags & 256; + } function isTupleType(type) { return !!(type.flags & 8192); } + function isObjectLiteralType(type) { + return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && + getSignaturesOfType(type, 0).length === 0 && + getSignaturesOfType(type, 1).length === 0; + } function getRegularTypeOfObjectLiteral(type) { if (type.flags & 1048576) { var regularType = type.regularType; @@ -15965,8 +17370,8 @@ var ts; regularType.properties = type.properties; regularType.callSignatures = type.callSignatures; regularType.constructSignatures = type.constructSignatures; - regularType.stringIndexType = type.stringIndexType; - regularType.numberIndexType = type.numberIndexType; + regularType.stringIndexInfo = type.stringIndexInfo; + regularType.numberIndexInfo = type.numberIndexInfo; type.regularType = regularType; } return regularType; @@ -15991,13 +17396,9 @@ var ts; } members[p.name] = p; }); - var stringIndexType = getIndexTypeOfType(type, 0); - var numberIndexType = getIndexTypeOfType(type, 1); - if (stringIndexType) - stringIndexType = getWidenedType(stringIndexType); - if (numberIndexType) - numberIndexType = getWidenedType(numberIndexType); - return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); + var stringIndexInfo = getIndexInfoOfType(type, 0); + var numberIndexInfo = getIndexInfoOfType(type, 1); + return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedType(type) { if (type.flags & 6291456) { @@ -16058,22 +17459,22 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 141: - case 140: + case 143: + case 142: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 138: + case 140: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 213: - case 143: - case 142: + case 217: case 145: - case 146: - case 173: - case 174: + case 144: + case 147: + case 148: + case 177: + case 178: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -16119,13 +17520,7 @@ var ts; } } function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var unused = typeParameters_1[_i]; - inferences.push({ - primary: undefined, secondary: undefined, isFixed: false - }); - } + var inferences = ts.map(typeParameters, createTypeInferencesObject); return { typeParameters: typeParameters, inferUnionTypes: inferUnionTypes, @@ -16133,11 +17528,19 @@ var ts; inferredTypes: new Array(typeParameters.length) }; } + function createTypeInferencesObject() { + return { + primary: undefined, + secondary: undefined, + isFixed: false + }; + } function inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; + var visited = {}; inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -16148,6 +17551,21 @@ var ts; return false; } function inferFromTypes(source, target) { + if (source.flags & 16384 && target.flags & 16384 || + source.flags & 32768 && target.flags & 32768) { + var matchingTypes = void 0; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (typeIdenticalToSomeType(t, source.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + } + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } if (target.flags & 512) { if (source.flags & 8388608) { return; @@ -16186,9 +17604,9 @@ var ts; else if (target.flags & 49152) { var targetTypes = target.types; var typeParameterCount = 0; - var typeParameter; - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var t = targetTypes_2[_i]; + var typeParameter = void 0; + for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { + var t = targetTypes_2[_b]; if (t.flags & 512 && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -16205,21 +17623,27 @@ var ts; } else if (source.flags & 49152) { var sourceTypes = source.types; - for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { - var sourceType = sourceTypes_3[_a]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 && (target.flags & (4096 | 8192) || - (target.flags & 65536) && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { + if (source.flags & 80896 && (target.flags & 4096 && target.typeArguments || + target.flags & 8192 || + target.flags & 65536 && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { if (isInProcess(source, target)) { return; } if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { return; } + var key = source.id + "," + target.id; + if (ts.hasProperty(visited, key)) { + return; + } + visited[key] = true; if (depth === 0) { sourceStack = []; targetStack = []; @@ -16230,9 +17654,7 @@ var ts; 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); + inferFromIndexTypes(source, target); depth--; } } @@ -16259,25 +17681,52 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - if (source.typePredicate && target.typePredicate) { - if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } } - function inferFromIndexTypes(source, target, sourceKind, targetKind) { - var targetIndexType = getIndexTypeOfType(target, targetKind); - if (targetIndexType) { - var sourceIndexType = getIndexTypeOfType(source, sourceKind); + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 0); if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetIndexType); + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1) || + getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 1); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); } } } } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 16384 ? getUnionType(reducedTypes, true) : getIntersectionType(reducedTypes); + } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; @@ -16296,14 +17745,19 @@ var ts; inferredType = emptyObjectType; inferenceSucceeded = true; } + context.inferredTypes[index] = inferredType; if (inferenceSucceeded) { var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + context.inferredTypes[index] = inferredType = instantiatedConstraint; + } + } } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { context.failedTypeParameterIndex = index; } - context.inferredTypes[index] = inferredType; } return inferredType; } @@ -16313,9 +17767,6 @@ var ts; } return context.inferredTypes; } - function hasAncestor(node, kind) { - return ts.getAncestor(node, kind) !== undefined; - } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { @@ -16326,10 +17777,10 @@ var ts; function isInTypeQuery(node) { while (node) { switch (node.kind) { - case 154: + case 156: return true; case 69: - case 135: + case 137: node = node.parent; continue; default: @@ -16338,21 +17789,6 @@ var ts; } ts.Debug.fail("should not get here"); } - function removeTypesFromUnionType(type, typeKind, isOfTypeKind, allowEmptyUnionResult) { - if (type.flags & 16384) { - var types = type.types; - if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { - var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); - if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { - return narrowedType; - } - } - } - else if (allowEmptyUnionResult && !!(type.flags & typeKind) === isOfTypeKind) { - return getUnionType(emptyArray); - } - return type; - } function hasInitializer(node) { return !!(node.initializer || ts.isBindingPattern(node.parent) && hasInitializer(node.parent.parent)); } @@ -16370,10 +17806,7 @@ var ts; return links.assignmentChecks[symbol.id] = isAssignedIn(node); function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 56 && node.operatorToken.kind <= 68) { - var n = node.left; - while (n.kind === 172) { - n = n.expression; - } + var n = skipParenthesizedNodes(node.left); if (n.kind === 69 && getResolvedSymbol(n) === symbol) { return true; } @@ -16388,55 +17821,55 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 181: + case 185: return isAssignedInBinaryExpression(node); - case 211: - case 163: + case 215: + case 167: return isAssignedInVariableDeclaration(node); - case 161: - case 162: - case 164: case 165: case 166: - case 167: case 168: case 169: + case 170: case 171: - case 189: case 172: - case 179: + case 173: case 175: - case 178: - case 176: - case 177: - case 180: - case 184: - case 182: - case 185: - case 192: case 193: - case 195: + case 176: + case 183: + case 179: + case 182: + case 180: + case 181: + case 184: + case 188: + case 186: + case 189: case 196: case 197: - case 198: case 199: case 200: case 201: + case 202: + case 203: case 204: case 205: - case 206: - case 241: - case 242: - case 207: case 208: case 209: - case 244: - case 233: - case 234: + case 210: + case 245: + case 246: + case 211: + case 212: + case 213: + case 248: + case 237: case 238: + case 242: + case 243: case 239: - case 235: - case 240: + case 244: return ts.forEachChild(node, isAssignedIn); } return false; @@ -16446,53 +17879,66 @@ var ts; var type = getTypeOfSymbol(symbol); if (node && symbol.flags & 3) { if (isTypeAny(type) || type.flags & (80896 | 16384 | 512)) { + var declaration = ts.getDeclarationOfKind(symbol, 215); + var top_1 = declaration && getDeclarationContainer(declaration); + var originalType = type; + var nodeStack = []; loop: while (node.parent) { var child = node; node = node.parent; - var narrowedType = type; switch (node.kind) { - case 196: - if (child !== node.expression) { - narrowedType = narrowType(type, node.expression, child === node.thenStatement); - } + case 200: + case 186: + case 185: + nodeStack.push({ node: node, child: child }); break; - case 182: - if (child !== node.condition) { - narrowedType = narrowType(type, node.condition, child === node.whenTrue); - } - break; - case 181: - if (child === node.right) { - if (node.operatorToken.kind === 51) { - narrowedType = narrowType(type, node.left, true); - } - else if (node.operatorToken.kind === 52) { - narrowedType = narrowType(type, node.left, false); - } - } - break; - case 248: - case 218: - case 213: - case 143: - case 142: - case 145: - case 146: - case 144: + case 252: + case 222: break loop; } - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; - } - type = narrowedType; + if (node === top_1) { + break; } } + var nodes = void 0; + while (nodes = nodeStack.pop()) { + var node_1 = nodes.node, child = nodes.child; + switch (node_1.kind) { + case 200: + if (child !== node_1.expression) { + type = narrowType(type, node_1.expression, child === node_1.thenStatement); + } + break; + case 186: + if (child !== node_1.condition) { + type = narrowType(type, node_1.condition, child === node_1.whenTrue); + } + break; + case 185: + if (child === node_1.right) { + if (node_1.operatorToken.kind === 51) { + type = narrowType(type, node_1.left, true); + } + else if (node_1.operatorToken.kind === 52) { + type = narrowType(type, node_1.left, false); + } + } + break; + default: + ts.Debug.fail("Unreachable!"); + } + if (type !== originalType && isVariableAssignedWithin(symbol, node_1)) { + type = originalType; + } + } + if (type === emptyUnionType) { + type = originalType; + } } } return type; function narrowTypeByEquality(type, expr, assumeTrue) { - if (expr.left.kind !== 176 || expr.right.kind !== 9) { + if (expr.left.kind !== 180 || expr.right.kind !== 9) { return type; } var left = expr.left; @@ -16500,24 +17946,30 @@ var ts; if (left.expression.kind !== 69 || getResolvedSymbol(left.expression) !== symbol) { return type; } - var typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === 33) { assumeTrue = !assumeTrue; } - if (assumeTrue) { - if (!typeInfo) { - return removeTypesFromUnionType(type, 258 | 132 | 8 | 16777216, true, false); - } - if (isTypeSubtypeOf(typeInfo.type, type)) { - return typeInfo.type; - } - return removeTypesFromUnionType(type, typeInfo.flags, false, false); + var typeInfo = primitiveTypeInfo[right.text]; + if (typeInfo && typeInfo.type === undefinedType) { + return type; + } + var flags; + if (typeInfo) { + flags = typeInfo.flags; } else { - if (typeInfo) { - return removeTypesFromUnionType(type, typeInfo.flags, true, false); + assumeTrue = !assumeTrue; + flags = 132 | 258 | 16777216 | 8; + } + if (!(type.flags & 16384)) { + if (assumeTrue && typeInfo && isTypeSubtypeOf(typeInfo.type, type)) { + return typeInfo.type; } - return type; + return filterUnion(type) ? type : emptyUnionType; + } + return getUnionType(ts.filter(type.types, filterUnion), true); + function filterUnion(type) { + return assumeTrue === !!(type.flags & flags); } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -16527,7 +17979,7 @@ var ts; else { return getUnionType([ narrowType(type, expr.left, false), - narrowType(narrowType(type, expr.left, true), expr.right, false) + narrowType(type, expr.right, false) ]); } } @@ -16535,7 +17987,7 @@ var ts; if (assumeTrue) { return getUnionType([ narrowType(type, expr.left, true), - narrowType(narrowType(type, expr.left, false), expr.right, true) + narrowType(type, expr.right, true) ]); } else { @@ -16543,7 +17995,7 @@ var ts; } } function narrowTypeByInstanceof(type, expr, assumeTrue) { - if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 69 || getResolvedSymbol(expr.left) !== symbol) { + if (isTypeAny(type) || expr.left.kind !== 69 || getResolvedSymbol(expr.left) !== symbol) { return type; } var rightType = checkExpression(expr.right); @@ -16559,7 +18011,7 @@ var ts; } } if (!targetType) { - var constructSignatures; + var constructSignatures = void 0; if (rightType.flags & 2048) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } @@ -16571,11 +18023,17 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType); + return getNarrowedType(type, targetType, assumeTrue); } return type; } - function getNarrowedType(originalType, narrowedTypeCandidate) { + function getNarrowedType(originalType, narrowedTypeCandidate, assumeTrue) { + if (!assumeTrue) { + if (originalType.flags & 16384) { + return getUnionType(ts.filter(originalType.types, function (t) { return !isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } if (originalType.flags & 16384) { var assignableConstituents = ts.filter(originalType.types, function (t) { return isTypeAssignableTo(t, narrowedTypeCandidate); }); if (assignableConstituents.length) { @@ -16587,31 +18045,52 @@ var ts; } return originalType; } - function narrowTypeByTypePredicate(type, expr, assumeTrue) { + function narrowTypeByTypePredicate(type, callExpression, 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; + var signature = getResolvedSignature(callExpression); + var predicate = signature.typePredicate; + if (!predicate) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + if (callExpression.arguments[predicate.parameterIndex] && + getSymbolAtTypePredicatePosition(callExpression.arguments[predicate.parameterIndex]) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); } - return getNarrowedType(type, signature.typePredicate.type); + } + else { + var invokedExpression = skipParenthesizedNodes(callExpression.expression); + return narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue); } return type; } + function narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue) { + if (invokedExpression.kind === 171 || invokedExpression.kind === 170) { + var accessExpression = invokedExpression; + var possibleIdentifier = skipParenthesizedNodes(accessExpression.expression); + if (possibleIdentifier.kind === 69 && getSymbolAtTypePredicatePosition(possibleIdentifier) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); + } + } + return type; + } + function getSymbolAtTypePredicatePosition(expr) { + expr = skipParenthesizedNodes(expr); + switch (expr.kind) { + case 69: + case 170: + return getSymbolOfEntityNameOrPropertyAccessExpression(expr); + } + } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 168: - return narrowTypeByTypePredicate(type, expr, assumeTrue); case 172: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 176: return narrowType(type, expr.expression, assumeTrue); - case 181: + case 185: var operator = expr.operatorToken.kind; if (operator === 32 || operator === 33) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -16626,7 +18105,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 179: + case 183: if (expr.operator === 49) { return narrowType(type, expr.operand, !assumeTrue); } @@ -16635,27 +18114,47 @@ var ts; return type; } } + function skipParenthesizedNodes(expression) { + while (expression.kind === 176) { + expression = expression.expression; + } + return expression; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 174) { + if (container.kind === 178) { if (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 (node.parserContextFlags & 8) { - getNodeLinks(container).flags |= 4096; - getNodeLinks(node).flags |= 2048; + if (node.flags & 33554432) { + getNodeLinks(container).flags |= 8192; } } if (symbol.flags & 8388608 && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + if (languageVersion === 2 + && localOrExportSymbol.flags & 32 + && localOrExportSymbol.valueDeclaration.kind === 218 + && ts.nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { + getNodeLinks(container).flags |= 524288; + getNodeLinks(node).flags |= 1048576; + break; + } + container = ts.getContainingClass(container); + } + } checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); - checkBlockScopedBindingCapturedInLoop(node, symbol); - return getNarrowedTypeOfSymbol(getExportSymbolOfValueSymbolIfExported(symbol), node); + checkNestedBlockScopedBinding(node, symbol); + return getNarrowedTypeOfSymbol(localOrExportSymbol, node); } function isInsideFunction(node, threshold) { var current = node; @@ -16667,42 +18166,67 @@ var ts; } return false; } - function checkBlockScopedBindingCapturedInLoop(node, symbol) { + function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 244) { + symbol.valueDeclaration.parent.kind === 248) { return; } - var container; - if (symbol.flags & 32) { - container = getClassLikeDeclarationOfSymbol(symbol).parent; - } - else { - container = symbol.valueDeclaration; - while (container.kind !== 212) { - container = container.parent; - } - container = container.parent; - if (container.kind === 193) { - container = container.parent; - } - } - var inFunction = isInsideFunction(node.parent, container); + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); var current = container; + var containedInIterationStatement = false; while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { if (ts.isIterationStatement(current, false)) { - if (inFunction) { - getNodeLinks(current).flags |= 65536; - } - getNodeLinks(symbol.valueDeclaration).flags |= 16384; + containedInIterationStatement = true; break; } current = current.parent; } + if (containedInIterationStatement) { + if (usedInFunction) { + getNodeLinks(current).flags |= 65536; + } + if (container.kind === 203 && + ts.getAncestor(symbol.valueDeclaration, 216).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 2097152; + } + getNodeLinks(symbol.valueDeclaration).flags |= 262144; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 131072; + } + } + function isAssignedInBodyOfForStatement(node, container) { + var current = node; + while (current.parent.kind === 176) { + current = current.parent; + } + var isAssigned = false; + if (current.parent.kind === 185) { + isAssigned = current.parent.left === current && ts.isAssignmentOperator(current.parent.operatorToken.kind); + } + if ((current.parent.kind === 183 || current.parent.kind === 184)) { + var expr = current.parent; + isAssigned = expr.operator === 41 || expr.operator === 42; + } + if (!isAssigned) { + return false; + } + while (current !== container) { + if (current === container.statement) { + return true; + } + else { + current = current.parent; + } + } + return false; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2; - if (container.kind === 141 || container.kind === 144) { + if (container.kind === 143 || container.kind === 146) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } @@ -16710,32 +18234,65 @@ var ts; getNodeLinks(container).flags |= 4; } } + function findFirstSuperCall(n) { + if (ts.isSuperCallExpression(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullType; + } function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; - if (container.kind === 174) { + if (container.kind === 146) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + } + } + if (container.kind === 178) { container = ts.getThisContainer(container, false); needToCaptureLexicalThis = (languageVersion < 2); } switch (container.kind) { - case 218: + case 222: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 217: + case 221: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 144: + case 146: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 141: - case 140: - if (container.flags & 64) { + case 143: + case 142: + if (container.flags & 32) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 136: + case 138: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -16744,64 +18301,113 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - return container.flags & 64 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return container.flags & 32 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + } + if (ts.isInJavaScriptFile(node)) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + if (container.kind === 177) { + if (ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { + var className = container.parent + .left + .expression + .expression; + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { + return getInferredClassType(classSymbol); + } + } + } } return anyType; } + function getTypeForThisExpressionFromJSDoc(node) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === 265) { + var jsDocFunctionType = typeTag.typeExpression.type; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 268) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 138) { + if (n.kind === 140) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 168 && node.parent.expression === node; - var classDeclaration = ts.getContainingClass(node); - var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; + var isCallExpression = node.parent.kind === 172 && node.parent.expression === node; var container = ts.getSuperContainer(node, true); var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 174) { + while (container && container.kind === 178) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; - if (canUseSuperExpression) { - if ((container.flags & 64) || isCallExpression) { - nodeCheckFlag = 512; - } - else { - nodeCheckFlag = 256; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (needToCaptureLexicalThis) { - captureLexicalThis(node.parent, container); - } - } - if (!baseClassType) { - if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } if (!canUseSuperExpression) { - if (container && container.kind === 136) { + var current = node; + while (current && current !== container && current.kind !== 138) { + current = current.parent; + } + if (current && current.kind === 138) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 169)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } else { error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } return unknownType; } - if (container.kind === 144 && isInConstructorArgumentInitializer(node, container)) { + if ((container.flags & 32) || isCallExpression) { + nodeCheckFlag = 512; + } + else { + nodeCheckFlag = 256; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (container.kind === 145 && container.flags & 256) { + if (ts.isSuperPropertyOrElementAccess(node.parent) && isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096; + } + else { + getNodeLinks(container).flags |= 2048; + } + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 169) { + if (languageVersion < 2) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + return anyType; + } + } + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } + if (container.kind === 146 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; } @@ -16813,24 +18419,24 @@ var ts; return false; } if (isCallExpression) { - return container.kind === 144; + return container.kind === 146; } else { - if (container && ts.isClassLike(container.parent)) { - if (container.flags & 64) { - return container.kind === 143 || - container.kind === 142 || - container.kind === 145 || - container.kind === 146; + if (ts.isClassLike(container.parent) || container.parent.kind === 169) { + if (container.flags & 32) { + return container.kind === 145 || + container.kind === 144 || + container.kind === 147 || + container.kind === 148; } else { - return container.kind === 143 || + return container.kind === 145 || + container.kind === 144 || + container.kind === 147 || + container.kind === 148 || + container.kind === 143 || container.kind === 142 || - container.kind === 145 || - container.kind === 146 || - container.kind === 141 || - container.kind === 140 || - container.kind === 144; + container.kind === 146; } } } @@ -16865,7 +18471,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 138) { + if (declaration.kind === 140) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -16898,7 +18504,7 @@ var ts; } function isInParameterInitializerBeforeContainingFunction(node) { while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 138 && node.parent.initializer === node) { + if (node.parent.kind === 140 && node.parent.initializer === node) { return true; } node = node.parent; @@ -16907,8 +18513,8 @@ var ts; } function getContextualReturnType(functionDecl) { if (functionDecl.type || - functionDecl.kind === 144 || - functionDecl.kind === 145 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 146))) { + functionDecl.kind === 146 || + functionDecl.kind === 147 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 148))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); @@ -16927,7 +18533,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 170) { + if (template.parent.kind === 174) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -16947,6 +18553,11 @@ var ts; } return type; } + else if (operator === 51 || operator === 24) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } return undefined; } function applyToContextualType(type, mapper) { @@ -16956,8 +18567,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var current = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -16982,12 +18593,12 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } + function contextualTypeIsStringLiteralType(type) { + return !!(type.flags & 16384 ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); + } function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } - function contextualTypeHasIndexSignature(type, kind) { - return !!(type.flags & 16384 ? ts.forEach(type.types, function (t) { return getIndexTypeOfStructuredType(t, kind); }) : getIndexTypeOfStructuredType(type, kind)); - } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); if (isInsideWithStatementBody(node)) { @@ -16997,7 +18608,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element) { var objectLiteral = element.parent; - var type = getContextualType(objectLiteral); + var type = getApparentTypeOfContextualType(objectLiteral); if (type) { if (!ts.hasDynamicName(element)) { var symbolName = getSymbolOfNode(element).name; @@ -17013,7 +18624,7 @@ var ts; } function getContextualTypeForElementExpression(node) { var arrayLiteral = node.parent; - var type = getContextualType(arrayLiteral); + var type = getApparentTypeOfContextualType(arrayLiteral); if (type) { var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) @@ -17026,27 +18637,26 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForJsxExpression(expr) { - if (expr.parent.kind === 238) { - var attrib = expr.parent; - var attrsType = getJsxElementAttributesType(attrib.parent); + function getContextualTypeForJsxAttribute(attribute) { + var kind = attribute.kind; + var jsxElement = attribute.parent; + var attrsType = getJsxElementAttributesType(jsxElement); + if (attribute.kind === 242) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } - else { - return getTypeOfPropertyOfType(attrsType, attrib.name.text); - } + return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - if (expr.kind === 239) { - return getJsxElementAttributesType(expr.parent); + else if (attribute.kind === 243) { + return attrsType; } - return undefined; + ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); } - function getContextualType(node) { - var type = getContextualTypeWorker(node); + function getApparentTypeOfContextualType(node) { + var type = getContextualType(node); return type && getApparentType(type); } - function getContextualTypeWorker(node) { + function getContextualType(node) { if (isInsideWithStatementBody(node)) { return undefined; } @@ -17055,39 +18665,41 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 211: - case 138: - case 141: + case 215: case 140: - case 163: + case 143: + case 142: + case 167: return getContextualTypeForInitializerExpression(node); - case 174: - case 204: + case 178: + case 208: return getContextualTypeForReturnExpression(node); - case 184: + case 188: return getContextualTypeForYieldOperand(parent); - case 168: - case 169: - return getContextualTypeForArgument(parent, node); - case 171: - case 189: - return getTypeFromTypeNode(parent.type); - case 181: - return getContextualTypeForBinaryOperand(node); - case 245: - return getContextualTypeForObjectLiteralElement(parent); - case 164: - return getContextualTypeForElementExpression(node); - case 182: - return getContextualTypeForConditionalOperand(node); - case 190: - ts.Debug.assert(parent.parent.kind === 183); - return getContextualTypeForSubstitutionExpression(parent.parent, node); case 172: + case 173: + return getContextualTypeForArgument(parent, node); + case 175: + case 193: + return getTypeFromTypeNode(parent.type); + case 185: + return getContextualTypeForBinaryOperand(node); + case 249: + return getContextualTypeForObjectLiteralElement(parent); + case 168: + return getContextualTypeForElementExpression(node); + case 186: + return getContextualTypeForConditionalOperand(node); + case 194: + ts.Debug.assert(parent.parent.kind === 187); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 176: return getContextualType(parent); - case 240: - case 239: - return getContextualTypeForJsxExpression(parent); + case 244: + return getContextualType(parent); + case 242: + case 243: + return getContextualTypeForJsxAttribute(parent); } return undefined; } @@ -17101,7 +18713,7 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 173 || node.kind === 174; + return node.kind === 177 || node.kind === 178; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -17109,10 +18721,10 @@ var ts; : undefined; } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 || ts.isObjectLiteralMethod(node)); var type = ts.isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) - : getContextualType(node); + : getApparentTypeOfContextualType(node); if (!type) { return undefined; } @@ -17121,14 +18733,14 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { signatureList = [signature]; } - else if (!compareSignatures(signatureList[0], signature, false, true, compareTypes)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, compareTypesIdentical)) { return undefined; } else { @@ -17149,13 +18761,13 @@ var ts; } function isAssignmentTarget(node) { var parent = node.parent; - if (parent.kind === 181 && parent.operatorToken.kind === 56 && parent.left === node) { + if (parent.kind === 185 && parent.operatorToken.kind === 56 && parent.left === node) { return true; } - if (parent.kind === 245) { + if (parent.kind === 249) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 164) { + if (parent.kind === 168) { return isAssignmentTarget(parent); } return false; @@ -17165,8 +18777,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false); } function hasDefaultValue(node) { - return (node.kind === 163 && !!node.initializer) || - (node.kind === 181 && node.operatorToken.kind === 56); + return (node.kind === 167 && !!node.initializer) || + (node.kind === 185 && node.operatorToken.kind === 56); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -17175,7 +18787,7 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 185) { + if (inDestructuringPattern && e.kind === 189) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || (languageVersion >= 2 ? getElementTypeOfIterable(restArrayType, undefined) : undefined); @@ -17187,7 +18799,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 185; + hasSpreadElement = hasSpreadElement || e.kind === 189; } if (!hasSpreadElement) { if (inDestructuringPattern && elementTypes.length) { @@ -17195,10 +18807,10 @@ var ts; type.pattern = node; return type; } - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { var pattern = contextualType.pattern; - if (pattern && (pattern.kind === 162 || pattern.kind === 164)) { + if (pattern && (pattern.kind === 166 || pattern.kind === 168)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -17206,7 +18818,7 @@ var ts; elementTypes.push(contextualType.elementTypes[i]); } else { - if (patternElement.kind !== 187) { + if (patternElement.kind !== 191) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -17221,13 +18833,13 @@ var ts; return createArrayType(elementTypes.length ? getUnionType(elementTypes) : undefinedType); } function isNumericName(name) { - return name.kind === 136 ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 138 ? isNumericComputedName(name) : isNumericLiteralName(name.text); } function isNumericComputedName(name) { return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); + return isTypeAny(type) || isTypeOfKind(type, kind); } function isNumericLiteralName(name) { return (+name).toString() === name; @@ -17245,42 +18857,58 @@ var ts; } return links.resolvedType; } + function getObjectLiteralIndexInfo(node, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 || isNumericName(node.properties[i].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; + return createIndexInfo(unionType, false); + } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = {}; var propertiesArray = []; - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 161 || contextualType.pattern.kind === 165); + (contextualType.pattern.kind === 165 || contextualType.pattern.kind === 169); var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 245 || - memberDecl.kind === 246 || + if (memberDecl.kind === 249 || + memberDecl.kind === 250 || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 245) { + if (memberDecl.kind === 249) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 143) { + else if (memberDecl.kind === 145) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 246); + ts.Debug.assert(memberDecl.kind === 250); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; var prop = createSymbol(4 | 67108864 | member.flags, member.name); if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 245 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 246 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 249 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 250 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912; } + if (ts.hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } } - else if (contextualTypeHasPattern) { + else if (contextualTypeHasPattern && !(contextualType.flags & 67108864)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -17299,10 +18927,18 @@ var ts; member = prop; } else { - ts.Debug.assert(memberDecl.kind === 145 || memberDecl.kind === 146); + ts.Debug.assert(memberDecl.kind === 147 || memberDecl.kind === 148); checkAccessorDeclaration(memberDecl); } - if (!ts.hasDynamicName(memberDecl)) { + if (ts.hasDynamicName(memberDecl)) { + if (isNumericName(memberDecl.name)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + } + else { propertiesTable[member.name] = member; } propertiesArray.push(member); @@ -17319,66 +18955,33 @@ var ts; } } } - var stringIndexType = getIndexType(0); - var numberIndexType = getIndexType(1); - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); + result.flags |= 524288 | 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064) | (patternWithComputedProperties ? 67108864 : 0); if (inDestructuringPattern) { result.pattern = node; } return result; - function getIndexType(kind) { - if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { - var propTypes = []; - for (var i = 0; i < propertiesArray.length; i++) { - var propertyDecl = node.properties[i]; - if (kind === 0 || isNumericName(propertyDecl.name)) { - var type = getTypeOfSymbol(propertiesArray[i]); - if (!ts.contains(propTypes, type)) { - propTypes.push(type); - } - } - } - var result_1 = propTypes.length ? getUnionType(propTypes) : undefinedType; - typeFlags |= result_1.flags; - return result_1; - } - return undefined; - } } function checkJsxSelfClosingElement(node) { checkJsxOpeningLikeElement(node); return jsxElementType || anyType; } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 69) { - return lhs.text === rhs.text; - } - return lhs.right.text === rhs.right.text && - tagNamesAreEquivalent(lhs.left, rhs.left); - } function checkJsxElement(node) { checkJsxOpeningLikeElement(node.openingElement); - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - error(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNode(node.openingElement.tagName)); - } - else { - getJsxElementTagSymbol(node.closingElement); - } + getJsxTagSymbol(node.closingElement); for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 240: + case 244: checkJsxExpression(child); break; - case 233: + case 237: checkJsxElement(child); break; - case 234: + case 238: checkJsxSelfClosingElement(child); break; } @@ -17389,7 +18992,7 @@ var ts; return name.indexOf("-") < 0; } function isJsxIntrinsicIdentifier(tagName) { - if (tagName.kind === 135) { + if (tagName.kind === 137) { return false; } else { @@ -17446,74 +19049,49 @@ var ts; } return type; } - function getJsxIntrinsicElementsType() { - if (!jsxIntrinsicElementsType) { - jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType; + function getJsxType(name) { + if (jsxTypes[name] === undefined) { + return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType; } - return jsxIntrinsicElementsType; + return jsxTypes[name]; } - function getJsxElementTagSymbol(node) { - var flags = 8; + function getJsxTagSymbol(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicTagSymbol(node); + } + else { + return checkExpression(node.tagName).symbol; + } + } + function getIntrinsicTagSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - links.resolvedSymbol = lookupIntrinsicTag(node); - } - else { - links.resolvedSymbol = lookupClassTag(node); - } - } - return links.resolvedSymbol; - function lookupIntrinsicTag(node) { - var intrinsicElementsType = getJsxIntrinsicElementsType(); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); if (intrinsicProp) { links.jsxFlags |= 1; - return intrinsicProp; + return links.resolvedSymbol = intrinsicProp; } var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); if (indexSignatureType) { links.jsxFlags |= 2; - return intrinsicElementsType.symbol; + return links.resolvedSymbol = intrinsicElementsType.symbol; } error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.tagName.text, "JSX." + JsxNames.IntrinsicElements); - return unknownSymbol; + return links.resolvedSymbol = unknownSymbol; } else { if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); } + return links.resolvedSymbol = unknownSymbol; } } - function lookupClassTag(node) { - var valueSymbol = resolveJsxTagName(node); - if (valueSymbol && valueSymbol !== unknownSymbol) { - links.jsxFlags |= 4; - if (valueSymbol.flags & 8388608) { - markAliasSymbolAsReferenced(valueSymbol); - } - } - return valueSymbol || unknownSymbol; - } - function resolveJsxTagName(node) { - if (node.tagName.kind === 69) { - var tag = node.tagName; - var sym = getResolvedSymbol(tag); - return sym.exportSymbol || sym; - } - else { - return checkQualifiedName(node.tagName).symbol; - } - } + return links.resolvedSymbol; } function getJsxElementInstanceType(node) { - ts.Debug.assert(!!(getNodeLinks(node).jsxFlags & 4), "Should not call getJsxElementInstanceType on non-class Element"); - var classSymbol = getJsxElementTagSymbol(node); - if (classSymbol === unknownSymbol) { - return anyType; - } - var valueType = getTypeOfSymbol(classSymbol); + var valueType = checkExpression(node.tagName); if (isTypeAny(valueType)) { return anyType; } @@ -17525,12 +19103,7 @@ var ts; return unknownType; } } - var returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); - var elemClassType = getJsxGlobalElementClassType(); - if (elemClassType) { - checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - return returnType; + return getUnionType(signatures.map(getReturnTypeOfSignature)); } function getJsxElementPropertiesName() { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536, undefined); @@ -17556,9 +19129,35 @@ var ts; function getJsxElementAttributesType(node) { var links = getNodeLinks(node); if (!links.resolvedJsxType) { - var sym = getJsxElementTagSymbol(node); - if (links.jsxFlags & 4) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1) { + return links.resolvedJsxType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2) { + return links.resolvedJsxType = getIndexInfoOfSymbol(symbol, 0).type; + } + } + else { var elemInstanceType = getJsxElementInstanceType(node); + var elemClassType = getJsxGlobalElementClassType(); + if (!elemClassType || !isTypeAssignableTo(elemInstanceType, elemClassType)) { + var elemType = checkExpression(node.tagName); + var callSignatures = elemType && getSignaturesOfType(elemType, 0); + var callSignature = callSignatures && callSignatures.length > 0 && callSignatures[0]; + var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); + var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) { + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return links.resolvedJsxType = paramType; + } + } + if (elemClassType) { + checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } @@ -17577,24 +19176,33 @@ var ts; else if (isTypeAny(attributesType) || (attributesType === unknownType)) { return links.resolvedJsxType = attributesType; } - else if (!(attributesType.flags & 80896)) { - error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType)); + else if (attributesType.flags & 16384) { + error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return links.resolvedJsxType = anyType; } else { - return links.resolvedJsxType = attributesType; + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return links.resolvedJsxType = apparentAttributesType; } } } - else if (links.jsxFlags & 1) { - return links.resolvedJsxType = getTypeOfSymbol(sym); - } - else if (links.jsxFlags & 2) { - return links.resolvedJsxType = getIndexTypeOfSymbol(sym, 0); - } - else { - return links.resolvedJsxType = anyType; - } + return links.resolvedJsxType = unknownType; } return links.resolvedJsxType; } @@ -17610,7 +19218,7 @@ var ts; return jsxElementClassType; } function getJsxIntrinsicTagNames() { - var intrinsics = getJsxIntrinsicElementsType(); + var intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } function checkJsxPreconditions(errorNode) { @@ -17626,21 +19234,21 @@ var ts; function checkJsxOpeningLikeElement(node) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - if (compilerOptions.jsx === 2) { - var reactSym = resolveName(node.tagName, "React", 107455, ts.Diagnostics.Cannot_find_name_0, "React"); - if (reactSym) { - getSymbolLinks(reactSym).referenced = true; - } + var reactRefErr = compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = {}; var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 238) { + if (node.attributes[i].kind === 242) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 239); + ts.Debug.assert(node.attributes[i].kind === 243); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -17666,19 +19274,19 @@ var ts; } } function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 141; + return s.valueDeclaration ? s.valueDeclaration.kind : 143; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 8 | 64 : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; } function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationFlagsFromSymbol(prop); - var declaringClass = getDeclaredTypeOfSymbol(prop.parent); + var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); if (left.kind === 95) { - var errorNode = node.kind === 166 ? + var errorNode = node.kind === 170 ? node.name : node.right; - if (getDeclarationKindFromSymbol(prop) !== 143) { + if (languageVersion < 2 && getDeclarationKindFromSymbol(prop) !== 145) { error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } @@ -17687,12 +19295,12 @@ var ts; return false; } } - if (!(flags & (16 | 32))) { + if (!(flags & (8 | 16))) { return true; } var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; - if (flags & 16) { + if (flags & 8) { if (declaringClass !== enclosingClass) { error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; @@ -17706,7 +19314,7 @@ var ts; error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); return false; } - if (flags & 64) { + if (flags & 32) { return true; } if (type.flags & 33554432) { @@ -17747,7 +19355,7 @@ var ts; return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 166 + var left = node.kind === 170 ? node.expression : node.left; var type = checkExpression(left); @@ -17759,10 +19367,47 @@ var ts; } return true; } + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 216) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 69) { + return getResolvedSymbol(initializer); + } + return undefined; + } + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); + } + function isForInVariableForNumericPropertyNames(expr) { + var e = skipParenthesizedNodes(expr); + if (e.kind === 69) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 204 && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(checkExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } function checkIndexedAccess(node) { if (!node.argumentExpression) { - var sourceFile = getSourceFile(node); - if (node.parent.kind === 169 && node.parent.expression === node) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 173 && 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); @@ -17785,32 +19430,36 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_12 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_12 !== undefined) { - var prop = getPropertyOfType(objectType, name_12); + var name_11 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_11 !== undefined) { + var prop = getPropertyOfType(objectType, name_11); 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_12, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_11, symbolToString(objectType.symbol)); return unknownType; } } } if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 | 132 | 16777216)) { - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132)) { - var numberIndexType = getIndexTypeOfType(objectType, 1); - if (numberIndexType) { - return numberIndexType; + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + var numberIndexInfo = getIndexInfoOfType(objectType, 1); + if (numberIndexInfo) { + getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; + return numberIndexInfo.type; } } - var stringIndexType = getIndexTypeOfType(objectType, 0); - if (stringIndexType) { - return stringIndexType; + var stringIndexInfo = getIndexInfoOfType(objectType, 0); + if (stringIndexInfo) { + getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; + return stringIndexInfo.type; } if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); + error(node, getIndexTypeOfType(objectType, 1) ? + ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : + ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } return anyType; } @@ -17821,7 +19470,7 @@ var ts; if (indexArgumentExpression.kind === 9 || indexArgumentExpression.kind === 8) { return indexArgumentExpression.text; } - if (indexArgumentExpression.kind === 167 || indexArgumentExpression.kind === 166) { + if (indexArgumentExpression.kind === 171 || indexArgumentExpression.kind === 170) { var value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); @@ -17864,10 +19513,10 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 170) { + if (node.kind === 174) { checkExpression(node.template); } - else if (node.kind !== 139) { + else if (node.kind !== 141) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -17889,19 +19538,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_5 = signature.declaration && signature.declaration.parent; + var parent_6 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_5 === lastParent) { + if (lastParent && parent_6 === lastParent) { index++; } else { - lastParent = parent_5; + lastParent = parent_6; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_5; + lastParent = parent_6; } lastSymbol = symbol; if (signature.hasStringLiterals) { @@ -17918,7 +19567,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 185) { + if (arg && arg.kind === 189) { return i; } } @@ -17930,11 +19579,11 @@ var ts; var callIsIncomplete; var isDecorator; var spreadArgIndex = -1; - if (node.kind === 170) { + if (node.kind === 174) { var tagExpression = node; adjustedArgCount = args.length; typeArguments = undefined; - if (tagExpression.template.kind === 183) { + if (tagExpression.template.kind === 187) { var templateExpression = tagExpression.template; var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -17946,7 +19595,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 139) { + else if (node.kind === 141) { isDecorator = true; typeArguments = undefined; adjustedArgCount = getEffectiveArgumentCount(node, undefined, signature); @@ -17954,7 +19603,7 @@ var ts; else { var callExpression = node; if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 169); + ts.Debug.assert(callExpression.kind === 173); return signature.minArgumentCount === 0; } adjustedArgCount = callExpression.arguments.hasTrailingComma ? args.length + 1 : args.length; @@ -17980,7 +19629,7 @@ var ts; if (type.flags & 80896) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && - resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) { + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { return resolved.callSignatures[0]; } } @@ -17995,7 +19644,7 @@ var ts; } function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; - var inferenceMapper = createInferenceMapper(context); + var inferenceMapper = getInferenceMapper(context); for (var i = 0; i < typeParameters.length; i++) { if (!context.inferences[i].isFixed) { context.inferredTypes[i] = undefined; @@ -18007,7 +19656,7 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 187) { + if (arg === undefined || arg.kind !== 191) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { @@ -18028,13 +19677,11 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; + var mapper; for (var i = 0; i < typeParameters.length; i++) { - var typeArgNode = typeArguments[i]; - var typeArgument = getTypeFromTypeNode(typeArgNode); - typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { @@ -18044,7 +19691,11 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); typeArgumentHeadMessage = headMessage; } - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); } } } @@ -18054,12 +19705,12 @@ var ts; var argCount = getEffectiveArgumentCount(node, args, signature); for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 187) { + if (arg === undefined || arg.kind !== 191) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); if (argType === undefined) { argType = arg.kind === 9 && !reportErrors - ? getStringLiteralType(arg) + ? getStringLiteralTypeForText(arg.text) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; @@ -18073,16 +19724,16 @@ var ts; } function getEffectiveCallArguments(node) { var args; - if (node.kind === 170) { + if (node.kind === 174) { var template = node.template; args = [undefined]; - if (template.kind === 183) { + if (template.kind === 187) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } - else if (node.kind === 139) { + else if (node.kind === 141) { return undefined; } else { @@ -18091,21 +19742,21 @@ var ts; return args; } function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 139) { + if (node.kind === 141) { switch (node.parent.kind) { - case 214: - case 186: + case 218: + case 190: return 1; - case 141: - return 2; case 143: + return 2; case 145: - case 146: + case 147: + case 148: if (languageVersion === 0) { return 2; } return signature.parameters.length >= 3 ? 3 : 2; - case 138: + case 140: return 3; } } @@ -18114,50 +19765,50 @@ var ts; } } function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 218) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 138) { + if (node.kind === 140) { node = node.parent; - if (node.kind === 144) { + if (node.kind === 146) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 141 || - node.kind === 143 || + if (node.kind === 143 || node.kind === 145 || - node.kind === 146) { + node.kind === 147 || + node.kind === 148) { return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); return unknownType; } function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 218) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 138) { + if (node.kind === 140) { node = node.parent; - if (node.kind === 144) { + if (node.kind === 146) { return anyType; } } - if (node.kind === 141 || - node.kind === 143 || + if (node.kind === 143 || node.kind === 145 || - node.kind === 146) { + node.kind === 147 || + node.kind === 148) { var element = node; switch (element.name.kind) { case 69: case 8: case 9: - return getStringLiteralType(element.name); - case 136: + return getStringLiteralTypeForText(element.name.text); + case 138: var nameType = checkComputedPropertyName(element.name); - if (allConstituentTypesHaveKind(nameType, 16777216)) { + if (isTypeOfKind(nameType, 16777216)) { return nameType; } else { @@ -18172,20 +19823,20 @@ var ts; return unknownType; } function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 214) { + if (node.kind === 218) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 138) { + if (node.kind === 140) { return numberType; } - if (node.kind === 141) { + if (node.kind === 143) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 143 || - node.kind === 145 || - node.kind === 146) { + if (node.kind === 145 || + node.kind === 147 || + node.kind === 148) { var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } @@ -18206,26 +19857,26 @@ var ts; return unknownType; } function getEffectiveArgumentType(node, argIndex, arg) { - if (node.kind === 139) { + if (node.kind === 141) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 170) { + else if (argIndex === 0 && node.kind === 174) { return globalTemplateStringsArrayType; } return undefined; } function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 139 || - (argIndex === 0 && node.kind === 170)) { + if (node.kind === 141 || + (argIndex === 0 && node.kind === 174)) { return undefined; } return args[argIndex]; } function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 139) { + if (node.kind === 141) { return node.expression; } - else if (argIndex === 0 && node.kind === 170) { + else if (argIndex === 0 && node.kind === 174) { return node.template; } else { @@ -18233,8 +19884,8 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 170; - var isDecorator = node.kind === 139; + var isTaggedTemplate = node.kind === 174; + var isDecorator = node.kind === 141; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; @@ -18281,7 +19932,8 @@ var ts; } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], true, headMessage); + var typeArguments_2 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -18333,7 +19985,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); } else { @@ -18380,8 +20032,10 @@ var ts; var superType = checkSuperExpression(node.expression); if (superType !== unknownType) { var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); - var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); - return resolveCall(node, baseConstructors, candidatesOutArray); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); + } } return resolveUntypedCall(node); } @@ -18434,6 +20088,9 @@ var ts; } var constructSignatures = getSignaturesOfType(expressionType, 1); if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } return resolveCall(node, constructSignatures, candidatesOutArray); } var callSignatures = getSignaturesOfType(expressionType, 0); @@ -18447,6 +20104,28 @@ var ts; error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); return resolveErrorCall(node); } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var flags = declaration.flags; + if (!(flags & (8 | 16))) { + return true; + } + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + if (flags & 8) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (flags & 16) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -18465,16 +20144,16 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 214: - case 186: + case 218: + case 190: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 138: + case 140: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 141: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 143: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; case 145: - case 146: + case 147: + case 148: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -18490,7 +20169,7 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo; + var errorInfo = void 0; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); @@ -18502,16 +20181,16 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 168) { + if (node.kind === 172) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 169) { + else if (node.kind === 173) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 170) { + else if (node.kind === 174) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } - else if (node.kind === 139) { + else if (node.kind === 141) { links.resolvedSignature = resolveDecorator(node, candidatesOutArray); } else { @@ -18520,24 +20199,39 @@ var ts; } return links.resolvedSignature; } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined); + } + return links.inferredClassType; + } function checkCallExpression(node) { checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); var signature = getResolvedSignature(node); if (node.expression.kind === 95) { return voidType; } - if (node.kind === 169) { + if (node.kind === 173) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 144 && - declaration.kind !== 148 && - declaration.kind !== 153) { - if (compilerOptions.noImplicitAny) { + declaration.kind !== 146 && + declaration.kind !== 150 && + declaration.kind !== 155 && + !ts.isJSDocConstructSignature(declaration)) { + var funcSymbol = checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16)) { + return getInferredClassType(funcSymbol); + } + else if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; } } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, true)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } return getReturnTypeOfSignature(signature); } function checkTaggedTemplateExpression(node) { @@ -18548,7 +20242,9 @@ var ts; var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); - if (!(isTypeAssignableTo(targetType, widenedType))) { + var bothAreStringLike = maybeTypeOfKind(targetType, 258) && + maybeTypeOfKind(widenedType, 258); + if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } } @@ -18576,7 +20272,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187) { + if (element.kind !== 191) { if (element.name.kind === 69) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -18595,6 +20291,13 @@ var ts; inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); } } + function getReturnTypeFromJSDocComment(func) { + var returnTag = ts.getJSDocReturnTag(func); + if (returnTag && returnTag.typeExpression) { + return getTypeFromTypeNode(returnTag.typeExpression.type); + } + return undefined; + } function createPromiseType(promisedType) { var globalPromiseType = getGlobalPromiseType(); if (globalPromiseType !== emptyGenericType) { @@ -18610,14 +20313,14 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 192) { + if (func.body.kind !== 196) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } } else { - var types; + var types = void 0; var funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); @@ -18653,7 +20356,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + return getUnionType(types); } } if (funcIsGenerator) { @@ -18712,34 +20415,37 @@ var ts; if (!produceDiagnostics) { return; } - if (returnType === voidType || isTypeAny(returnType)) { + if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 || !(func.flags & 524288)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 196 || !(func.flags & 32768)) { return; } - if (func.flags & 1048576) { - if (compilerOptions.noImplicitReturns) { - error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { + var hasExplicitReturn = func.flags & 65536; + if (returnType && !hasExplicitReturn) { error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + var inferredReturnType = hasExplicitReturn + ? getReturnTypeOfSignature(getSignatureFromDeclaration(func)) + : voidType; + if (inferredReturnType === voidType || isTypeAny(inferredReturnType)) { + return; + } + } + error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 || ts.isObjectLiteralMethod(node)); var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 173) { + if (!hasGrammarError && node.kind === 177) { checkGrammarForGenerator(node); } if (contextualMapper === identityMapper && isContextSensitive(node)) { return anyFunctionType; } - var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } var links = getNodeLinks(node); var type = getTypeOfSymbol(node.symbol); var contextSensitive = isContextSensitive(node); @@ -18763,48 +20469,41 @@ var ts; } if (!contextChecked) { checkSignatureDeclaration(node); + checkNodeDeferred(node); } } } - if (produceDiagnostics && node.kind !== 143 && node.kind !== 142) { + if (produceDiagnostics && node.kind !== 145 && node.kind !== 144) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } - function checkFunctionExpressionOrObjectLiteralMethodBody(node) { - ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 145 || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } - var returnType = node.type && getTypeFromTypeNode(node.type); - var promisedType; - if (returnType && isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - if (returnType && !node.asteriskToken) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + if (!node.asteriskToken) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { if (!node.type) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 192) { + if (node.body.kind === 196) { checkSourceElement(node.body); } else { var exprType = checkExpression(node.body); - if (returnType) { + if (returnOrPromisedType) { if (isAsync) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); - checkTypeAssignableTo(awaitedType, promisedType, node.body); + checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } else { - checkTypeAssignableTo(exprType, returnType, node.body); + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } - checkFunctionAndClassExpressionBodies(node.body); } } } @@ -18815,59 +20514,62 @@ var ts; } return true; } - function checkReferenceExpression(n, invalidReferenceMessage, constantVariableMessage) { - function findSymbol(n) { - var symbol = getNodeLinks(n).resolvedSymbol; - return symbol && getExportSymbolOfValueSymbolIfExported(symbol); + function isReadonlySymbol(symbol) { + return symbol.flags & 4 && (getDeclarationFlagsFromSymbol(symbol) & 64) !== 0 || + symbol.flags & 3 && (getDeclarationFlagsFromSymbol(symbol) & 2048) !== 0 || + symbol.flags & 98304 && !(symbol.flags & 65536) || + (symbol.flags & 8) !== 0; + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + if (symbol.flags & 4 && + (expr.kind === 170 || expr.kind === 171) && + expr.expression.kind === 97) { + var func = ts.getContainingFunction(expr); + return !(func && func.kind === 146 && func.parent === symbol.valueDeclaration.parent); + } + return true; } - function isReferenceOrErrorExpression(n) { - switch (n.kind) { - case 69: { - var symbol = findSymbol(n); - return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3) !== 0; + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 170 || expr.kind === 171) { + var node = skipParenthesizedNodes(expr.expression); + if (node.kind === 69) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 8388608) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return declaration && declaration.kind === 228; } - case 166: { - var symbol = findSymbol(n); - return !symbol || symbol === unknownSymbol || (symbol.flags & ~8) !== 0; - } - case 167: - return true; - case 172: - return isReferenceOrErrorExpression(n.expression); - default: - return false; } } - function isConstVariableReference(n) { - switch (n.kind) { - case 69: - case 166: { - var symbol = findSymbol(n); - return symbol && (symbol.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384) !== 0; - } - case 167: { - var index = n.argumentExpression; - var symbol = findSymbol(n.expression); - if (symbol && index && index.kind === 9) { - var name_13 = index.text; - var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_13); - return prop && (prop.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 16384) !== 0; - } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage, constantVariableMessage) { + var node = skipParenthesizedNodes(expr); + if (node.kind !== 69 && node.kind !== 170 && node.kind !== 171) { + error(expr, invalidReferenceMessage); + return false; + } + var links = getNodeLinks(node); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol) { + if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { + if (node.kind === 69 && !(symbol.flags & 3)) { + error(expr, invalidReferenceMessage); return false; } - case 172: - return isConstVariableReference(n.expression); - default: + if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { + error(expr, constantVariableMessage); return false; + } } } - if (!isReferenceOrErrorExpression(n)) { - error(n, invalidReferenceMessage); - return false; - } - if (isConstVariableReference(n)) { - error(n, constantVariableMessage); - return false; + else if (node.kind === 171) { + if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { + error(expr, constantVariableMessage); + return false; + } } return true; } @@ -18885,7 +20587,7 @@ var ts; } function checkAwaitExpression(node) { if (produceDiagnostics) { - if (!(node.parserContextFlags & 8)) { + if (!(node.flags & 33554432)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -18901,7 +20603,7 @@ var ts; case 35: case 36: case 50: - if (someConstituentTypeHasKind(operandType, 16777216)) { + if (maybeTypeOfKind(operandType, 16777216)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -18911,7 +20613,7 @@ var ts; case 42: var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); } return numberType; } @@ -18921,40 +20623,48 @@ var ts; 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) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); } return numberType; } - function someConstituentTypeHasKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 49152) { - var types = type.types; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var current = types_9[_i]; - if (current.flags & kind) { - return true; - } - } - return false; - } - return false; - } - function allConstituentTypesHaveKind(type, kind) { + function maybeTypeOfKind(type, kind) { if (type.flags & kind) { return true; } if (type.flags & 49152) { var types = type.types; for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var current = types_10[_i]; - if (!(current.flags & kind)) { + var t = types_10[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 16384) { + var types = type.types; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + if (!isTypeOfKind(t, kind)) { return false; } } return true; } + if (type.flags & 32768) { + var types = type.types; + for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { + var t = types_12[_a]; + if (isTypeOfKind(t, kind)) { + return true; + } + } + } return false; } function isConstEnumObjectType(type) { @@ -18964,7 +20674,7 @@ var ts; return (symbol.flags & 128) !== 0; } function checkInstanceOfExpression(left, right, leftType, rightType) { - if (allConstituentTypesHaveKind(leftType, 16777726)) { + if (isTypeOfKind(leftType, 16777726)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -18985,23 +20695,30 @@ var ts; var properties = node.properties; for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var p = properties_3[_i]; - if (p.kind === 245 || p.kind === 246) { - var name_14 = p.name; + if (p.kind === 249 || p.kind === 250) { + var name_12 = p.name; + if (name_12.kind === 138) { + checkComputedPropertyName(name_12); + } + if (isComputedNonLiteralName(name_12)) { + continue; + } + var text = getTextOfPropertyName(name_12); var type = isTypeAny(sourceType) ? sourceType - : getTypeOfPropertyOfType(sourceType, name_14.text) || - isNumericLiteralName(name_14.text) && getIndexTypeOfType(sourceType, 1) || + : getTypeOfPropertyOfType(sourceType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1) || getIndexTypeOfType(sourceType, 0); if (type) { - if (p.kind === 246) { + if (p.kind === 250) { checkDestructuringAssignment(p, type); } else { - checkDestructuringAssignment(p.initializer || name_14, type); + checkDestructuringAssignment(p.initializer, type); } } else { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_14)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_12)); } } else { @@ -19015,8 +20732,8 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187) { - if (e.kind !== 185) { + if (e.kind !== 191) { + if (e.kind !== 189) { var propName = "" + i; var type = isTypeAny(sourceType) ? sourceType @@ -19041,7 +20758,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 181 && restExpression.operatorToken.kind === 56) { + if (restExpression.kind === 185 && restExpression.operatorToken.kind === 56) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -19055,7 +20772,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 246) { + if (exprOrAssignment.kind === 250) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -19065,21 +20782,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 181 && target.operatorToken.kind === 56) { + if (target.kind === 185 && target.operatorToken.kind === 56) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 165) { + if (target.kind === 169) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 164) { + if (target.kind === 168) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); } function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant)) { + if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { checkTypeAssignableTo(sourceType, targetType, target, undefined); } return sourceType; @@ -19089,7 +20806,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 && (left.kind === 165 || left.kind === 164)) { + if (operator === 56 && (left.kind === 169 || left.kind === 168)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); @@ -19121,7 +20838,7 @@ var ts; leftType = rightType; if (rightType.flags & (32 | 64)) rightType = leftType; - var suggestedOperator; + var suggestedOperator = void 0; if ((leftType.flags & 8) && (rightType.flags & 8) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { @@ -19141,12 +20858,12 @@ var ts; leftType = rightType; if (rightType.flags & (32 | 64)) rightType = leftType; - var resultType; - if (allConstituentTypesHaveKind(leftType, 132) && allConstituentTypesHaveKind(rightType, 132)) { + var resultType = void 0; + if (isTypeOfKind(leftType, 132) && isTypeOfKind(rightType, 132)) { resultType = numberType; } else { - if (allConstituentTypesHaveKind(leftType, 258) || allConstituentTypesHaveKind(rightType, 258)) { + if (isTypeOfKind(leftType, 258) || isTypeOfKind(rightType, 258)) { resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { @@ -19175,6 +20892,9 @@ var ts; case 31: case 32: case 33: + if (maybeTypeOfKind(leftType, 258) && maybeTypeOfKind(rightType, 258)) { + return booleanType; + } if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) { reportOperatorError(); } @@ -19194,8 +20914,8 @@ var ts; return rightType; } function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 16777216) ? left : - someConstituentTypeHasKind(rightType, 16777216) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216) ? left : + maybeTypeOfKind(rightType, 16777216) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -19220,7 +20940,7 @@ var ts; } function checkAssignmentOperator(valueType) { if (produceDiagnostics && operator >= 56 && operator <= 68) { - var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); if (ok) { checkTypeAssignableTo(valueType, leftType, left, undefined); } @@ -19247,7 +20967,7 @@ var ts; } function checkYieldExpression(node) { if (produceDiagnostics) { - if (!(node.parserContextFlags & 2) || isYieldExpressionInClass(node)) { + if (!(node.flags & 8388608) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -19258,7 +20978,7 @@ var ts; var func = ts.getContainingFunction(node); if (func && func.asteriskToken) { var expressionType = checkExpressionCached(node.expression, undefined); - var expressionElementType; + var expressionElementType = void 0; var nodeIsYieldStar = !!node.asteriskToken; if (nodeIsYieldStar) { expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); @@ -19282,6 +21002,13 @@ var ts; var type2 = checkExpression(node.whenFalse, contextualMapper); return getUnionType([type1, type2]); } + function checkStringLiteralExpression(node) { + var contextualType = getContextualType(node); + if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + return getStringLiteralTypeForText(node.text); + } + return stringType; + } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { checkExpression(templateSpan.expression); @@ -19303,14 +21030,14 @@ var ts; return links.resolvedType; } function checkPropertyAssignment(node, contextualMapper) { - if (node.name.kind === 136) { + if (node.name.kind === 138) { checkComputedPropertyName(node.name); } return checkExpression(node.initializer, contextualMapper); } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); - if (node.name.kind === 136) { + if (node.name.kind === 138) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -19320,7 +21047,7 @@ var ts; if (isInferentialContext(contextualMapper)) { var signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); if (contextualType) { var contextualSignature = getSingleCallSignature(contextualType); if (contextualSignature && !contextualSignature.typeParameters) { @@ -19333,7 +21060,7 @@ var ts; } function checkExpression(node, contextualMapper) { var type; - if (node.kind === 135) { + if (node.kind === 137) { type = checkQualifiedName(node); } else { @@ -19341,9 +21068,9 @@ var ts; type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 166 && node.parent.expression === node) || - (node.parent.kind === 167 && node.parent.expression === node) || - ((node.kind === 69 || node.kind === 135) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 170 && node.parent.expression === node) || + (node.parent.kind === 171 && node.parent.expression === node) || + ((node.kind === 69 || node.kind === 137) && 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); } @@ -19369,65 +21096,66 @@ var ts; return booleanType; case 8: return checkNumericLiteral(node); - case 183: + case 187: return checkTemplateExpression(node); case 9: + return checkStringLiteralExpression(node); case 11: return stringType; case 10: return globalRegExpType; - case 164: - return checkArrayLiteral(node, contextualMapper); - case 165: - return checkObjectLiteral(node, contextualMapper); - case 166: - return checkPropertyAccessExpression(node); - case 167: - return checkIndexedAccess(node); case 168: + return checkArrayLiteral(node, contextualMapper); case 169: - return checkCallExpression(node); + return checkObjectLiteral(node, contextualMapper); case 170: - return checkTaggedTemplateExpression(node); - case 172: - return checkExpression(node.expression, contextualMapper); - case 186: - return checkClassExpression(node); - case 173: - case 174: - return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 176: - return checkTypeOfExpression(node); + return checkPropertyAccessExpression(node); case 171: - case 189: - return checkAssertion(node); - case 175: - return checkDeleteExpression(node); + return checkIndexedAccess(node); + case 172: + case 173: + return checkCallExpression(node); + case 174: + return checkTaggedTemplateExpression(node); + case 176: + return checkExpression(node.expression, contextualMapper); + case 190: + return checkClassExpression(node); case 177: - return checkVoidExpression(node); case 178: - return checkAwaitExpression(node); - case 179: - return checkPrefixUnaryExpression(node); + return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); case 180: - return checkPostfixUnaryExpression(node); + return checkTypeOfExpression(node); + case 175: + case 193: + return checkAssertion(node); + case 179: + return checkDeleteExpression(node); case 181: - return checkBinaryExpression(node, contextualMapper); + return checkVoidExpression(node); case 182: - return checkConditionalExpression(node, contextualMapper); - case 185: - return checkSpreadElementExpression(node, contextualMapper); - case 187: - return undefinedType; + return checkAwaitExpression(node); + case 183: + return checkPrefixUnaryExpression(node); case 184: + return checkPostfixUnaryExpression(node); + case 185: + return checkBinaryExpression(node, contextualMapper); + case 186: + return checkConditionalExpression(node, contextualMapper); + case 189: + return checkSpreadElementExpression(node, contextualMapper); + case 191: + return undefinedType; + case 188: return checkYieldExpression(node); - case 240: + case 244: return checkJsxExpression(node); - case 233: + case 237: return checkJsxElement(node); - case 234: + case 238: return checkJsxSelfClosingElement(node); - case 235: + case 239: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -19437,8 +21165,8 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); + getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node))); if (produceDiagnostics) { - checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } @@ -19446,9 +21174,9 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 56) { + if (node.flags & 28) { func = ts.getContainingFunction(node); - if (!(func.kind === 144 && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 146 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -19463,9 +21191,9 @@ var ts; if (!node.asteriskToken || !node.body) { return false; } - return node.kind === 143 || - node.kind === 213 || - node.kind === 173; + return node.kind === 145 || + node.kind === 217 || + node.kind === 177; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { @@ -19479,90 +21207,98 @@ var ts; } return -1; } - function isInLegalTypePredicatePosition(node) { + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name_13 = _a[_i].name; + if (ts.isBindingPattern(name_13) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_13, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { switch (node.parent.kind) { - case 174: - case 147: - case 213: - case 173: - case 152: - case 143: - case 142: - return node === node.parent.type; + case 178: + case 149: + case 217: + case 177: + case 154: + case 145: + case 144: + var parent_7 = node.parent; + if (node === parent_7.type) { + return parent_7; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var name_14 = _a[_i].name; + if (name_14.kind === 69 && + name_14.text === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name_14.kind === 166 || + name_14.kind === 165) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_14, predicateVariableNode, predicateVariableName)) { + return true; + } + } } - return false; } function checkSignatureDeclaration(node) { - if (node.kind === 149) { + if (node.kind === 151) { checkGrammarIndexSignature(node); } - else if (node.kind === 152 || node.kind === 213 || node.kind === 153 || - node.kind === 147 || node.kind === 144 || - node.kind === 148) { + else if (node.kind === 154 || node.kind === 217 || node.kind === 155 || + node.kind === 149 || node.kind === 146 || + node.kind === 150) { checkGrammarFunctionLikeDeclaration(node); } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { - if (node.type.kind === 150) { - 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, getTypeOfNode(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 === 161 || - param.name.kind === 162) { - (function checkBindingPattern(pattern) { - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (element.name.kind === 69 && - 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 === 162 || - element.name.kind === 161) { - 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); - } + checkSourceElement(node.type); } if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 148: + case 150: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 147: + case 149: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -19579,12 +21315,14 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } + else if (ts.isAsyncFunctionLike(node)) { + checkAsyncFunctionReturnType(node); + } } } - checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 215) { + if (node.kind === 219) { var nodeSymbol = getSymbolOfNode(node); if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; @@ -19599,7 +21337,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 130: + case 131: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -19607,7 +21345,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 128: + case 129: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -19626,7 +21364,7 @@ var ts; } function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); - checkFunctionLikeDeclaration(node); + checkFunctionOrMethodDeclaration(node); if (node.flags & 128 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } @@ -19646,14 +21384,11 @@ var ts; if (!produceDiagnostics) { return; } - function isSuperCallExpression(n) { - return n.kind === 168 && n.expression.kind === 95; - } function containsSuperCallAsComputedPropertyName(n) { return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (isSuperCallExpression(n)) { + if (ts.isSuperCallExpression(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -19668,32 +21403,31 @@ var ts; if (n.kind === 97) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 173 && n.kind !== 213) { + else if (n.kind !== 177 && n.kind !== 217) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 141 && - !(n.flags & 64) && + return n.kind === 143 && + !(n.flags & 32) && !!n.initializer; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { - var containingClassSymbol = getSymbolOfNode(containingClassDecl); - var containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); - var baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); - if (containsSuperCall(node.body)) { - if (baseConstructorType === nullType) { - error(node, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & (8 | 16 | 32); }); + ts.forEach(node.parameters, function (p) { return p.flags & (4 | 8 | 16); }); if (superCallShouldBeFirst) { var statements = node.body.statements; - var superCallStatement; + var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 195 && isSuperCallExpression(statement.expression)) { + if (statement.kind === 199 && ts.isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; } @@ -19704,12 +21438,9 @@ var ts; if (!superCallStatement) { error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); } - else { - markThisReferencesAsErrors(superCallStatement.expression); - } } } - else if (baseConstructorType !== nullType) { + else if (!classExtendsNull) { error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); } } @@ -19717,9 +21448,11 @@ var ts; function checkAccessorDeclaration(node) { if (produceDiagnostics) { checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (node.kind === 145) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288)) { - if (node.flags & 1048576) { + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 147) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768)) { + if (node.flags & 65536) { if (compilerOptions.noImplicitReturns) { error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -19729,13 +21462,19 @@ var ts; } } } + if (node.name.kind === 138) { + checkComputedPropertyName(node.name); + } if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 145 ? 146 : 145; + var otherKind = node.kind === 147 ? 148 : 147; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 56) !== (otherAccessor.flags & 56))) { + if (((node.flags & 28) !== (otherAccessor.flags & 28))) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } + if (((node.flags & 128) !== (otherAccessor.flags & 128))) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } var currentAccessorType = getAnnotatedAccessorType(node); var otherAccessorType = getAnnotatedAccessorType(otherAccessor); if (currentAccessorType && otherAccessorType) { @@ -19747,18 +21486,32 @@ var ts; } getTypeOfAccessors(getSymbolOfNode(node)); } - checkFunctionLikeDeclaration(node); + if (node.parent.kind !== 169) { + checkSourceElement(node.body); + } + else { + checkNodeDeferred(node); + } + } + function checkAccessorDeferred(node) { + checkSourceElement(node.body); } function checkMissingDeclaration(node) { checkDecorators(node); } - function checkTypeArgumentConstraints(typeParameters, typeArguments) { + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var typeArguments; + var mapper; var result = true; for (var i = 0; i < typeParameters.length; i++) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { + if (!typeArguments) { + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + mapper = createTypeMapper(typeParameters, typeArguments); + } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -19800,49 +21553,18 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 16) && ts.isInAmbientContext(node); - } - function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { - if (!produceDiagnostics) { - return; - } - var signature = getSignatureFromDeclaration(signatureDeclarationNode); - if (!signature.hasStringLiterals) { - return; - } - if (ts.nodeIsPresent(signatureDeclarationNode.body)) { - error(signatureDeclarationNode, ts.Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type); - return; - } - var signaturesToCheck; - if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 215) { - ts.Debug.assert(signatureDeclarationNode.kind === 147 || signatureDeclarationNode.kind === 148); - var signatureKind = signatureDeclarationNode.kind === 147 ? 0 : 1; - var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); - var containingType = getDeclaredTypeOfSymbol(containingSymbol); - signaturesToCheck = getSignaturesOfType(containingType, signatureKind); - } - else { - signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); - } - for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { - var otherSignature = signaturesToCheck_1[_i]; - if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { - return; - } - } - error(signatureDeclarationNode, ts.Diagnostics.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature); + return (node.flags & 8) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedNodeFlags(n); - if (n.parent.kind !== 215 && - n.parent.kind !== 214 && - n.parent.kind !== 186 && + if (n.parent.kind !== 219 && + n.parent.kind !== 218 && + n.parent.kind !== 190 && ts.isInAmbientContext(n)) { - if (!(flags & 4)) { - flags |= 2; + if (!(flags & 2)) { + flags |= 1; } - flags |= 4; + flags |= 2; } return flags & flagsToCheck; } @@ -19857,36 +21579,36 @@ var ts; function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; if (someButNotAllOverloadFlags !== 0) { - var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); ts.forEach(overloads, function (o) { - var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } - else if (deviation & 4) { + else if (deviation & 2) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (16 | 32)) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + else if (deviation & (8 | 16)) { + error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } } function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { if (someHaveQuestionToken !== allHaveQuestionToken) { - var canonicalHasQuestionToken = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); ts.forEach(overloads, function (o) { - var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken; + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } } - var flagsToCheck = 2 | 4 | 16 | 32 | 128; + var flagsToCheck = 1 | 2 | 8 | 16 | 128; var someNodeFlags = 0; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; @@ -19910,14 +21632,16 @@ var ts; seen = c === node; } }); - if (subsequentNode) { + if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - ts.Debug.assert(node.kind === 143 || node.kind === 142); - ts.Debug.assert((node.flags & 64) !== (subsequentNode.flags & 64)); - var diagnostic = node.flags & 64 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); + var reportError = (node.kind === 145 || node.kind === 144) && + (node.flags & 32) !== (subsequentNode.flags & 32); + if (reportError) { + var diagnostic = node.flags & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } return; } else if (ts.nodeIsPresent(subsequentNode.body)) { @@ -19946,11 +21670,11 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 215 || node.parent.kind === 155 || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 219 || node.parent.kind === 157 || inAmbientContext; if (inAmbientContextOrInterface) { previousDeclaration = undefined; } - if (node.kind === 213 || node.kind === 143 || node.kind === 142 || node.kind === 144) { + if (node.kind === 217 || node.kind === 145 || node.kind === 144 || node.kind === 146) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -20001,13 +21725,11 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - if (!bodySignature.hasStringLiterals) { - for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { - var signature = signatures_3[_a]; - if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { - error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); - break; - } + for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { + var signature = signatures_3[_a]; + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; } } } @@ -20033,8 +21755,8 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var d = _a[_i]; var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 2 | 512); - if (effectiveDeclarationFlags & 2) { + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 512); + if (effectiveDeclarationFlags & 1) { if (effectiveDeclarationFlags & 512) { defaultExportedDeclarationSpaces |= declarationSpaces; } @@ -20063,20 +21785,20 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 215: + case 219: return 2097152; - case 218: - return d.name.kind === 9 || ts.getModuleInstanceState(d) !== 0 + case 222: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 ? 4194304 | 1048576 : 4194304; - case 214: - case 217: - return 2097152 | 1048576; + case 218: case 221: - var result = 0; + return 2097152 | 1048576; + case 225: + var result_1 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); - return result; + ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); + return result_1; default: return 1048576; } @@ -20162,7 +21884,23 @@ var ts; } } } + function checkCorrectPromiseType(returnType, location) { + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType === emptyGenericType + || globalPromiseType === getTargetType(returnType)) { + return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + } + error(location, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } function checkAsyncFunctionReturnType(node) { + if (languageVersion >= 2) { + var returnType = getTypeFromTypeNode(node.type); + return checkCorrectPromiseType(returnType, node.type); + } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { return unknownType; @@ -20179,15 +21917,16 @@ var ts; error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } + checkReturnTypeAnnotationAsExpression(node); var promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } var promiseName = ts.getEntityNameFromTypeNode(node.type); - var root = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, root.text, 107455); + var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); + var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455); if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, getFullyQualifiedName(promiseConstructor)); + error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); @@ -20202,22 +21941,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 214: + case 218: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 138: + case 140: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 141: + case 143: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 143: case 145: - case 146: + case 147: + case 148: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -20226,9 +21965,9 @@ var ts; checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); } function checkTypeNodeAsExpression(node) { - if (node && node.kind === 151) { + if (node && node.kind === 153) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 151 ? 793056 : 1536; + var meaning = root.parent.kind === 153 ? 793056 : 1536; var rootSymbol = resolveName(root, root.text, meaning | 8388608, undefined, undefined); if (rootSymbol && rootSymbol.flags & 8388608) { var aliasTarget = resolveAlias(rootSymbol); @@ -20239,23 +21978,10 @@ var ts; } } function checkTypeAnnotationAsExpression(node) { - switch (node.kind) { - case 141: - checkTypeNodeAsExpression(node.type); - break; - case 138: - checkTypeNodeAsExpression(node.type); - break; - case 143: - checkTypeNodeAsExpression(node.type); - break; - case 145: - checkTypeNodeAsExpression(node.type); - break; - case 146: - checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node)); - break; - } + checkTypeNodeAsExpression(node.type); + } + function checkReturnTypeAnnotationAsExpression(node) { + checkTypeNodeAsExpression(node.type); } function checkParameterTypeAnnotationsAsExpressions(node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -20271,54 +21997,51 @@ var ts; 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); + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } if (compilerOptions.emitDecoratorMetadata) { switch (node.kind) { - case 214: + case 218: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; - case 143: - checkParameterTypeAnnotationsAsExpressions(node); - case 146: case 145: - case 141: - case 138: + case 147: + case 148: + checkParameterTypeAnnotationsAsExpressions(node); + checkReturnTypeAnnotationAsExpression(node); + break; + case 143: + case 140: checkTypeAnnotationAsExpression(node); break; } } - emitDecorate = true; - if (node.kind === 138) { - emitParam = true; - } ts.forEach(node.decorators, checkDecorator); } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); + checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkFunctionLikeDeclaration(node) { + function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } - if (node.name && node.name.kind === 136) { + if (node.name && node.name.kind === 138) { checkComputedPropertyName(node.name); } if (!ts.hasDynamicName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); + var firstDeclaration = ts.forEach(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)) ? + declaration : undefined; }); if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); } @@ -20329,13 +22052,9 @@ var ts; } } checkSourceElement(node.body); - if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - var returnType = getTypeFromTypeNode(node.type); - var promisedType; - if (isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + if (!node.asteriskToken) { + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !node.type) { if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { @@ -20347,13 +22066,10 @@ var ts; } } function checkBlock(node) { - if (node.kind === 192) { + if (node.kind === 196) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 219) { - checkFunctionAndClassExpressionBodies(node); - } } function checkCollisionWithArgumentsInGeneratedCode(node) { if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { @@ -20369,19 +22085,19 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 141 || - node.kind === 140 || - node.kind === 143 || + if (node.kind === 143 || node.kind === 142 || node.kind === 145 || - node.kind === 146) { + node.kind === 144 || + node.kind === 147 || + node.kind === 148) { return false; } if (ts.isInAmbientContext(node)) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 138 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 140 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -20429,19 +22145,31 @@ var ts; if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } - if (node.kind === 218 && ts.getModuleInstanceState(node) !== 1) { + if (node.kind === 222 && ts.getModuleInstanceState(node) !== 1) { return; } var parent = getDeclarationContainer(node); - if (parent.kind === 248 && ts.isExternalModule(parent)) { + if (parent.kind === 252 && ts.isExternalOrCommonJsModule(parent)) { error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } - function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 24576) !== 0 || ts.isParameterDeclaration(node)) { + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "Promise")) { return; } - if (node.kind === 211 && !node.initializer) { + if (node.kind === 222 && ts.getModuleInstanceState(node) !== 1) { + return; + } + var parent = getDeclarationContainer(node); + if (parent.kind === 252 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2097152) { + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + if ((ts.getCombinedNodeFlags(node) & 3072) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + if (node.kind === 215 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -20450,16 +22178,16 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212); - var container = varDeclList.parent.kind === 193 && varDeclList.parent.parent + if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 3072) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 216); + var container = varDeclList.parent.kind === 197 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 192 && ts.isFunctionLike(container.parent) || - container.kind === 219 || - container.kind === 218 || - container.kind === 248); + (container.kind === 196 && ts.isFunctionLike(container.parent) || + container.kind === 223 || + container.kind === 222 || + container.kind === 252); if (!namesShareScope) { var name_15 = symbolToString(localDeclarationSymbol); error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_15, name_15); @@ -20469,7 +22197,7 @@ var ts; } } function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 138) { + if (ts.getRootDeclaration(node).kind !== 140) { return; } var func = ts.getContainingFunction(node); @@ -20478,7 +22206,7 @@ var ts; if (n.kind === 69) { var referencedSymbol = getNodeLinks(n).resolvedSymbol; if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, 107455) === referencedSymbol) { - if (referencedSymbol.valueDeclaration.kind === 138) { + if (referencedSymbol.valueDeclaration.kind === 140) { if (referencedSymbol.valueDeclaration === node) { error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); return; @@ -20498,21 +22226,26 @@ var ts; function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); - if (node.name.kind === 136) { + if (node.name.kind === 138) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } + if (node.kind === 167) { + if (node.propertyName && node.propertyName.kind === 138) { + checkComputedPropertyName(node.propertyName); + } + } if (ts.isBindingPattern(node.name)) { ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && ts.getRootDeclaration(node).kind === 138 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 140 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } if (ts.isBindingPattern(node.name)) { - if (node.initializer) { + if (node.initializer && node.parent.parent.kind !== 204) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); checkParameterInitializer(node); } @@ -20521,7 +22254,7 @@ var ts; var symbol = getSymbolOfNode(node); var type = getTypeOfVariableOrParameterOrProperty(symbol); if (node === symbol.valueDeclaration) { - if (node.initializer) { + if (node.initializer && node.parent.parent.kind !== 204) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); checkParameterInitializer(node); } @@ -20535,14 +22268,15 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } } - if (node.kind !== 141 && node.kind !== 140) { + if (node.kind !== 143 && node.kind !== 142) { checkExportsOnMergedDeclarations(node); - if (node.kind === 211 || node.kind === 163) { + if (node.kind === 215 || node.kind === 167) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } function checkVariableDeclaration(node) { @@ -20558,7 +22292,7 @@ var ts; ts.forEach(node.declarationList.declarations, checkSourceElement); } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 165) { + if (node.modifiers && node.parent.kind === 169) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -20577,7 +22311,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 194) { + if (node.thenStatement.kind === 198) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -20594,12 +22328,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 212) { + if (node.initializer && node.initializer.kind === 216) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 212) { + if (node.initializer.kind === 216) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -20614,18 +22348,18 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 216) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression); - if (varExpr.kind === 164 || varExpr.kind === 165) { + if (varExpr.kind === 168 || varExpr.kind === 169) { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant); + checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); if (iteratedType) { checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); } @@ -20635,7 +22369,7 @@ var ts; } function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 216) { 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); @@ -20645,14 +22379,14 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 164 || varExpr.kind === 165) { + if (varExpr.kind === 168 || varExpr.kind === 169) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } 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 { - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant); + checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); } } var rightType = checkExpression(node.expression); @@ -20773,7 +22507,13 @@ var ts; } function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { ts.Debug.assert(languageVersion < 2); - var arrayType = removeTypesFromUnionType(arrayOrStringType, 258, true, true); + var arrayType = arrayOrStringType; + if (arrayOrStringType.flags & 16384) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258); })); + } + else if (arrayOrStringType.flags & 258) { + arrayType = emptyUnionType; + } var hasStringConstituent = arrayOrStringType !== arrayType; var reportedError = false; if (hasStringConstituent) { @@ -20806,8 +22546,8 @@ var ts; function checkBreakOrContinueStatement(node) { checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); } - function isGetAccessorWithAnnotatatedSetAccessor(node) { - return !!(node.kind === 145 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 146))); + function isGetAccessorWithAnnotatedSetAccessor(node) { + return !!(node.kind === 147 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 148))); } function checkReturnStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { @@ -20825,15 +22565,15 @@ var ts; if (func.asteriskToken) { return; } - if (func.kind === 146) { + if (func.kind === 148) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === 144) { + else if (func.kind === 146) { if (!checkTypeAssignableTo(exprType, returnType, node.expression)) { 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) { + else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { if (ts.isAsyncFunctionLike(func)) { var promisedType = getPromisedType(returnType); var awaitedType = checkAwaitedType(exprType, node.expression, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -20850,7 +22590,7 @@ var ts; } function checkWithStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.parserContextFlags & 8) { + if (node.flags & 33554432) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -20862,8 +22602,9 @@ var ts; var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); + var expressionTypeIsStringLike = maybeTypeOfKind(expressionType, 258); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 242 && !hasDuplicateDefaultClause) { + if (clause.kind === 246 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -20875,10 +22616,12 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 241) { + if (produceDiagnostics && clause.kind === 245) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); - if (!isTypeAssignableTo(expressionType, caseType)) { + var expressionTypeIsAssignableToCaseType = (expressionTypeIsStringLike && maybeTypeOfKind(caseType, 258)) || + isTypeAssignableTo(expressionType, caseType); + if (!expressionTypeIsAssignableToCaseType) { checkTypeAssignableTo(caseType, expressionType, caseClause.expression, undefined); } } @@ -20892,7 +22635,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 207 && current.label.text === node.label.text) { + if (current.kind === 211 && 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; @@ -20959,7 +22702,7 @@ var ts; var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!(member.flags & 64) && ts.hasDynamicName(member)) { + if (!(member.flags & 32) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); @@ -20986,7 +22729,7 @@ var ts; return; } var errorNode; - if (prop.valueDeclaration.name.kind === 136 || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 138 || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { @@ -21030,10 +22773,31 @@ var ts; } } } + function checkTypeParameterListsIdentical(node, symbol) { + if (symbol.declarations.length === 1) { + return; + } + var firstDecl; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 218 || declaration.kind === 219) { + if (!firstDecl) { + firstDecl = declaration; + } + else if (!areTypeParametersIdentical(firstDecl.typeParameters, node.typeParameters)) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, node.name.text); + } + } + } + } function checkClassExpression(node) { checkClassLikeDeclaration(node); + checkNodeDeferred(node); return getTypeOfSymbol(getSymbolOfNode(node)); } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + } function checkClassDeclaration(node) { if (!node.name && !(node.flags & 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -21048,6 +22812,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } checkTypeParameters(node.typeParameters); checkExportsOnMergedDeclarations(node); @@ -21055,13 +22820,14 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(node, symbol); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - emitExtends = emitExtends || !ts.isInAmbientContext(node); var baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { - var baseType = baseTypes[0]; + var baseType_1 = baseTypes[0]; var staticBaseType = getBaseConstructorTypeOfClass(type); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); if (baseTypeNode.typeArguments) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); @@ -21072,15 +22838,15 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType; })) { + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } - checkKindsOfPropertyMemberOverrides(type, baseType); + checkKindsOfPropertyMemberOverrides(type, baseType_1); } } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); @@ -21110,6 +22876,18 @@ var ts; checkTypeForDuplicateIndexSignatures(node); } } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && declaration.flags & 8) { + var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); + } + } + } + } function getTargetSymbol(s) { return s.flags & 16777216 ? getSymbolLinks(s).target : s; } @@ -21131,7 +22909,7 @@ var ts; if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(derivedClassDecl.flags & 128))) { - if (derivedClassDecl.kind === 186) { + if (derivedClassDecl.kind === 190) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -21141,10 +22919,10 @@ var ts; } else { var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); - if ((baseDeclarationFlags & 16) || (derivedDeclarationFlags & 16)) { + if ((baseDeclarationFlags & 8) || (derivedDeclarationFlags & 8)) { continue; } - if ((baseDeclarationFlags & 64) !== (derivedDeclarationFlags & 64)) { + if ((baseDeclarationFlags & 32) !== (derivedDeclarationFlags & 32)) { continue; } if ((base.flags & derived.flags & 8192) || ((base.flags & 98308) && (derived.flags & 98308))) { @@ -21175,7 +22953,7 @@ var ts; } } function isAccessor(kind) { - return kind === 145 || kind === 146; + return kind === 147 || kind === 148; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -21241,12 +23019,8 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 215); - 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); - } - } + checkTypeParameterListsIdentical(node, symbol); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 219); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -21277,7 +23051,7 @@ var ts; } function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 8192)) { + if (!(nodeLinks.flags & 16384)) { var enumSymbol = getSymbolOfNode(node); var enumType = getDeclaredTypeOfSymbol(enumSymbol); var autoValue = 0; @@ -21285,11 +23059,14 @@ var ts; var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.name.kind === 136) { + if (isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } - else if (isNumericLiteralName(member.name.text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + else { + var text = getTextOfPropertyName(member.name); + if (isNumericLiteralName(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } } var previousEnumMemberIsNonConstant = autoValue === undefined; var initializer = member.initializer; @@ -21303,10 +23080,11 @@ var ts; error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); } if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue++; + getNodeLinks(member).enumMemberValue = autoValue; + autoValue++; } } - nodeLinks.flags |= 8192; + nodeLinks.flags |= 16384; } function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { var reportError = true; @@ -21335,7 +23113,7 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 179: + case 183: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; @@ -21346,7 +23124,7 @@ var ts; case 50: return ~value_1; } return undefined; - case 181: + case 185: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -21371,22 +23149,22 @@ var ts; return undefined; case 8: return +e.text; - case 172: + case 176: return evalConstant(e.expression); case 69: - case 167: - case 166: + case 171: + case 170: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; - var propertyName; + var propertyName = void 0; if (e.kind === 69) { enumType_1 = currentType; propertyName = e.text; } else { - var expression; - if (e.kind === 167) { + var expression = void 0; + if (e.kind === 171) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9) { return undefined; @@ -21403,7 +23181,7 @@ var ts; if (current.kind === 69) { break; } - else if (current.kind === 166) { + else if (current.kind === 170) { current = current.expression; } else { @@ -21444,6 +23222,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); @@ -21460,9 +23239,9 @@ var ts; } }); } - var seenEnumMissingInitialInitializer = false; + var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 217) { + if (declaration.kind !== 221) { return false; } var enumDeclaration = declaration; @@ -21471,11 +23250,11 @@ var ts; } var firstEnumMember = enumDeclaration.members[0]; if (!firstEnumMember.initializer) { - if (seenEnumMissingInitialInitializer) { + if (seenEnumMissingInitialInitializer_1) { error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); } else { - seenEnumMissingInitialInitializer = true; + seenEnumMissingInitialInitializer_1 = true; } } }); @@ -21485,8 +23264,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 214 || - (declaration.kind === 213 && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 218 || + (declaration.kind === 217 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -21508,7 +23287,12 @@ var ts; } function checkModuleDeclaration(node) { if (produceDiagnostics) { - var isAmbientExternalModule = node.name.kind === 9; + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = ts.isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); var contextErrorMessage = isAmbientExternalModule ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; @@ -21516,17 +23300,18 @@ var ts; return; } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!ts.isInAmbientContext(node) && node.name.kind === 9) { + if (!inAmbientContext && node.name.kind === 9) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 && symbol.declarations.length > 1 - && !ts.isInAmbientContext(node) + && !inAmbientContext && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -21537,29 +23322,102 @@ 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, 214); + var mergedClass = ts.getDeclarationOfKind(symbol, 218); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; } } if (isAmbientExternalModule) { - if (!isGlobalSourceFile(node.parent)) { - error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + if (ts.isExternalModuleAugmentation(node)) { + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); + if (checkBody) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } } - if (ts.isExternalModuleNameRelative(node.name.text)) { - error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(node.name.text)) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } } } } checkSourceElement(node.body); } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 197: + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 231: + case 232: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 225: + if (node.moduleReference.kind !== 9) { + error(node.name, ts.Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + break; + } + case 226: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 167: + case 215: + var name_16 = node.name; + if (ts.isBindingPattern(name_16)) { + for (var _b = 0, _c = name_16.elements; _b < _c.length; _b++) { + var el = _c[_b]; + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + case 218: + case 221: + case 217: + case 219: + case 222: + case 220: + var symbol = getSymbolOfNode(node); + if (symbol) { + var reportError = !(symbol.flags & 33554432); + if (!reportError) { + if (isGlobalAugmentation) { + reportError = symbol.parent !== undefined; + } + else { + reportError = ts.isExternalModuleAugmentation(symbol.parent.valueDeclaration); + } + } + if (reportError) { + error(node, ts.Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + } + } + break; + } + } function getFirstIdentifier(node) { while (true) { - if (node.kind === 135) { + if (node.kind === 137) { node = node.left; } - else if (node.kind === 166) { + else if (node.kind === 170) { node = node.expression; } else { @@ -21575,16 +23433,18 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 219 && node.parent.parent.name.kind === 9; - if (node.parent.kind !== 248 && !inAmbientExternalModule) { - error(moduleName, node.kind === 228 ? + var inAmbientExternalModule = node.parent.kind === 223 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 252 && !inAmbientExternalModule) { + error(moduleName, node.kind === 232 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); - return false; + if (!isTopLevelInExternalModuleAugmentation(node)) { + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } } return true; } @@ -21596,7 +23456,7 @@ var ts; (symbol.flags & 793056 ? 793056 : 0) | (symbol.flags & 1536 ? 1536 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 230 ? + var message = node.kind === 234 ? 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)); @@ -21606,13 +23466,14 @@ var ts; function checkImportBinding(node) { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); } function checkImportDeclaration(node) { if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -21622,7 +23483,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224) { + if (importClause.namedBindings.kind === 228) { checkImportBinding(importClause.namedBindings); } else { @@ -21639,7 +23500,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 2) { + if (node.flags & 1) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -21657,7 +23518,7 @@ var ts; } } else { - if (modulekind === 5 && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES6 && !ts.isInAmbientContext(node)) { grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } @@ -21667,46 +23528,53 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959)) { 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 === 219 && node.parent.parent.name.kind === 9; - if (node.parent.kind !== 248 && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 223 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 252 && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } else { var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && moduleSymbol.exports["export="]) { + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } } } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 248 && node.parent.kind !== 219 && node.parent.kind !== 218) { + if (node.parent.kind !== 252 && node.parent.kind !== 223 && node.parent.kind !== 222) { return grammarErrorOnFirstToken(node, errorMessage); } } function checkExportSpecifier(node) { checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { - markExportAsReferenced(node); + var exportedName = node.propertyName || node.name; + var symbol = resolveName(exportedName, exportedName.text, 107455 | 793056 | 1536 | 8388608, undefined, undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_re_export_name_that_is_not_defined_in_the_module); + } + else { + markExportAsReferenced(node); + } } } function checkExportAssignment(node) { if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { return; } - var container = node.parent.kind === 248 ? node.parent : node.parent.parent; - if (container.kind === 218 && container.name.kind === 69) { + var container = node.parent.kind === 252 ? node.parent : node.parent.parent; + if (container.kind === 222 && !ts.isAmbientModule(container)) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69) { @@ -21717,23 +23585,14 @@ var ts; } checkExternalModuleExports(container); if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === 5) { + if (modulekind === ts.ModuleKind.ES6) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_export_default_or_another_module_format_instead); } - else if (modulekind === 4) { + else if (modulekind === ts.ModuleKind.System) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); } } } - function getModuleStatements(node) { - if (node.kind === 248) { - return node.statements; - } - if (node.kind === 218 && node.body.kind === 219) { - return node.body.statements; - } - return emptyArray; - } function hasExportedMembers(moduleSymbol) { for (var id in moduleSymbol.exports) { if (id !== "export=") { @@ -21749,14 +23608,36 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports["export="]; if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + var exports_2 = getExportsOfModule(moduleSymbol); + for (var id in exports_2) { + if (id === "__export") { + continue; + } + var _a = exports_2[id], declarations = _a.declarations, flags = _a.flags; + if (flags & (1536 | 64 | 384)) { + continue; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + if (flags & 524288 && exportedDeclarationsCount <= 2) { + continue; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); + } + } + } } 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 isNotOverload(declaration) { + return declaration.kind !== 217 || !!declaration.body; } } function checkSourceElement(node) { @@ -21766,217 +23647,144 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { + case 222: case 218: - case 214: - case 215: - case 213: + case 219: + case 217: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 137: + case 139: return checkTypeParameter(node); - case 138: - return checkParameter(node); - case 141: case 140: - return checkPropertyDeclaration(node); - case 152: - case 153: - case 147: - case 148: - return checkSignatureDeclaration(node); - case 149: - return checkSignatureDeclaration(node); + return checkParameter(node); case 143: case 142: - return checkMethodDeclaration(node); - case 144: - return checkConstructorDeclaration(node); - case 145: - case 146: - return checkAccessorDeclaration(node); - case 151: - return checkTypeReferenceNode(node); - case 150: - return checkTypePredicate(node); + return checkPropertyDeclaration(node); case 154: - return checkTypeQuery(node); case 155: - return checkTypeLiteral(node); + case 149: + case 150: + return checkSignatureDeclaration(node); + case 151: + return checkSignatureDeclaration(node); + case 145: + case 144: + return checkMethodDeclaration(node); + case 146: + return checkConstructorDeclaration(node); + case 147: + case 148: + return checkAccessorDeclaration(node); + case 153: + return checkTypeReferenceNode(node); + case 152: + return checkTypePredicate(node); case 156: - return checkArrayType(node); + return checkTypeQuery(node); case 157: - return checkTupleType(node); + return checkTypeLiteral(node); case 158: + return checkArrayType(node); case 159: - return checkUnionOrIntersectionType(node); + return checkTupleType(node); case 160: + case 161: + return checkUnionOrIntersectionType(node); + case 162: return checkSourceElement(node.type); - case 213: - return checkFunctionDeclaration(node); - case 192: - case 219: - return checkBlock(node); - case 193: - return checkVariableStatement(node); - case 195: - return checkExpressionStatement(node); - case 196: - return checkIfStatement(node); - case 197: - return checkDoStatement(node); - case 198: - return checkWhileStatement(node); - case 199: - return checkForStatement(node); - case 200: - return checkForInStatement(node); - case 201: - return checkForOfStatement(node); - case 202: - case 203: - return checkBreakOrContinueStatement(node); - case 204: - return checkReturnStatement(node); - case 205: - return checkWithStatement(node); - case 206: - return checkSwitchStatement(node); - case 207: - return checkLabeledStatement(node); - case 208: - return checkThrowStatement(node); - case 209: - return checkTryStatement(node); - case 211: - return checkVariableDeclaration(node); - case 163: - return checkBindingElement(node); - case 214: - return checkClassDeclaration(node); - case 215: - return checkInterfaceDeclaration(node); - case 216: - return checkTypeAliasDeclaration(node); case 217: - return checkEnumDeclaration(node); - case 218: - return checkModuleDeclaration(node); - case 222: - return checkImportDeclaration(node); - case 221: - return checkImportEqualsDeclaration(node); - case 228: - return checkExportDeclaration(node); - case 227: - return checkExportAssignment(node); - case 194: - checkGrammarStatementInAmbientContext(node); - return; + return checkFunctionDeclaration(node); + case 196: + case 223: + return checkBlock(node); + case 197: + return checkVariableStatement(node); + case 199: + return checkExpressionStatement(node); + case 200: + return checkIfStatement(node); + case 201: + return checkDoStatement(node); + case 202: + return checkWhileStatement(node); + case 203: + return checkForStatement(node); + case 204: + return checkForInStatement(node); + case 205: + return checkForOfStatement(node); + case 206: + case 207: + return checkBreakOrContinueStatement(node); + case 208: + return checkReturnStatement(node); + case 209: + return checkWithStatement(node); case 210: + return checkSwitchStatement(node); + case 211: + return checkLabeledStatement(node); + case 212: + return checkThrowStatement(node); + case 213: + return checkTryStatement(node); + case 215: + return checkVariableDeclaration(node); + case 167: + return checkBindingElement(node); + case 218: + return checkClassDeclaration(node); + case 219: + return checkInterfaceDeclaration(node); + case 220: + return checkTypeAliasDeclaration(node); + case 221: + return checkEnumDeclaration(node); + case 222: + return checkModuleDeclaration(node); + case 226: + return checkImportDeclaration(node); + case 225: + return checkImportEqualsDeclaration(node); + case 232: + return checkExportDeclaration(node); + case 231: + return checkExportAssignment(node); + case 198: checkGrammarStatementInAmbientContext(node); return; - case 231: + case 214: + checkGrammarStatementInAmbientContext(node); + return; + case 235: return checkMissingDeclaration(node); } } - function checkFunctionAndClassExpressionBodies(node) { - switch (node.kind) { - case 173: - case 174: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - checkFunctionExpressionOrObjectLiteralMethodBody(node); - break; - case 186: - ts.forEach(node.members, checkSourceElement); - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; - case 143: - case 142: - ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - if (ts.isObjectLiteralMethod(node)) { - checkFunctionExpressionOrObjectLiteralMethodBody(node); - } - break; - case 144: - case 145: - case 146: - case 213: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - break; - case 205: - checkFunctionAndClassExpressionBodies(node.expression); - break; - case 139: - case 138: - case 141: - case 140: - case 161: - case 162: - case 163: - case 164: - case 165: - case 245: - case 166: - case 167: - case 168: - case 169: - case 170: - case 183: - case 190: - case 171: - case 189: - case 172: - case 176: - case 177: - case 178: - case 175: - case 179: - case 180: - case 181: - case 182: - case 185: - case 184: - case 192: - case 219: - case 193: - case 195: - case 196: - case 197: - case 198: - case 199: - case 200: - case 201: - case 202: - case 203: - case 204: - case 206: - case 220: - case 241: - case 242: - case 207: - case 208: - case 209: - case 244: - case 211: - case 212: - case 214: - case 243: - case 188: - case 217: - case 247: - case 227: - case 248: - case 240: - case 233: - case 234: - case 238: - case 239: - case 235: - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 177: + case 178: + case 145: + case 144: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 147: + case 148: + checkAccessorDeferred(node); + break; + case 190: + checkClassExpressionDeferred(node); + break; + } } } function checkSourceFile(node) { @@ -21987,38 +23795,24 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1)) { - if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) { - return; + if (compilerOptions.skipDefaultLibCheck) { + if (node.hasNoDefaultLib) { + return; + } } checkGrammarSourceFile(node); - emitExtends = false; - emitDecorate = false; - emitParam = false; potentialThisCollisions.length = 0; + deferredNodes = []; ts.forEach(node.statements, checkSourceElement); - checkFunctionAndClassExpressionBodies(node); - if (ts.isExternalModule(node)) { + checkDeferredNodes(); + deferredNodes = undefined; + if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } if (potentialThisCollisions.length) { ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); potentialThisCollisions.length = 0; } - if (emitExtends) { - links.flags |= 8; - } - if (emitDecorate) { - links.flags |= 16; - } - if (emitParam) { - links.flags |= 32; - } - if (emitAwaiter) { - links.flags |= 64; - } - if (emitGenerator || (emitAwaiter && languageVersion < 2)) { - links.flags |= 128; - } links.flags |= 1; } } @@ -22052,7 +23846,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 205 && node.parent.statement === node) { + if (node.parent.kind === 209 && node.parent.statement === node) { return true; } node = node.parent; @@ -22074,28 +23868,28 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 248: - if (!ts.isExternalModule(location)) { + case 252: + if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 218: + case 222: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); break; - case 217: + case 221: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 186: + case 190: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 214: - case 215: - if (!(memberFlags & 64)) { + case 218: + case 219: + if (!(memberFlags & 32)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; - case 173: + case 177: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -22134,36 +23928,47 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 137: - case 214: - case 215: - case 216: - case 217: + case 139: + case 218: + case 219: + case 220: + case 221: return true; } } function isTypeReferenceIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 135) { + while (node.parent && node.parent.kind === 137) { node = node.parent; } - return node.parent && node.parent.kind === 151; + return node.parent && node.parent.kind === 153; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 166) { + while (node.parent && node.parent.kind === 170) { node = node.parent; } - return node.parent && node.parent.kind === 188; + return node.parent && node.parent.kind === 192; + } + function isNodeWithinClass(node, classDeclaration) { + while (true) { + node = ts.getContainingClass(node); + if (!node) { + return false; + } + if (node === classDeclaration) { + return true; + } + } } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 135) { + while (nodeOnRightSide.parent.kind === 137) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 221) { + if (nodeOnRightSide.parent.kind === 225) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 227) { + if (nodeOnRightSide.parent.kind === 231) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -22175,10 +23980,22 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 227) { + if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 170) { + var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1: + case 3: + return getSymbolOfNode(entityName.parent); + case 4: + case 2: + return getSymbolOfNode(entityName.parent.parent); + default: + } + } + if (entityName.parent.kind === 231) { return resolveEntityName(entityName, 107455 | 793056 | 1536 | 8388608); } - if (entityName.kind !== 166) { + if (entityName.kind !== 170) { if (isInRightSideOfImportOrExportAssignment(entityName)) { return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); } @@ -22188,7 +24005,7 @@ var ts; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; - if (entityName.parent.kind === 188) { + if (entityName.parent.kind === 192) { meaning = 793056; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { meaning |= 107455; @@ -22200,10 +24017,10 @@ var ts; meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if ((entityName.parent.kind === 235) || - (entityName.parent.kind === 234) || - (entityName.parent.kind === 237)) { - return getJsxElementTagSymbol(entityName.parent); + else if ((entityName.parent.kind === 239) || + (entityName.parent.kind === 238) || + (entityName.parent.kind === 241)) { + return getJsxTagSymbol(entityName.parent); } else if (ts.isExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { @@ -22213,14 +24030,14 @@ var ts; var meaning = 107455 | 8388608; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 166) { + else if (entityName.kind === 170) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 135) { + else if (entityName.kind === 137) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -22229,14 +24046,14 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 151 ? 793056 : 1536; + var meaning = entityName.parent.kind === 153 ? 793056 : 1536; meaning |= 8388608; return resolveEntityName(entityName, meaning); } - else if (entityName.parent.kind === 238) { + else if (entityName.parent.kind === 242) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 150) { + if (entityName.parent.kind === 152) { return resolveEntityName(entityName, 1); } return undefined; @@ -22250,12 +24067,12 @@ var ts; } if (node.kind === 69) { if (isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 227 + return node.parent.kind === 231 ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } - else if (node.parent.kind === 163 && - node.parent.parent.kind === 161 && + else if (node.parent.kind === 167 && + node.parent.parent.kind === 165 && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -22266,28 +24083,30 @@ var ts; } switch (node.kind) { case 69: - case 166: - case 135: + case 170: + case 137: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 97: case 95: var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; + case 163: + return getTypeFromTypeNode(node).symbol; case 121: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 144) { + if (constructorDeclaration && constructorDeclaration.kind === 146) { return constructorDeclaration.parent.symbol; } return undefined; case 9: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 222 || node.parent.kind === 228) && + ((node.parent.kind === 226 || node.parent.kind === 232) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } case 8: - if (node.parent.kind === 167 && node.parent.argumentExpression === node) { + if (node.parent.kind === 171 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -22301,11 +24120,16 @@ var ts; return undefined; } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 246) { - return resolveEntityName(location.name, 107455); + if (location && location.kind === 250) { + return resolveEntityName(location.name, 107455 | 8388608); } return undefined; } + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 | 793056 | 1536 | 8388608); + } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { return unknownType; @@ -22353,7 +24177,7 @@ var ts; } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 64 + return node.flags & 32 ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -22371,15 +24195,15 @@ var ts; } function getRootSymbols(symbol) { if (symbol.flags & 268435456) { - var symbols = []; - var name_16 = symbol.name; + var symbols_3 = []; + var name_17 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_16); + var symbol = getPropertyOfType(t, name_17); if (symbol) { - symbols.push(symbol); + symbols_3.push(symbol); } }); - return symbols; + return symbols_3; } else if (symbol.flags & 67108864) { var target = getSymbolLinks(symbol).target; @@ -22392,6 +24216,25 @@ var ts; function isArgumentsLocalBinding(node) { return getReferencedValueSymbol(node) === argumentsSymbol; } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol) { + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455) + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455); + } + } function getReferencedExportContainer(node) { var symbol = getReferencedValueSymbol(node); if (symbol) { @@ -22404,11 +24247,11 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 248) { + if (parentSymbol.flags & 512 && parentSymbol.valueDeclaration.kind === 252) { return parentSymbol.valueDeclaration; } for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 218 || n.kind === 217) && getSymbolOfNode(n) === parentSymbol) { + if ((n.kind === 222 || n.kind === 221) && getSymbolOfNode(n) === parentSymbol) { return n; } } @@ -22419,54 +24262,56 @@ var ts; var symbol = getReferencedValueSymbol(node); return symbol && symbol.flags & 8388608 ? getDeclarationOfAliasSymbol(symbol) : undefined; } - function isStatementWithLocals(node) { - switch (node.kind) { - case 192: - case 220: - case 199: - case 200: - case 201: - return true; - } - return false; - } - function isNestedRedeclarationSymbol(symbol) { + function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418) { var links = getSymbolLinks(symbol); - if (links.isNestedRedeclaration === undefined) { + if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - links.isNestedRedeclaration = isStatementWithLocals(container) && - !!resolveName(container.parent, symbol.name, 107455, undefined, undefined); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.name, 107455, undefined, undefined)) { + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 131072) { + var isDeclaredInLoop = nodeLinks_1.flags & 262144; + var inLoopInitializer = ts.isIterationStatement(container, false); + var inLoopBodyBlock = container.kind === 196 && ts.isIterationStatement(container.parent, false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } } - return links.isNestedRedeclaration; + return links.isDeclarationWithCollidingName; } return false; } - function getReferencedNestedRedeclaration(node) { + function getReferencedDeclarationWithCollidingName(node) { var symbol = getReferencedValueSymbol(node); - return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + return symbol && isSymbolOfDeclarationWithCollidingName(symbol) ? symbol.valueDeclaration : undefined; } - function isNestedRedeclaration(node) { - return isNestedRedeclarationSymbol(getSymbolOfNode(node)); + function isDeclarationWithCollidingName(node) { + return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); } function isValueAliasDeclaration(node) { switch (node.kind) { - case 221: - case 223: - case 224: - case 226: - case 230: - return isAliasResolvedToValue(getSymbolOfNode(node)); + case 225: + case 227: case 228: + case 230: + case 234: + return isAliasResolvedToValue(getSymbolOfNode(node)); + case 232: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 227: + case 231: return node.expression && node.expression.kind === 69 ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 248 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 252 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -22514,7 +24359,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 247) { + if (node.kind === 251) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -22545,22 +24390,22 @@ var ts; else if (type.flags & 1) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (allConstituentTypesHaveKind(type, 16)) { + else if (isTypeOfKind(type, 16)) { return ts.TypeReferenceSerializationKind.VoidType; } - else if (allConstituentTypesHaveKind(type, 8)) { + else if (isTypeOfKind(type, 8)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (allConstituentTypesHaveKind(type, 132)) { + else if (isTypeOfKind(type, 132)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (allConstituentTypesHaveKind(type, 258)) { + else if (isTypeOfKind(type, 258)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (allConstituentTypesHaveKind(type, 8192)) { + else if (isTypeOfKind(type, 8192)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (allConstituentTypesHaveKind(type, 16777216)) { + else if (isTypeOfKind(type, 16777216)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -22600,23 +24445,12 @@ var ts; var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } - function instantiateSingleCallFunctionType(functionType, typeArguments) { - if (functionType === unknownType) { - return unknownType; - } - var signature = getSingleCallSignature(functionType); - if (!signature) { - return unknownType; - } - var instantiatedSignature = getSignatureInstantiation(signature, typeArguments); - return getOrCreateTypeFromSignature(instantiatedSignature); - } function createResolver() { return { getReferencedExportContainer: getReferencedExportContainer, getReferencedImportDeclaration: getReferencedImportDeclaration, - getReferencedNestedRedeclaration: getReferencedNestedRedeclaration, - isNestedRedeclaration: isNestedRedeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, isValueAliasDeclaration: isValueAliasDeclaration, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: isReferencedAliasDeclaration, @@ -22634,22 +24468,45 @@ var ts; getReferencedValueDeclaration: getReferencedValueDeclaration, getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, isOptionalParameter: isOptionalParameter, - isArgumentsLocalBinding: isArgumentsLocalBinding + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration }; } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 252); + } function initializeTypeChecker() { ts.forEach(host.getSourceFiles(), function (file) { ts.bindSourceFile(file, compilerOptions); }); + var augmentations; ts.forEach(host.getSourceFiles(), function (file) { - if (!ts.isExternalModule(file)) { + if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } }); + if (augmentations) { + for (var _i = 0, augmentations_1 = augmentations; _i < augmentations_1.length; _i++) { + var list = augmentations_1[_i]; + for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { + var augmentation = list_2[_a]; + mergeModuleAugmentation(augmentation); + } + } + } + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; - globals[undefinedSymbol.name] = undefinedSymbol; globalArrayType = getGlobalType("Array", 1); globalObjectType = getGlobalType("Object"); globalFunctionType = getGlobalType("Function"); @@ -22687,6 +24544,9 @@ var ts; globalIterableIteratorType = emptyGenericType; } anyArrayType = createArrayType(anyType); + var symbol = getGlobalSymbol("ReadonlyArray", 793056, undefined); + globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); @@ -22710,9 +24570,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + if (node.kind === 145 && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } } - else if (node.kind === 145 || node.kind === 146) { + else if (node.kind === 147 || node.kind === 148) { 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); @@ -22722,38 +24587,38 @@ var ts; } function checkGrammarModifiers(node) { switch (node.kind) { - case 145: + case 147: + case 148: case 146: - case 144: - case 141: - case 140: case 143: case 142: - case 149: - case 218: + case 145: + case 144: + case 151: case 222: - case 221: - case 228: - case 227: - case 138: - break; - case 213: - if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && - node.parent.kind !== 219 && node.parent.kind !== 248) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - break; - case 214: - case 215: - case 193: - case 216: - if (node.modifiers && node.parent.kind !== 219 && node.parent.kind !== 248) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } + case 226: + case 225: + case 232: + case 231: + case 140: break; case 217: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118) && + node.parent.kind !== 223 && node.parent.kind !== 252) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 218: + case 219: + case 197: + case 220: + if (node.modifiers && node.parent.kind !== 223 && node.parent.kind !== 252) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 221: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74) && - node.parent.kind !== 219 && node.parent.kind !== 248) { + node.parent.kind !== 223 && node.parent.kind !== 252) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; @@ -22763,37 +24628,48 @@ var ts; if (!node.modifiers) { return; } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync; + var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (modifier.kind !== 127) { + if (node.kind === 142 || node.kind === 144) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 151) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } switch (modifier.kind) { + case 74: + if (node.kind !== 221 && node.parent.kind === 218) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74)); + } + break; case 112: case 111: case 110: - var text = void 0; - if (modifier.kind === 112) { - text = "public"; - } - else if (modifier.kind === 111) { - text = "protected"; + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (modifier.kind === 111) { lastProtected = modifier; } - else { - text = "private"; + else if (modifier.kind === 110) { lastPrivate = modifier; } - if (flags & 56) { + if (flags & 28) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & 64) { + else if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 219 || node.parent.kind === 248) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); + else if (node.parent.kind === 223 || node.parent.kind === 252) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128) { if (modifier.kind === 110) { @@ -22806,29 +24682,42 @@ var ts; flags |= ts.modifierToFlag(modifier.kind); break; case 113: - if (flags & 64) { + if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 219 || node.parent.kind === 248) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); + else if (node.parent.kind === 223 || node.parent.kind === 252) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 138) { + else if (node.kind === 140) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= 64; + flags |= 32; lastStatic = modifier; break; + case 127: + if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 143 && node.kind !== 142 && node.kind !== 151) { + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64; + lastReadonly = modifier; + break; case 82: - if (flags & 2) { + if (flags & 1) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & 4) { + else if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } else if (flags & 128) { @@ -22837,48 +24726,51 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 218) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 138) { + else if (node.kind === 140) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= 2; + flags |= 1; break; case 122: - if (flags & 4) { + if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 214) { + else if (node.parent.kind === 218) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 138) { + else if (node.kind === 140) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 223) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= 4; + flags |= 2; lastDeclare = modifier; break; case 115: if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 214) { - if (node.kind !== 143) { - return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); + if (node.kind !== 218) { + if (node.kind !== 145 && + node.kind !== 143 && + node.kind !== 147 && + node.kind !== 148) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 214 && node.parent.flags & 128)) { + if (!(node.parent.kind === 218 && node.parent.flags & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & 64) { + if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 16) { + if (flags & 8) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } @@ -22888,10 +24780,10 @@ var ts; if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 4 || ts.isInAmbientContext(node.parent)) { + else if (flags & 2 || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 138) { + else if (node.kind === 140) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256; @@ -22899,28 +24791,25 @@ var ts; break; } } - if (node.kind === 144) { - if (flags & 64) { + if (node.kind === 146) { + if (flags & 32) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & 32) { - return grammarErrorOnNode(lastProtected, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); - } - else if (flags & 16) { - return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); - } else if (flags & 256) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } + else if (flags & 64) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } return; } - else if ((node.kind === 222 || node.kind === 221) && flags & 4) { + else if ((node.kind === 226 || node.kind === 225) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 138 && (flags & 56) && ts.isBindingPattern(node.name)) { + else if (node.kind === 140 && (flags & 28) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } if (flags & 256) { @@ -22932,10 +24821,10 @@ var ts; return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher); } switch (node.kind) { - case 143: - case 213: - case 173: - case 174: + case 145: + case 217: + case 177: + case 178: if (!node.asteriskToken) { return false; } @@ -23000,7 +24889,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 174) { + if (node.kind === 178) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -23023,7 +24912,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 1022) { + if (parameter.flags & 959) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -23035,20 +24924,15 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 130 && parameter.type.kind !== 128) { + if (parameter.type.kind !== 131 && parameter.type.kind !== 129) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } } - function checkGrammarForIndexSignatureModifier(node) { - if (node.flags & 1022) { - grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); - } - } function checkGrammarIndexSignature(node) { - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node) || checkGrammarForIndexSignatureModifier(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); } function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { if (typeArguments && typeArguments.length === 0) { @@ -23067,7 +24951,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { var arg = args_1[_i]; - if (arg.kind === 187) { + if (arg.kind === 191) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -23138,19 +25022,19 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 136) { + if (node.kind !== 138) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 181 && computedPropertyName.expression.operatorToken.kind === 24) { + if (computedPropertyName.expression.kind === 185 && computedPropertyName.expression.operatorToken.kind === 24) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 213 || - node.kind === 173 || - node.kind === 143); + ts.Debug.assert(node.kind === 217 || + node.kind === 177 || + node.kind === 145); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -23171,78 +25055,88 @@ var ts; var seen = {}; var Property = 1; var GetAccessor = 2; - var SetAccesor = 4; - var GetOrSetAccessor = GetAccessor | SetAccesor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - var name_17 = prop.name; - if (prop.kind === 187 || - name_17.kind === 136) { - checkGrammarComputedPropertyName(name_17); - continue; + var SetAccessor = 4; + var GetOrSetAccessor = GetAccessor | SetAccessor; + var _loop_1 = function(prop) { + var name_18 = prop.name; + if (prop.kind === 191 || + name_18.kind === 138) { + checkGrammarComputedPropertyName(name_18); + return "continue"; } - if (prop.kind === 246 && !inDestructuring && prop.objectAssignmentInitializer) { - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + if (prop.kind === 250 && !inDestructuring && prop.objectAssignmentInitializer) { + return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; } + ts.forEach(prop.modifiers, function (mod) { + if (mod.kind !== 118 || prop.kind !== 145) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + }); var currentKind = void 0; - if (prop.kind === 245 || prop.kind === 246) { + if (prop.kind === 249 || prop.kind === 250) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_17.kind === 8) { - checkGrammarNumericLiteral(name_17); + if (name_18.kind === 8) { + checkGrammarNumericLiteral(name_18); } currentKind = Property; } - else if (prop.kind === 143) { + else if (prop.kind === 145) { currentKind = Property; } - else if (prop.kind === 145) { + else if (prop.kind === 147) { currentKind = GetAccessor; } - else if (prop.kind === 146) { - currentKind = SetAccesor; + else if (prop.kind === 148) { + currentKind = SetAccessor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_17.text)) { - seen[name_17.text] = currentKind; + if (!ts.hasProperty(seen, name_18.text)) { + seen[name_18.text] = currentKind; } else { - var existingKind = seen[name_17.text]; + var existingKind = seen[name_18.text]; if (currentKind === Property && existingKind === Property) { - continue; + return "continue"; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_17.text] = currentKind | existingKind; + seen[name_18.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_17, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return { value: grammarErrorOnNode(name_18, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return grammarErrorOnNode(name_17, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return { value: grammarErrorOnNode(name_18, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } + }; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_1(prop); + if (typeof state_2 === "object") return state_2.value; + if (state_2 === "continue") continue; } } function checkGrammarJsxElement(node) { var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 239) { + if (attr.kind === 243) { continue; } var jsxAttr = attr; - var name_18 = jsxAttr.name; - if (!ts.hasProperty(seen, name_18.text)) { - seen[name_18.text] = true; + var name_19 = jsxAttr.name; + if (!ts.hasProperty(seen, name_19.text)) { + seen[name_19.text] = true; } else { - return grammarErrorOnNode(name_18, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_19, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 240 && !initializer.expression) { + if (initializer && initializer.kind === 244 && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -23251,24 +25145,28 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 212) { + if (forInOrOfStatement.initializer.kind === 216) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { - if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 200 + var declarations = variableList.declarations; + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 204 ? 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]; + var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 200 + var diagnostic = forInOrOfStatement.kind === 204 ? 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 === 200 + var diagnostic = forInOrOfStatement.kind === 204 ? 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); @@ -23285,16 +25183,16 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined) { + else if (accessor.body === undefined && !(accessor.flags & 128)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } - else if (kind === 145 && accessor.parameters.length) { + else if (kind === 147 && accessor.parameters.length) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); } - else if (kind === 146) { + else if (kind === 148) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -23306,7 +25204,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); } - else if (parameter.flags & 1022) { + else if (parameter.flags & 959) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } else if (parameter.questionToken) { @@ -23319,7 +25217,7 @@ var ts; } } function checkGrammarForNonSymbolComputedProperty(node, message) { - if (node.kind === 136 && !ts.isWellKnownSymbolSyntactically(node.expression)) { + if (ts.isDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -23329,12 +25227,12 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 165) { + if (node.parent.kind === 169) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } else if (node.body === undefined) { - return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (ts.isClassLike(node.parent)) { @@ -23348,10 +25246,10 @@ 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 === 215) { + else if (node.parent.kind === 219) { 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 === 155) { + else if (node.parent.kind === 157) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } @@ -23362,9 +25260,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 207: + case 211: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 202 + var isMisplacedContinueLabel = node.kind === 206 && !ts.isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -23372,8 +25270,8 @@ var ts; return false; } break; - case 206: - if (node.kind === 203 && !node.label) { + case 210: + if (node.kind === 207 && !node.label) { return false; } break; @@ -23386,13 +25284,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 203 + var message = node.kind === 207 ? 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 === 203 + var message = node.kind === 207 ? 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); @@ -23404,7 +25302,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 === 162 || node.name.kind === 161) { + if (node.name.kind === 166 || node.name.kind === 165) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -23413,7 +25311,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 200 && node.parent.parent.kind !== 201) { + if (node.parent.parent.kind !== 204 && node.parent.parent.kind !== 205) { if (ts.isInAmbientContext(node)) { if (node.initializer) { var equalsTokenLength = "=".length; @@ -23429,12 +25327,12 @@ var ts; } } } - var checkLetConstNames = languageVersion >= 2 && (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 69) { - if (name.text === "let") { + if (name.originalKeywordKind === 108) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -23442,7 +25340,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 187) { + if (element.kind !== 191) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -23459,15 +25357,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 196: - case 197: - case 198: - case 205: - case 199: case 200: case 201: + case 202: + case 209: + case 203: + case 204: + case 205: return false; - case 207: + case 211: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -23482,18 +25380,6 @@ var ts; } } } - function isIntegerLiteral(expression) { - if (expression.kind === 179) { - var unaryExpression = expression; - if (unaryExpression.operator === 35 || unaryExpression.operator === 36) { - expression = unaryExpression.operand; - } - } - if (expression.kind === 8) { - return /^[0-9]+([eE]\+?[0-9]+)?$/.test(expression.text); - } - return false; - } function hasParseDiagnostics(sourceFile) { return sourceFile.parseDiagnostics.length > 0; } @@ -23518,10 +25404,6 @@ var ts; return true; } } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 && - (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); @@ -23539,29 +25421,35 @@ var ts; return true; } } - else if (node.parent.kind === 215) { + else if (node.parent.kind === 219) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } } - else if (node.parent.kind === 155) { + else if (node.parent.kind === 157) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } } if (ts.isInAmbientContext(node) && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 215 || - node.kind === 216 || - node.kind === 222 || - node.kind === 221 || - node.kind === 228 || - node.kind === 227 || - (node.flags & 4) || - (node.flags & (2 | 512))) { + if (node.kind === 219 || + node.kind === 220 || + node.kind === 226 || + node.kind === 225 || + node.kind === 232 || + node.kind === 231 || + (node.flags & 2) || + (node.flags & (1 | 512))) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -23569,7 +25457,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 === 193) { + if (ts.isDeclaration(decl) || decl.kind === 197) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -23588,7 +25476,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 === 192 || node.parent.kind === 219 || node.parent.kind === 248) { + if (node.parent.kind === 196 || node.parent.kind === 223 || node.parent.kind === 252) { 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); @@ -23599,7 +25487,7 @@ var ts; } } function checkGrammarNumericLiteral(node) { - if (node.flags & 32768 && languageVersion >= 1) { + if (node.isOctalLiteral && languageVersion >= 1) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -23611,19 +25499,287 @@ var ts; return true; } } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); var ts; +(function (ts) { + var nullSourceMapWriter; + var defaultLastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitStart: function (range) { }, + emitEnd: function (range, stopOverridingSpan) { }, + emitPos: function (pos) { }, + changeEmitSourcePos: function () { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; }, + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var currentSourceFile; + var sourceMapDir; + var stopOverridingSpan = false; + var modifyLastSourcePos = false; + var sourceMapSourceIndex; + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + var sourceMapData; + return { + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + changeEmitSourcePos: changeEmitSourcePos, + getText: getText, + getSourceMappingURL: getSourceMappingURL, + initialize: initialize, + reset: reset + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + sourceMapSourceIndex = -1; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; + lastEncodedNameIndex = 0; + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, + sourceMapDecodedMappings: [] + }; + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + } + function updateLastEncodedAndRecordedSpans() { + if (modifyLastSourcePos) { + modifyLastSourcePos = false; + lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; + lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; + sourceMapData.sourceMapDecodedMappings.pop(); + lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? + sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : + defaultLastEncodedSourceMapSpan; + var sourceMapMappings = sourceMapData.sourceMapMappings; + var lenthToSet = sourceMapMappings.length - 1; + for (; lenthToSet >= 0; lenthToSet--) { + var currentChar = sourceMapMappings.charAt(lenthToSet); + if (currentChar === ",") { + break; + } + if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { + break; + } + } + sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); + } + } + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this"); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (pos === -1) { + return; + } + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + if (!lastRecordedSourceMapSpan || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || + (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + sourceIndex: sourceMapSourceIndex + }; + stopOverridingSpan = false; + } + else if (!stopOverridingSpan) { + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + updateLastEncodedAndRecordedSpans(); + } + function getStartPos(range) { + var rangeHasDecorators = !!range.decorators; + return range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1; + } + function emitStart(range) { + emitPos(getStartPos(range)); + } + function emitEnd(range, stopOverridingEnd) { + emitPos(range.end); + stopOverridingSpan = stopOverridingEnd; + } + function changeEmitSourcePos() { + ts.Debug.assert(!modifyLastSourcePos); + modifyLastSourcePos = true; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + ts.createSourceMapWriter = createSourceMapWriter; + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } +})(ts || (ts = {})); +var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var diagnostics = []; - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); - emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; + var declarationDiagnostics = ts.createDiagnosticCollection(); + ts.forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); + return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName); + function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { + var declarationFilePath = _a.declarationFilePath; + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -23631,78 +25787,94 @@ var ts; var increaseIndent; var decreaseIndent; var writeTextOfNode; - var writer = createAndSetNewTextWriterWithSymbolWriter(); + var writer; + createAndSetNewTextWriterWithSymbolWriter(); var enclosingDeclaration; - var currentSourceFile; + var resultHasExternalModuleIndicator; + var currentText; + var currentLineMap; + var currentIdentifiers; + var isCurrentFileExternalModule; var reportedDeclarationError = false; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; + var noDeclare; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencePathsOutput = ""; - if (root) { + var emittedReferencedFiles = []; + var addedGlobalFileReference = false; + var allSourcesModuleElementDeclarationEmitInfo = []; + ts.forEach(sourceFiles, function (sourceFile) { + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; - ts.forEach(root.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); - if (referencedFile && ((referencedFile.flags & 4096) || - ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || - !addedGlobalFileReference)) { - writeReferencePath(referencedFile); - if (!ts.isExternalModuleOrDeclarationFile(referencedFile)) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } + emittedReferencedFiles.push(referencedFile); } }); } - emitSourceFile(root); + resultHasExternalModuleIndicator = false; + if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { + noDeclare = false; + emitSourceFile(sourceFile); + } + else if (ts.isExternalModule(sourceFile)) { + noDeclare = true; + write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); + writeLine(); + increaseIndent(); + emitSourceFile(sourceFile); + decreaseIndent(); + write("}"); + writeLine(); + } if (moduleElementDeclarationEmitInfo.length) { var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222); + if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { + ts.Debug.assert(aliasEmitInfo.node.kind === 226); createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0); + ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + increaseIndent(); + } writeImportDeclaration(aliasEmitInfo.node); aliasEmitInfo.asynchronousOutput = writer.getText(); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + decreaseIndent(); + } } }); setWriter(oldWriter); + allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); + moduleElementDeclarationEmitInfo = []; } - } - else { - var emittedReferencedFiles = []; - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) { - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - if (referencedFile && (ts.isExternalModuleOrDeclarationFile(referencedFile) && - !ts.contains(emittedReferencedFiles, referencedFile))) { - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - emitSourceFile(sourceFile); - } - }); - } + if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + write("export {};"); + writeLine(); + } + }); return { reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: moduleElementDeclarationEmitInfo, + moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput: referencePathsOutput }; function hasInternalAnnotation(range) { - var text = currentSourceFile.text; - var comment = text.substring(range.pos, range.end); + var comment = currentText.substring(range.pos, range.end); return comment.indexOf("@internal") >= 0; } function stripInternal(node) { if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { return; } @@ -23721,7 +25893,6 @@ var ts; writer.writeParameter = writer.write; writer.writeSymbol = writer.write; setWriter(writer); - return writer; } function setWriter(newWriter) { writer = newWriter; @@ -23735,10 +25906,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 211) { + if (declaration.kind === 215) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 225 || declaration.kind === 226 || declaration.kind === 223) { + else if (declaration.kind === 229 || declaration.kind === 230 || declaration.kind === 227) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -23749,7 +25920,7 @@ var ts; moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); } if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 222) { + if (moduleElementEmitInfo.node.kind === 226) { moduleElementEmitInfo.isVisible = true; } else { @@ -23757,12 +25928,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 218) { + if (nodeToCheck.kind === 222) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 218) { + if (nodeToCheck.kind === 222) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -23772,21 +25943,21 @@ var ts; }); setWriter(oldWriter); } - function handleSymbolAccessibilityError(symbolAccesibilityResult) { - if (symbolAccesibilityResult.accessibility === 0) { - if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccesibilityResult.aliasesToMakeVisible); + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0) { + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); } } else { reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); if (errorInfo) { if (errorInfo.typeName) { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); } else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); } } } @@ -23796,7 +25967,8 @@ var ts; } function reportInaccessibleThisError() { if (errorNameNode) { - diagnostics.push(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { @@ -23847,9 +26019,9 @@ var ts; } function writeJsDocComments(declaration) { if (declaration) { - var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile); - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); - ts.emitComments(currentSourceFile, writer, jsDocComments, true, newLine, ts.writeCommentRange); + var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -23859,62 +26031,62 @@ var ts; function emitType(type) { switch (type.kind) { case 117: - case 130: - case 128: - case 120: case 131: + case 129: + case 120: + case 132: case 103: - case 97: - case 9: - return writeTextOfNode(currentSourceFile, type); - case 188: + case 163: + case 164: + return writeTextOfNode(currentText, type); + case 192: return emitExpressionWithTypeArguments(type); - case 151: - return emitTypeReference(type); - case 154: - return emitTypeQuery(type); - case 156: - return emitArrayType(type); - case 157: - return emitTupleType(type); - case 158: - return emitUnionType(type); - case 159: - return emitIntersectionType(type); - case 160: - return emitParenType(type); - case 152: case 153: - return emitSignatureDeclarationWithJsDocComments(type); + return emitTypeReference(type); + case 156: + return emitTypeQuery(type); + case 158: + return emitArrayType(type); + case 159: + return emitTupleType(type); + case 160: + return emitUnionType(type); + case 161: + return emitIntersectionType(type); + case 162: + return emitParenType(type); + case 154: case 155: + return emitSignatureDeclarationWithJsDocComments(type); + case 157: return emitTypeLiteral(type); case 69: return emitEntityName(type); - case 135: + case 137: return emitEntityName(type); - case 150: + case 152: return emitTypePredicate(type); } function writeEntityName(entityName) { if (entityName.kind === 69) { - writeTextOfNode(currentSourceFile, entityName); + writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 135 ? entityName.left : entityName.expression; - var right = entityName.kind === 135 ? entityName.right : entityName.name; + var left = entityName.kind === 137 ? entityName.left : entityName.expression; + var right = entityName.kind === 137 ? entityName.right : entityName.name; writeEntityName(left); write("."); - writeTextOfNode(currentSourceFile, right); + writeTextOfNode(currentText, right); } } function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 221 ? entityName.parent : enclosingDeclaration); + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 225 ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 166); + ts.Debug.assert(node.expression.kind === 69 || node.expression.kind === 170); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -23932,7 +26104,7 @@ var ts; } } function emitTypePredicate(type) { - writeTextOfNode(currentSourceFile, type.parameterName); + writeTextOfNode(currentText, type.parameterName); write(" is "); emitType(type.type); } @@ -23972,28 +26144,32 @@ var ts; } } function emitSourceFile(node) { - currentSourceFile = node; + currentText = node.text; + currentLineMap = ts.getLineStarts(node); + currentIdentifiers = node.identifiers; + isCurrentFileExternalModule = ts.isExternalModule(node); enclosingDeclaration = node; - ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true); + ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) { + if (!ts.hasProperty(currentIdentifiers, baseName)) { return baseName; } var count = 0; while (true) { - var name_19 = baseName + "_" + (++count); - if (!ts.hasProperty(currentSourceFile.identifiers, name_19)) { - return name_19; + count++; + var name_20 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_20)) { + return name_20; } } } function emitExportAssignment(node) { if (node.expression.kind === 69) { write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentSourceFile, node.expression); + writeTextOfNode(currentText, node.expression); } else { var tempVarName = getExportDefaultTempVariableName(); @@ -24027,10 +26203,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 221 || - (node.parent.kind === 248 && ts.isExternalModule(currentSourceFile))) { - var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248) { + else if (node.kind === 225 || + (node.parent.kind === 252 && isCurrentFileExternalModule)) { + var isVisible = void 0; + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 252) { asynchronousSubModuleDeclarationEmitInfo.push({ node: node, outputPos: writer.getTextPos(), @@ -24039,7 +26215,7 @@ var ts; }); } else { - if (node.kind === 222) { + if (node.kind === 226) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -24057,62 +26233,65 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 213: - return writeFunctionDeclaration(node); - case 193: - return writeVariableStatement(node); - case 215: - return writeInterfaceDeclaration(node); - case 214: - return writeClassDeclaration(node); - case 216: - return writeTypeAliasDeclaration(node); case 217: - return writeEnumDeclaration(node); + return writeFunctionDeclaration(node); + case 197: + return writeVariableStatement(node); + case 219: + return writeInterfaceDeclaration(node); case 218: - return writeModuleDeclaration(node); + return writeClassDeclaration(node); + case 220: + return writeTypeAliasDeclaration(node); case 221: - return writeImportEqualsDeclaration(node); + return writeEnumDeclaration(node); case 222: + return writeModuleDeclaration(node); + case 225: + return writeImportEqualsDeclaration(node); + case 226: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); } } function emitModuleElementDeclarationFlags(node) { - if (node.parent === currentSourceFile) { - if (node.flags & 2) { + if (node.parent.kind === 252) { + if (node.flags & 1) { write("export "); } if (node.flags & 512) { write("default "); } - else if (node.kind !== 215) { + else if (node.kind !== 219 && !noDeclare) { write("declare "); } } } - function emitClassMemberDeclarationFlags(node) { - if (node.flags & 16) { + function emitClassMemberDeclarationFlags(flags) { + if (flags & 8) { write("private "); } - else if (node.flags & 32) { + else if (flags & 16) { write("protected "); } - if (node.flags & 64) { + if (flags & 32) { write("static "); } - if (node.flags & 128) { + if (flags & 64) { + write("readonly "); + } + if (flags & 128) { write("abstract "); } } function writeImportEqualsDeclaration(node) { emitJsDocComments(node); - if (node.flags & 2) { + if (node.flags & 1) { write("export "); } write("import "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" = "); if (ts.isInternalModuleImportEqualsDeclaration(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); @@ -24120,11 +26299,11 @@ var ts; } else { write("require("); - writeTextOfNode(currentSourceFile, ts.getExternalModuleImportEqualsDeclarationExpression(node)); + emitExternalModuleSpecifier(node); write(");"); } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccesibilityResult) { + function getImportEntityNameVisibilityError(symbolAccessibilityResult) { return { diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -24134,7 +26313,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 224) { + if (namedBindings.kind === 228) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -24143,26 +26322,23 @@ var ts; } } function writeImportDeclaration(node) { - if (!node.importClause && !(node.flags & 2)) { - return; - } emitJsDocComments(node); - if (node.flags & 2) { + if (node.flags & 1) { write("export "); } write("import "); if (node.importClause) { var currentWriterPos = writer.getTextPos(); if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentSourceFile, node.importClause.name); + writeTextOfNode(currentText, node.importClause.name); } if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { if (currentWriterPos !== writer.getTextPos()) { write(", "); } - if (node.importClause.namedBindings.kind === 224) { + if (node.importClause.namedBindings.kind === 228) { write("* as "); - writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name); + writeTextOfNode(currentText, node.importClause.namedBindings.name); } else { write("{ "); @@ -24172,16 +26348,41 @@ var ts; } write(" from "); } - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); write(";"); writer.writeLine(); } + function emitExternalModuleSpecifier(parent) { + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 222; + var moduleSpecifier; + if (parent.kind === 225) { + var node = parent; + moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); + } + else if (parent.kind === 222) { + moduleSpecifier = parent.name; + } + else { + var node = parent; + moduleSpecifier = node.moduleSpecifier; + } + if (moduleSpecifier.kind === 9 && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); + if (moduleName) { + write("\""); + write(moduleName); + write("\""); + return; + } + } + writeTextOfNode(currentText, moduleSpecifier); + } function emitImportOrExportSpecifier(node) { if (node.propertyName) { - writeTextOfNode(currentSourceFile, node.propertyName); + writeTextOfNode(currentText, node.propertyName); write(" as "); } - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } function emitExportSpecifier(node) { emitImportOrExportSpecifier(node); @@ -24201,7 +26402,7 @@ var ts; } if (node.moduleSpecifier) { write(" from "); - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); } write(";"); writer.writeLine(); @@ -24209,17 +26410,27 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 65536) { - write("namespace "); + if (ts.isGlobalScopeAugmentation(node)) { + write("global "); } else { - write("module "); + if (node.flags & 4096) { + write("namespace "); + } + else { + write("module "); + } + if (ts.isExternalModuleAugmentation(node)) { + emitExternalModuleSpecifier(node); + } + else { + writeTextOfNode(currentText, node.name); + } } - writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 219) { + while (node.body.kind !== 223) { node = node.body; write("."); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; @@ -24238,14 +26449,14 @@ var ts; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("type "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); emitTypeParameters(node.typeParameters); write(" = "); emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); write(";"); writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult) { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -24260,7 +26471,7 @@ var ts; write("const "); } write("enum "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" {"); writeLine(); increaseIndent(); @@ -24271,7 +26482,7 @@ var ts; } function emitEnumMemberDeclaration(node) { emitJsDocComments(node); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); @@ -24281,59 +26492,59 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 143 && (node.parent.flags & 16); + return node.parent.kind === 145 && (node.parent.flags & 8); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { increaseIndent(); emitJsDocComments(node); decreaseIndent(); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); if (node.constraint && !isPrivateMethodTypeParameter(node)) { write(" extends "); - if (node.parent.kind === 152 || - node.parent.kind === 153 || - (node.parent.parent && node.parent.parent.kind === 155)) { - ts.Debug.assert(node.parent.kind === 143 || - node.parent.kind === 142 || - node.parent.kind === 152 || - node.parent.kind === 153 || - node.parent.kind === 147 || - node.parent.kind === 148); + if (node.parent.kind === 154 || + node.parent.kind === 155 || + (node.parent.parent && node.parent.parent.kind === 157)) { + ts.Debug.assert(node.parent.kind === 145 || + node.parent.kind === 144 || + node.parent.kind === 154 || + node.parent.kind === 155 || + node.parent.kind === 149 || + node.parent.kind === 150); emitType(node.constraint); } else { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); } } - function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { + function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.parent.kind) { - case 214: + case 218: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 215: + case 219: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 148: + case 150: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 147: + case 149: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 143: - case 142: - if (node.parent.flags & 64) { + case 145: + case 144: + if (node.parent.flags & 32) { 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 === 214) { + else if (node.parent.parent.kind === 218) { 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 213: + case 217: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -24364,9 +26575,9 @@ var ts; else if (!isImplementsList && node.expression.kind === 93) { write("null"); } - function getHeritageClauseVisibilityError(symbolAccesibilityResult) { + function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.parent.parent.kind === 214) { + if (node.parent.parent.kind === 218) { 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; @@ -24386,7 +26597,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 56) { + if (param.flags & 28) { emitPropertyDeclaration(param); } }); @@ -24398,7 +26609,7 @@ var ts; write("abstract "); } write("class "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -24421,7 +26632,7 @@ var ts; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("interface "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -24440,61 +26651,61 @@ var ts; return; } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node); + emitClassMemberDeclarationFlags(node.flags); emitVariableDeclaration(node); write(";"); writeLine(); } function emitVariableDeclaration(node) { - if (node.kind !== 211 || resolver.isDeclarationVisible(node)) { + if (node.kind !== 215 || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } else { - writeTextOfNode(currentSourceFile, node.name); - if ((node.kind === 141 || node.kind === 140) && ts.hasQuestionToken(node)) { + writeTextOfNode(currentText, node.name); + if ((node.kind === 143 || node.kind === 142) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 141 || node.kind === 140) && node.parent.kind === 155) { + if ((node.kind === 143 || node.kind === 142) && node.parent.kind === 157) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 16)) { + else if (!(node.flags & 8)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 211) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 215) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 === 141 || node.kind === 140) { - if (node.flags & 64) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + else if (node.kind === 143 || node.kind === 142) { + if (node.flags & 32) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : 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 === 214) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + else if (node.parent.kind === 218) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; } else { - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; } } } - function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: node, @@ -24505,15 +26716,15 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187) { + if (element.kind !== 191) { elements.push(element); } } emitCommaList(elements, emitBindingElement); } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: bindingElement, @@ -24525,7 +26736,7 @@ var ts; emitBindingPattern(bindingElement.name); } else { - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); writeTypeOfDeclaration(bindingElement, undefined, getBindingElementTypeVisibilityError); } } @@ -24565,13 +26776,13 @@ var ts; if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node); - writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 16)) { + emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : 64)); + writeTextOfNode(currentText, node.name); + if (!(node.flags & 8)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { - var anotherAccessor = node.kind === 145 ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 147 ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -24584,23 +26795,23 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 145 + return accessor.kind === 147 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type : undefined; } } - function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 146) { - if (accessorWithTypeAnnotation.parent.flags & 64) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + if (accessorWithTypeAnnotation.kind === 148) { + if (accessorWithTypeAnnotation.parent.flags & 32) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; } @@ -24611,16 +26822,16 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 64) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + if (accessorWithTypeAnnotation.flags & 32) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; @@ -24639,21 +26850,21 @@ var ts; } if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 213) { + if (node.kind === 217) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 143) { - emitClassMemberDeclarationFlags(node); + else if (node.kind === 145 || node.kind === 146) { + emitClassMemberDeclarationFlags(node.flags); } - if (node.kind === 213) { + if (node.kind === 217) { write("function "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } - else if (node.kind === 144) { + else if (node.kind === 146) { write("constructor"); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); if (ts.hasQuestionToken(node)) { write("?"); } @@ -24666,33 +26877,34 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { - if (node.kind === 148 || node.kind === 153) { - write("new "); - } - emitTypeParameters(node.typeParameters); - if (node.kind === 149) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + if (node.kind === 151) { + emitClassMemberDeclarationFlags(node.flags); write("["); } else { + if (node.kind === 150 || node.kind === 155) { + write("new "); + } + emitTypeParameters(node.typeParameters); write("("); } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 149) { + if (node.kind === 151) { write("]"); } else { write(")"); } - var isFunctionTypeOrConstructorType = node.kind === 152 || node.kind === 153; - if (isFunctionTypeOrConstructorType || node.parent.kind === 155) { + var isFunctionTypeOrConstructorType = node.kind === 154 || node.kind === 155; + if (isFunctionTypeOrConstructorType || node.parent.kind === 157) { if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 144 && !(node.flags & 16)) { + else if (node.kind !== 146 && !(node.flags & 8)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -24700,49 +26912,49 @@ var ts; write(";"); writeLine(); } - function getReturnTypeVisibilityError(symbolAccesibilityResult) { + function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 148: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + case 150: + diagnosticMessage = symbolAccessibilityResult.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 147: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + case 149: + diagnosticMessage = symbolAccessibilityResult.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 149: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + case 151: + diagnosticMessage = symbolAccessibilityResult.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 143: - case 142: - if (node.flags & 64) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + case 145: + case 144: + if (node.flags & 32) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : 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 === 214) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + else if (node.parent.kind === 218) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 213: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + case 217: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; @@ -24766,68 +26978,68 @@ var ts; emitBindingPattern(node.name); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } if (resolver.isOptionalParameter(node)) { write("?"); } decreaseIndent(); - if (node.parent.kind === 152 || - node.parent.kind === 153 || - node.parent.parent.kind === 155) { + if (node.parent.kind === 154 || + node.parent.kind === 155 || + node.parent.parent.kind === 157) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 16)) { + else if (!(node.parent.flags & 8)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } - function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: node, typeName: node.name } : undefined; } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 144: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + case 146: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 148: - return symbolAccesibilityResult.errorModuleName ? + case 150: + return symbolAccessibilityResult.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 147: - return symbolAccesibilityResult.errorModuleName ? + case 149: + return symbolAccessibilityResult.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 143: - case 142: - if (node.parent.flags & 64) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + case 145: + case 144: + if (node.parent.flags & 32) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : 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 === 214) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + else if (node.parent.parent.kind === 218) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? 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 213: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 ? + case 217: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; @@ -24836,12 +27048,12 @@ var ts; } } function emitBindingPattern(bindingPattern) { - if (bindingPattern.kind === 161) { + if (bindingPattern.kind === 165) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 162) { + else if (bindingPattern.kind === 166) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -24852,20 +27064,12 @@ var ts; } } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.kind === 187) { + if (bindingElement.kind === 191) { write(" "); } - else if (bindingElement.kind === 163) { + else if (bindingElement.kind === 167) { if (bindingElement.propertyName) { - writeTextOfNode(currentSourceFile, bindingElement.propertyName); + writeTextOfNode(currentText, bindingElement.propertyName); write(": "); } if (bindingElement.name) { @@ -24877,7 +27081,7 @@ var ts; if (bindingElement.dotDotDotToken) { write("..."); } - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); } } } @@ -24885,59 +27089,75 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 213: - case 218: - case 221: - case 215: - case 214: - case 216: case 217: - return emitModuleElement(node, isModuleElementVisible(node)); - case 193: - return emitModuleElement(node, isVariableStatementVisible(node)); case 222: + case 225: + case 219: + case 218: + case 220: + case 221: + return emitModuleElement(node, isModuleElementVisible(node)); + case 197: + return emitModuleElement(node, isVariableStatementVisible(node)); + case 226: return emitModuleElement(node, !node.importClause); - case 228: + case 232: return emitExportDeclaration(node); + case 146: + case 145: case 144: + return writeFunctionDeclaration(node); + case 150: + case 149: + case 151: + return emitSignatureDeclarationWithJsDocComments(node); + case 147: + case 148: + return emitAccessorDeclaration(node); case 143: case 142: - return writeFunctionDeclaration(node); - case 148: - case 147: - case 149: - return emitSignatureDeclarationWithJsDocComments(node); - case 145: - case 146: - return emitAccessorDeclaration(node); - case 141: - case 140: return emitPropertyDeclaration(node); - case 247: + case 251: return emitEnumMemberDeclaration(node); - case 227: + case 231: return emitExportAssignment(node); - case 248: + case 252: return emitSourceFile(node); } } - function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 4096 - ? referencedFile.fileName - : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) - ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") - : ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); - referencePathsOutput += "/// " + newLine; + function writeReferencePath(referencedFile, addBundledFileReference) { + var declFileName; + var addedBundledEmitReference = false; + if (ts.isDeclarationFile(referencedFile)) { + declFileName = referencedFile.fileName; + } + else { + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + } + if (declFileName) { + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); + referencePathsOutput += "/// " + newLine; + } + return addedBundledEmitReference; + function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + if (isBundledEmit && !addBundledFileReference) { + return; + } + ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); + declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; + addedBundledEmitReference = isBundledEmit; + } } } - function writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); - if (!emitDeclarationResult.reportedDeclarationError) { + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; + if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } + return emitSkipped; function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { var appliedSyncOutputPos = 0; var declarationOutput = ""; @@ -24956,10 +27176,18 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); + function getResolvedExternalModuleName(host, file) { + return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || ts.isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; var entities = { "quot": 0x0022, "amp": 0x0026, @@ -25220,39 +27448,19 @@ var ts; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\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};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\n return new Promise(function (resolve, reject) {\n generator = generator.call(thisArg, _arguments);\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\n function onfulfill(value) { try { step(\"next\", value); } catch (e) { reject(e); } }\n function onreject(value) { try { step(\"throw\", value); } catch (e) { reject(e); } }\n function step(verb, value) {\n var result = generator[verb](value);\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\n }\n step(\"next\", void 0);\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || 0; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 ? 5 : 0; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - var diagnostics = []; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emitSkipped = false; var newLine = host.getNewLine(); - var jsxDesugaring = host.getCompilerOptions().jsx !== 1; - var shouldEmitJsx = function (s) { return (s.languageVariant === 1 && !jsxDesugaring); }; - if (targetSourceFile === undefined) { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - if (compilerOptions.outFile || compilerOptions.out) { - emitFile(compilerOptions.outFile || compilerOptions.out); - } - } - else { - if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) { - emitFile(compilerOptions.outFile || compilerOptions.out); - } - } - diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics); + var emitJavaScript = createFileEmitter(); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { - emitSkipped: false, - diagnostics: diagnostics, + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), sourceMaps: sourceMapDataList }; function isUniqueLocalName(name, container) { @@ -25296,86 +27504,136 @@ var ts; } } } - function emitJavaScript(jsFilePath, root) { + function createFileEmitter() { var writer = ts.createTextWriter(newLine); var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); + var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; var currentSourceFile; + var currentText; + var currentLineMap; + var currentFileIdentifiers; + var renamedDependencies; + var isEs6Module; + var isCurrentFileExternalModule; var exportFunctionForFile; - var generatedNameSet = {}; - var nodeToGeneratedName = []; + var contextObjectForFile; + var generatedNameSet; + var nodeToGeneratedName; var computedPropertyNamesToGeneratedNames; + var decoratedClassAliases; var convertedLoopState; - var extendsEmitted = false; - var decorateEmitted = false; - var paramEmitted = false; - var awaiterEmitted = false; + var extendsEmitted; + var decorateEmitted; + var paramEmitted; + var awaiterEmitted; var tempFlags = 0; var tempVariables; var tempParameters; var externalImports; var exportSpecifiers; var exportEquals; - var hasExportStars; - var writeEmittedFiles = writeJavaScriptFile; + var hasExportStarsToExportValues; var detachedCommentsInfo; - var writeComment = ts.writeCommentRange; - var emit = emitNodeWithCommentsAndWithoutSourcemap; - var emitStart = function (node) { }; - var emitEnd = function (node) { }; - var emitToken = emitTokenText; - var scopeEmitStart = function (scopeDeclaration, scopeName) { }; - var scopeEmitEnd = function () { }; var sourceMapData; + var isOwnFileEmit; var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; + var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; var moduleEmitDelegates = (_a = {}, - _a[5] = emitES6Module, - _a[2] = emitAMDModule, - _a[4] = emitSystemModule, - _a[3] = emitUMDModule, - _a[1] = emitCommonJSModule, + _a[ts.ModuleKind.ES6] = emitES6Module, + _a[ts.ModuleKind.AMD] = emitAMDModule, + _a[ts.ModuleKind.System] = emitSystemModule, + _a[ts.ModuleKind.UMD] = emitUMDModule, + _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, _a ); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - initializeEmitterWithSourceMaps(); + var bundleEmitDelegates = (_b = {}, + _b[ts.ModuleKind.ES6] = function () { }, + _b[ts.ModuleKind.AMD] = emitAMDModule, + _b[ts.ModuleKind.System] = emitSystemModule, + _b[ts.ModuleKind.UMD] = function () { }, + _b[ts.ModuleKind.CommonJS] = function () { }, + _b + ); + return doEmit; + function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + generatedNameSet = {}; + nodeToGeneratedName = []; + decoratedClassAliases = []; + isOwnFileEmit = !isBundledEmit; + if (isBundledEmit && modulekind) { + ts.forEach(sourceFiles, emitEmitHelpers); + } + ts.forEach(sourceFiles, emitSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# sourceMappingURL=" + sourceMappingURL); + } + writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM); + sourceMap.reset(); + writer.reset(); + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + exportFunctionForFile = undefined; + contextObjectForFile = undefined; + generatedNameSet = undefined; + nodeToGeneratedName = undefined; + decoratedClassAliases = undefined; + computedPropertyNamesToGeneratedNames = undefined; + convertedLoopState = undefined; + extendsEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + tempFlags = 0; + tempVariables = undefined; + tempParameters = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = undefined; + detachedCommentsInfo = undefined; + sourceMapData = undefined; + isEs6Module = false; + renamedDependencies = undefined; + isCurrentFileExternalModule = false; } - if (root) { - emitSourceFile(root); - } - else { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!isExternalModuleOrDeclarationFile(sourceFile)) { - emitSourceFile(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), compilerOptions.emitBOM); - return; function emitSourceFile(sourceFile) { currentSourceFile = sourceFile; + currentText = sourceFile.text; + currentLineMap = ts.getLineStarts(sourceFile); exportFunctionForFile = undefined; - emit(sourceFile); + contextObjectForFile = undefined; + isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"]; + renamedDependencies = sourceFile.renamedDependencies; + currentFileIdentifiers = sourceFile.identifiers; + isCurrentFileExternalModule = ts.isExternalModule(sourceFile); + setSourceFile(sourceFile); + emitNodeWithCommentsAndWithoutSourcemap(sourceFile); } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentSourceFile.identifiers, name) && + !ts.hasProperty(currentFileIdentifiers, name) && !ts.hasProperty(generatedNameSet, name); } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_20 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_20)) { + var name_21 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_21)) { tempFlags |= flags; - return name_20; + return name_21; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_21 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_21)) { - return name_21; + var name_22 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_22)) { + return name_22; } } } @@ -25413,17 +27671,17 @@ var ts; switch (node.kind) { case 69: return makeUniqueName(node.text); - case 218: - case 217: - return generateNameForModuleOrEnum(node); case 222: - case 228: + case 221: + return generateNameForModuleOrEnum(node); + case 226: + case 232: return generateNameForImportOrExportDeclaration(node); - case 213: - case 214: - case 227: + case 217: + case 218: + case 231: return generateNameForExportDefault(); - case 186: + case 190: return generateNameForClassExpression(); } } @@ -25431,289 +27689,14 @@ var ts; var id = ts.getNodeId(node); return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); } - function initializeEmitterWithSourceMaps() { - var sourceMapDir; - var sourceMapSourceIndex = -1; - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; + function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark) { + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), false); } - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - var encodedStr = ""; - do { - var currentDigit = inValue & 31; - inValue = inValue >> 5; - if (inValue > 0) { - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); } - function recordSourceMapSpan(pos) { - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine !== emittedLine || - lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || - (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - sourceMapData.inputSourceFileNames.push(node.fileName); - if (compilerOptions.inlineSources) { - if (!sourceMapData.sourceMapSourcesContent) { - sourceMapData.sourceMapSourcesContent = []; - } - sourceMapData.sourceMapSourcesContent.push(node.text); - } - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - var name_22 = node.name; - if (!name_22 || name_22.kind !== 136) { - scopeName = "." + scopeName; - } - scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - recordScopeNameStart(scopeName); - } - else if (node.kind === 213 || - node.kind === 173 || - node.kind === 143 || - node.kind === 142 || - node.kind === 145 || - node.kind === 146 || - node.kind === 218 || - node.kind === 214 || - node.kind === 217) { - if (node.name) { - var name_23 = node.name; - scopeName = name_23.kind === 136 - ? ts.getTextOfNode(name_23) - : node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - ts.writeCommentRange(currentSourceFile, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) { - if (typeof JSON !== "undefined") { - var map_2 = { - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }; - if (sourcesContent !== undefined) { - map_2.sourcesContent = sourcesContent; - } - return JSON.stringify(map_2); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\" " + (sourcesContent !== undefined ? ",\"sourcesContent\":[" + serializeStringArray(sourcesContent) + "]" : "") + "}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) { - encodeLastRecordedSourceMapSpan(); - var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent); - sourceMapDataList.push(sourceMapData); - var sourceMapUrl; - if (compilerOptions.inlineSourceMap) { - var base64SourceMapText = ts.convertToBase64(sourceMapText); - sourceMapUrl = "//# sourceMappingURL=data:application/json;base64," + base64SourceMapText; - } - else { - ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, false); - sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL; - } - writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark); - } - var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: undefined, - sourceMapDecodedMappings: [] - }; - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithSourceMap(node) { - if (node) { - if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node); - } - if (node.kind !== 248) { - recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node); - } - } - } - function emitNodeWithCommentsAndWithSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithCommentsAndWithSourcemap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, writeByteOrderMark) { - ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark); } function createTempVariable(flags) { var result = ts.createSynthesizedNode(69); @@ -25744,7 +27727,9 @@ var ts; write(";"); } } - function emitTokenText(tokenKind, startPos, emitFn) { + function emitToken(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentText, startPos); + emitPos(tokenStartPos); var tokenString = ts.tokenToString(tokenKind); if (emitFn) { emitFn(); @@ -25752,7 +27737,9 @@ var ts; else { write(tokenString); } - return startPos + tokenString.length; + var tokenEndPos = tokenStartPos + tokenString.length; + emitPos(tokenEndPos); + return tokenEndPos; } function emitOptional(prefix, node) { if (node) { @@ -25769,11 +27756,6 @@ var ts; write(")"); } } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { ts.Debug.assert(nodes.length > 0); increaseIndent(); @@ -25882,7 +27864,7 @@ var ts; return getQuotedEscapedLiteralText("\"", node.text, "\""); } if (node.parent) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + return ts.getTextOfNodeFromSourceText(currentText, node); } switch (node.kind) { case 9: @@ -25904,7 +27886,7 @@ var ts; return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote; } function emitDownlevelRawTemplateLiteral(node) { - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + var text = ts.getTextOfNodeFromSourceText(currentText, node); var isLast = node.kind === 11 || node.kind === 14; text = text.substring(1, text.length - (isLast ? 1 : 2)); text = text.replace(/\r\n?/g, "\n"); @@ -25939,10 +27921,10 @@ var ts; emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); write("("); emit(tempVariable); - if (node.template.kind === 183) { + if (node.template.kind === 187) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 181 + var needsParens = templateSpan.expression.kind === 185 && templateSpan.expression.operatorToken.kind === 24; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -25966,7 +27948,7 @@ var ts; } for (var i = 0, n = node.templateSpans.length; i < n; i++) { var templateSpan = node.templateSpans[i]; - var needsParens = templateSpan.expression.kind !== 172 + var needsParens = templateSpan.expression.kind !== 176 && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1; if (i > 0 || headEmitted) { write(" + "); @@ -25986,11 +27968,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 168: - case 169: - return parent.expression === template; - case 170: case 172: + case 173: + return parent.expression === template; + case 174: + case 176: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1; @@ -25998,7 +27980,7 @@ var ts; } function comparePrecedenceToBinaryPlus(expression) { switch (expression.kind) { - case 181: + case 185: switch (expression.operatorToken.kind) { case 37: case 39: @@ -26010,8 +27992,8 @@ var ts; default: return -1; } - case 184: - case 182: + case 188: + case 186: return -1; default: return 1; @@ -26034,13 +28016,13 @@ var ts; } } function emitAttributeName(name) { - if (/[A-Za-z_]+[\w*]/.test(name.text)) { - write("\""); + if (/^[A-Za-z_]\w*$/.test(name.text)) { emit(name); - write("\""); } else { + write("\""); emit(name); + write("\""); } } function emitJsxAttribute(node) { @@ -26055,7 +28037,7 @@ var ts; } function emitJsxElement(openingNode, children) { var syntheticReactRef = ts.createSynthesizedNode(69); - syntheticReactRef.text = "React"; + syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; syntheticReactRef.parent = openingNode; emitLeadingComments(openingNode); emitExpressionIdentifier(syntheticReactRef); @@ -26067,37 +28049,37 @@ var ts; } else { var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 239; })) { + if (ts.forEach(attrs, function (attr) { return attr.kind === 243; })) { emitExpressionIdentifier(syntheticReactRef); write(".__spread("); var haveOpenedObjectLiteral = false; - for (var i_1 = 0; i_1 < attrs.length; i_1++) { - if (attrs[i_1].kind === 239) { - if (i_1 === 0) { + for (var i = 0; i < attrs.length; i++) { + if (attrs[i].kind === 243) { + if (i === 0) { write("{}, "); } if (haveOpenedObjectLiteral) { write("}"); haveOpenedObjectLiteral = false; } - if (i_1 > 0) { + if (i > 0) { write(", "); } - emit(attrs[i_1].expression); + emit(attrs[i].expression); } else { - ts.Debug.assert(attrs[i_1].kind === 238); + ts.Debug.assert(attrs[i].kind === 242); if (haveOpenedObjectLiteral) { write(", "); } else { haveOpenedObjectLiteral = true; - if (i_1 > 0) { + if (i > 0) { write(", "); } write("{"); } - emitJsxAttribute(attrs[i_1]); + emitJsxAttribute(attrs[i]); } } if (haveOpenedObjectLiteral) @@ -26106,7 +28088,7 @@ var ts; } else { write("{"); - for (var i = 0; i < attrs.length; i++) { + for (var i = 0, n = attrs.length; i < n; i++) { if (i > 0) { write(", "); } @@ -26116,32 +28098,52 @@ var ts; } } if (children) { - for (var i = 0; i < children.length; i++) { - if (children[i].kind === 240 && !(children[i].expression)) { - continue; - } - if (children[i].kind === 236) { - var text = getTextToEmit(children[i]); - if (text !== undefined) { - write(", \""); - write(text); - write("\""); + var firstChild = void 0; + var multipleEmittableChildren = false; + for (var i = 0, n = children.length; i < n; i++) { + var jsxChild = children[i]; + if (isJsxChildEmittable(jsxChild)) { + if (!firstChild) { + write(", "); + firstChild = jsxChild; + } + else { + if (!multipleEmittableChildren) { + multipleEmittableChildren = true; + increaseIndent(); + writeLine(); + emit(firstChild); + } + write(", "); + writeLine(); + emit(jsxChild); } } + } + if (multipleEmittableChildren) { + decreaseIndent(); + } + else if (firstChild) { + if (firstChild.kind !== 237 && firstChild.kind !== 238) { + emit(firstChild); + } else { - write(", "); - emit(children[i]); + increaseIndent(); + writeLine(); + emit(firstChild); + writeLine(); + decreaseIndent(); } } } write(")"); emitTrailingComments(openingNode); } - if (node.kind === 233) { + if (node.kind === 237) { emitJsxElement(node.openingElement, node.children); } else { - ts.Debug.assert(node.kind === 234); + ts.Debug.assert(node.kind === 238); emitJsxElement(node); } } @@ -26163,11 +28165,11 @@ var ts; if (i > 0) { write(" "); } - if (attribs[i].kind === 239) { + if (attribs[i].kind === 243) { emitJsxSpreadAttribute(attribs[i]); } else { - ts.Debug.assert(attribs[i].kind === 238); + ts.Debug.assert(attribs[i].kind === 242); emitJsxAttribute(attribs[i]); } } @@ -26175,11 +28177,11 @@ var ts; function emitJsxOpeningOrSelfClosingElement(node) { write("<"); emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 234)) { + if (node.attributes.length > 0 || (node.kind === 238)) { write(" "); } emitAttributes(node.attributes); - if (node.kind === 234) { + if (node.kind === 238) { write("/>"); } else { @@ -26198,20 +28200,20 @@ var ts; } emitJsxClosingElement(node.closingElement); } - if (node.kind === 233) { + if (node.kind === 237) { emitJsxElement(node); } else { - ts.Debug.assert(node.kind === 234); + ts.Debug.assert(node.kind === 238); emitJsxOpeningOrSelfClosingElement(node); } } function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 163); + ts.Debug.assert(node.kind !== 167); if (node.kind === 9) { emitLiteral(node); } - else if (node.kind === 136) { + else if (node.kind === 138) { if (ts.nodeIsDecorated(node.parent)) { if (!computedPropertyNamesToGeneratedNames) { computedPropertyNamesToGeneratedNames = []; @@ -26234,7 +28236,7 @@ var ts; write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } write("\""); } @@ -26242,74 +28244,71 @@ var ts; function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 164: - case 189: - case 181: case 168: - case 241: - case 136: - case 182: - case 139: - case 175: - case 197: - case 167: - case 227: - case 195: - case 188: - case 199: - case 200: - case 201: - case 196: - case 234: - case 235: - case 239: - case 240: - case 169: - case 172: - case 180: - case 179: - case 204: - case 246: + case 193: case 185: - case 206: - case 170: - case 190: - case 208: - case 171: - case 176: - case 177: - case 198: - case 205: - case 184: - return true; - case 163: - case 247: - case 138: + case 172: case 245: + case 138: + case 186: case 141: - case 211: - return parent.initializer === node; - case 166: - return parent.expression === node; - case 174: + case 179: + case 201: + case 171: + case 231: + case 199: + case 192: + case 203: + case 204: + case 205: + case 200: + case 241: + case 238: + case 239: + case 243: + case 244: case 173: + case 176: + case 184: + case 183: + case 208: + case 250: + case 189: + case 210: + case 174: + case 194: + case 212: + case 175: + case 180: + case 181: + case 202: + case 209: + case 188: + return true; + case 167: + case 251: + case 140: + case 249: + case 143: + case 215: + return parent.initializer === node; + case 170: + return parent.expression === node; + case 178: + case 177: return parent.body === node; - case 221: + case 225: return parent.moduleReference === node; - case 135: + case 137: return parent.left === node; } return false; } function emitExpressionIdentifier(node) { - if (resolver.getNodeCheckFlags(node) & 2048) { - write("_arguments"); - return; - } var container = resolver.getReferencedExportContainer(node); if (container) { - if (container.kind === 248) { - if (modulekind !== 5 && modulekind !== 4) { + if (container.kind === 252) { + if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { write("exports."); } } @@ -26319,18 +28318,18 @@ var ts; } } else { - if (modulekind !== 5) { + if (modulekind !== ts.ModuleKind.ES6) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { - if (declaration.kind === 223) { + if (declaration.kind === 227) { write(getGeneratedNameForNode(declaration.parent)); write(languageVersion === 0 ? "[\"default\"]" : ".default"); return; } - else if (declaration.kind === 226) { + else if (declaration.kind === 230) { write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_24 = declaration.propertyName || declaration.name; - var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_24); + var name_23 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_23); if (languageVersion === 0 && identifier === "default") { write("[\"default\"]"); } @@ -26342,30 +28341,40 @@ var ts; } } } - if (languageVersion !== 2) { - var declaration = resolver.getReferencedNestedRedeclaration(node); + if (languageVersion < 2) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration) { write(getGeneratedNameForNode(declaration.name)); return; } } + else if (resolver.getNodeCheckFlags(node) & 1048576) { + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = decoratedClassAliases[ts.getNodeId(declaration)]; + if (classAlias !== undefined) { + write(classAlias); + return; + } + } + } } if (ts.nodeIsSynthesized(node)) { write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } } - function isNameOfNestedRedeclaration(node) { + function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node) { if (languageVersion < 2) { - var parent_6 = node.parent; - switch (parent_6.kind) { - case 163: - case 214: - case 217: - case 211: - return parent_6.name === node && resolver.isNestedRedeclaration(parent_6); + var parent_8 = node.parent; + switch (parent_8.kind) { + case 167: + case 218: + case 221: + case 215: + return parent_8.name === node && resolver.isDeclarationWithCollidingName(parent_8); } } return false; @@ -26373,8 +28382,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_25 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_25); + var name_24 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_24); return; } } @@ -26384,20 +28393,23 @@ var ts; else if (isExpressionIdentifier(node)) { emitExpressionIdentifier(node); } - else if (isNameOfNestedRedeclaration(node)) { + else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { write(getGeneratedNameForNode(node)); } else if (ts.nodeIsSynthesized(node)) { write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } } function emitThis(node) { if (resolver.getNodeCheckFlags(node) & 2) { write("_this"); } + else if (convertedLoopState) { + write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); + } else { write("this"); } @@ -26471,10 +28483,10 @@ var ts; } } function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 181 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { + if (node.parent.kind === 185 && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { return true; } - else if (node.parent.kind === 182 && node.parent.condition === node) { + else if (node.parent.kind === 186 && node.parent.condition === node) { return true; } return false; @@ -26482,11 +28494,11 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 69: - case 164: - case 166: - case 167: case 168: + case 170: + case 171: case 172: + case 176: return false; } return true; @@ -26503,17 +28515,17 @@ var ts; write(", "); } var e = elements[pos]; - if (e.kind === 185) { + if (e.kind === 189) { e = e.expression; emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 168) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 185) { + while (i < length && elements[i].kind !== 189) { i++; } write("["); @@ -26536,7 +28548,7 @@ var ts; } } function isSpreadElementExpression(node) { - return node.kind === 185; + return node.kind === 189; } function emitArrayLiteral(node) { var elements = node.elements; @@ -26549,7 +28561,7 @@ var ts; write("]"); } else { - emitListWithSpread(elements, true, (node.flags & 1024) !== 0, elements.hasTrailingComma, true); + emitListWithSpread(elements, true, node.multiLine, elements.hasTrailingComma, true); } } function emitObjectLiteralBody(node, numElements) { @@ -26564,7 +28576,7 @@ var ts; emitLinePreservingList(node, properties, languageVersion >= 1, true); } else { - var multiLine = (node.flags & 1024) !== 0; + var multiLine = node.multiLine; if (!multiLine) { write(" "); } @@ -26583,7 +28595,7 @@ var ts; write("}"); } function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = (node.flags & 1024) !== 0; + var multiLine = node.multiLine; var properties = node.properties; write("("); if (multiLine) { @@ -26597,7 +28609,7 @@ var ts; writeComma(); var property = properties[i]; emitStart(property); - if (property.kind === 145 || property.kind === 146) { + if (property.kind === 147 || property.kind === 148) { var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; @@ -26648,13 +28660,13 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 245) { + if (property.kind === 249) { emit(property.initializer); } - else if (property.kind === 246) { + else if (property.kind === 250) { emitExpressionIdentifier(property.name); } - else if (property.kind === 143) { + else if (property.kind === 145) { emitFunctionDeclaration(property); } else { @@ -26686,7 +28698,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 === 136) { + if (properties[i].name.kind === 138) { numInitialNonComputedProperties = i; break; } @@ -26700,35 +28712,35 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(181, startsOnNewLine); + var result = ts.createSynthesizedNode(185, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(166); + var result = ts.createSynthesizedNode(170); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(21); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(167); + var result = ts.createSynthesizedNode(171); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; } function parenthesizeForAccess(expr) { - while (expr.kind === 171 || expr.kind === 189) { + while (expr.kind === 175 || expr.kind === 193) { expr = expr.expression; } if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 169 && + expr.kind !== 173 && expr.kind !== 8) { return expr; } - var node = ts.createSynthesizedNode(172); + var node = ts.createSynthesizedNode(176); node.expression = expr; return node; } @@ -26755,11 +28767,11 @@ var ts; } function isNamespaceExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 248; + return container && container.kind !== 252; } function emitShorthandPropertyAssignment(node) { - writeTextOfNode(currentSourceFile, node.name); - if (languageVersion < 2 || isNamespaceExportReference(node.name)) { + writeTextOfNode(currentText, node.name); + if (modulekind !== ts.ModuleKind.ES6 || isNamespaceExportReference(node.name)) { write(": "); emit(node.name); } @@ -26773,7 +28785,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 166 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 170 ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -26784,7 +28796,7 @@ var ts; if (compilerOptions.isolatedModules) { return undefined; } - return node.kind === 166 || node.kind === 167 + return node.kind === 170 || node.kind === 171 ? resolver.getConstantValue(node) : undefined; } @@ -26807,12 +28819,20 @@ var ts; if (tryEmitConstantValue(node)) { return; } + if (languageVersion === 2 && + node.expression.kind === 95 && + isInAsyncMethodWithSuperInES6(node)) { + var name_25 = ts.createSynthesizedNode(9); + name_25.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_25); + return; + } emit(node.expression); var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); - var shouldEmitSpace; + var shouldEmitSpace = false; if (!indentedBeforeDot) { if (node.expression.kind === 8) { - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); + var text = ts.getTextOfNodeFromSourceText(currentText, node.expression); shouldEmitSpace = text.indexOf(ts.tokenToString(21)) < 0; } else { @@ -26864,25 +28884,34 @@ var ts; } emitExpressionIdentifier(node); break; - case 135: + case 137: emitQualifiedNameAsExpression(node, useFallback); break; + default: + emitNodeWithoutSourceMap(node); + break; } } function emitIndexedAccess(node) { if (tryEmitConstantValue(node)) { return; } + if (languageVersion === 2 && + node.expression.kind === 95 && + isInAsyncMethodWithSuperInES6(node)) { + emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression); + return; + } emit(node.expression); write("["); emit(node.argumentExpression); write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 185; }); + return ts.forEach(elements, function (e) { return e.kind === 189; }); } function skipParentheses(node) { - while (node.kind === 172 || node.kind === 171 || node.kind === 189) { + while (node.kind === 176 || node.kind === 175 || node.kind === 193) { node = node.expression; } return node; @@ -26903,12 +28932,12 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 166) { + if (expr.kind === 170) { target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 167) { + else if (expr.kind === 171) { target = emitCallTarget(expr.expression); write("["); emit(expr.argumentExpression); @@ -26937,23 +28966,42 @@ var ts; emitListWithSpread(node.arguments, false, false, false, true); write(")"); } + function isInAsyncMethodWithSuperInES6(node) { + if (languageVersion === 2) { + var container = ts.getSuperContainer(node, false); + if (container && resolver.getNodeCheckFlags(container) & (2048 | 4096)) { + return true; + } + } + return false; + } + function emitSuperAccessInAsyncMethod(superNode, argumentExpression) { + var container = ts.getSuperContainer(superNode, false); + var isSuperBinding = resolver.getNodeCheckFlags(container) & 4096; + write("_super("); + emit(argumentExpression); + write(isSuperBinding ? ").value" : ")"); + } function emitCallExpression(node) { if (languageVersion < 2 && hasSpreadElement(node.arguments)) { emitCallWithSpread(node); return; } + var expression = node.expression; var superCall = false; - if (node.expression.kind === 95) { - emitSuper(node.expression); + var isAsyncMethodWithSuper = false; + if (expression.kind === 95) { + emitSuper(expression); superCall = true; } else { - emit(node.expression); - superCall = node.expression.kind === 166 && node.expression.expression.kind === 95; + superCall = ts.isSuperPropertyOrElementAccess(expression); + isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node); + emit(expression); } - if (superCall && languageVersion < 2) { + if (superCall && (languageVersion < 2 || isAsyncMethodWithSuper)) { write(".call("); - emitThis(node.expression); + emitThis(expression); if (node.arguments.length) { write(", "); emitCommaList(node.arguments); @@ -27000,21 +29048,21 @@ var ts; } } function emitParenExpression(node) { - if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 174) { - if (node.expression.kind === 171 || node.expression.kind === 189) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 178) { + if (node.expression.kind === 175 || node.expression.kind === 193) { var operand = node.expression.expression; - while (operand.kind === 171 || operand.kind === 189) { + while (operand.kind === 175 || operand.kind === 193) { operand = operand.expression; } - if (operand.kind !== 179 && - operand.kind !== 177 && - operand.kind !== 176 && - operand.kind !== 175 && + if (operand.kind !== 183 && + operand.kind !== 181 && operand.kind !== 180 && - operand.kind !== 169 && - !(operand.kind === 168 && node.parent.kind === 169) && - !(operand.kind === 173 && node.parent.kind === 168) && - !(operand.kind === 8 && node.parent.kind === 166)) { + operand.kind !== 179 && + operand.kind !== 184 && + operand.kind !== 173 && + !(operand.kind === 172 && node.parent.kind === 173) && + !(operand.kind === 177 && node.parent.kind === 172) && + !(operand.kind === 8 && node.parent.kind === 170)) { emit(operand); return; } @@ -27043,21 +29091,22 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 || node.parent.kind === 163); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 215 || node.parent.kind === 167); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, true); } function emitPrefixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + var exportChanged = (node.operator === 41 || node.operator === 42) && + isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); if (exportChanged) { write(exportFunctionForFile + "(\""); emitNodeWithoutSourceMap(node.operand); write("\", "); } write(ts.tokenToString(node.operator)); - if (node.operand.kind === 179) { + if (node.operand.kind === 183) { var operand = node.operand; if (node.operator === 35 && (operand.operator === 35 || operand.operator === 41)) { write(" "); @@ -27098,12 +29147,12 @@ var ts; if (!node || !isCurrentFileSystemExternalModule()) { return false; } - var current = node; + var current = ts.getRootDeclaration(node).parent; while (current) { - if (current.kind === 248) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 2) !== 0); + if (current.kind === 252) { + return !isExported || ((ts.getCombinedNodeFlags(node) & 1) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 219) { + else if (ts.isDeclaration(current)) { return false; } else { @@ -27114,19 +29163,19 @@ var ts; function emitExponentiationOperator(node) { var leftHandSideExpression = node.left; if (node.operatorToken.kind === 60) { - var synthesizedLHS; + var synthesizedLHS = void 0; var shouldEmitParentheses = false; if (ts.isElementAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(167, false); + synthesizedLHS = ts.createSynthesizedNode(171, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; if (leftHandSideExpression.argumentExpression.kind !== 8 && leftHandSideExpression.argumentExpression.kind !== 9) { var tempArgumentExpression = createAndRecordTempVariable(268435456); synthesizedLHS.argumentExpression = tempArgumentExpression; - emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, true); + emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, true, leftHandSideExpression.expression); } else { synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; @@ -27136,7 +29185,7 @@ var ts; else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(166, false); + synthesizedLHS = ts.createSynthesizedNode(170, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; synthesizedLHS.dotToken = leftHandSideExpression.dotToken; @@ -27164,8 +29213,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 && node.operatorToken.kind === 56 && - (node.left.kind === 165 || node.left.kind === 164)) { - emitDestructuring(node, node.parent.kind === 195); + (node.left.kind === 169 || node.left.kind === 168)) { + emitDestructuring(node, node.parent.kind === 199); } else { var exportChanged = node.operatorToken.kind >= 56 && @@ -27217,7 +29266,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 192) { + if (node && node.kind === 196) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -27231,22 +29280,20 @@ var ts; } emitToken(15, node.pos); increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 219) { - ts.Debug.assert(node.parent.kind === 218); + if (node.kind === 223) { + ts.Debug.assert(node.parent.kind === 222); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 219) { + if (node.kind === 223) { emitTempDeclarations(true); } decreaseIndent(); writeLine(); emitToken(16, node.statements.end); - scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 192) { + if (node.kind === 196) { write(" "); emit(node); } @@ -27258,7 +29305,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 174); + emitParenthesizedIf(node.expression, node.expression.kind === 178); write(";"); } function emitIfStatement(node) { @@ -27271,7 +29318,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(80, node.thenStatement.end); - if (node.elseStatement.kind === 196) { + if (node.elseStatement.kind === 200) { write(" "); emit(node.elseStatement); } @@ -27291,7 +29338,7 @@ var ts; else { emitNormalLoopBody(node, true); } - if (node.statement.kind === 192) { + if (node.statement.kind === 196) { write(" "); } else { @@ -27315,42 +29362,31 @@ var ts; emitNormalLoopBody(node, true); } } - function tryEmitStartOfVariableDeclarationList(decl, startPos) { + function tryEmitStartOfVariableDeclarationList(decl) { if (shouldHoistVariable(decl, true)) { return false; } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576) === 0) { + if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 3072) === 0) { for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { var varDecl = _b[_a]; hoistVariableDeclarationFromLoop(convertedLoopState, varDecl); } return false; } - var tokenKind = 102; + emitStart(decl); if (decl && languageVersion >= 2) { if (ts.isLet(decl)) { - tokenKind = 108; + write("let "); } else if (ts.isConst(decl)) { - tokenKind = 74; + write("const "); + } + else { + write("var "); } - } - if (startPos !== undefined) { - emitToken(tokenKind, startPos); - write(" "); } else { - switch (tokenKind) { - case 102: - write("var "); - break; - case 108: - write("let "); - break; - case 74: - write("const "); - break; - } + write("var "); } return true; } @@ -27382,7 +29418,7 @@ var ts; } else { var loop = convertLoopBody(node); - if (node.parent.kind === 207) { + if (node.parent.kind === 211) { emitLabelAndColon(node.parent); } loopEmitter(node, loop); @@ -27392,49 +29428,67 @@ var ts; var functionName = makeUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 199: - case 200: - case 201: - if (node.initializer.kind === 212) { + case 203: + case 204: + case 205: + var initializer = node.initializer; + if (initializer && initializer.kind === 216) { loopInitializer = node.initializer; } break; } var loopParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 24576)) { + var loopOutParameters; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3072)) { loopParameters = []; for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { var varDeclaration = _b[_a]; - collectNames(varDeclaration.name); + processVariableDeclaration(varDeclaration.name); } } - var bodyIsBlock = node.statement.kind === 192; + var bodyIsBlock = node.statement.kind === 196; var paramList = loopParameters ? loopParameters.join(", ") : ""; writeLine(); write("var " + functionName + " = function(" + paramList + ")"); - if (!bodyIsBlock) { - write(" {"); - writeLine(); - increaseIndent(); - } var convertedOuterLoopState = convertedLoopState; - convertedLoopState = {}; + convertedLoopState = { loopOutParameters: loopOutParameters }; if (convertedOuterLoopState) { if (convertedOuterLoopState.argumentsName) { convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; } + if (convertedOuterLoopState.thisName) { + convertedLoopState.thisName = convertedOuterLoopState.thisName; + } if (convertedOuterLoopState.hoistedLocalVariables) { convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; } } - emitEmbeddedStatement(node.statement); - if (!bodyIsBlock) { - decreaseIndent(); - writeLine(); - write("}"); - } - write(";"); + write(" {"); writeLine(); + increaseIndent(); + if (bodyIsBlock) { + emitLines(node.statement.statements); + } + else { + emit(node.statement); + } + writeLine(); + copyLoopOutParameters(convertedLoopState, 1, true); + decreaseIndent(); + writeLine(); + write("};"); + writeLine(); + if (loopOutParameters) { + write("var "); + for (var i = 0; i < loopOutParameters.length; i++) { + if (i !== 0) { + write(", "); + } + write(loopOutParameters[i].outParamName); + } + write(";"); + writeLine(); + } if (convertedLoopState.argumentsName) { if (convertedOuterLoopState) { convertedOuterLoopState.argumentsName = convertedLoopState.argumentsName; @@ -27444,13 +29498,22 @@ var ts; writeLine(); } } + if (convertedLoopState.thisName) { + if (convertedOuterLoopState) { + convertedOuterLoopState.thisName = convertedLoopState.thisName; + } + else { + write("var " + convertedLoopState.thisName + " = this;"); + writeLine(); + } + } if (convertedLoopState.hoistedLocalVariables) { if (convertedOuterLoopState) { convertedOuterLoopState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } else { write("var "); - var seen; + var seen = void 0; for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { var id = _d[_c]; if (!seen) { @@ -27471,15 +29534,21 @@ var ts; var currentLoopState = convertedLoopState; convertedLoopState = convertedOuterLoopState; return { functionName: functionName, paramList: paramList, state: currentLoopState }; - function collectNames(name) { + function processVariableDeclaration(name) { if (name.kind === 69) { - var nameText = isNameOfNestedRedeclaration(name) ? getGeneratedNameForNode(name) : name.text; + var nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(name) + ? getGeneratedNameForNode(name) + : name.text; loopParameters.push(nameText); + if (resolver.getNodeCheckFlags(name.parent) & 2097152) { + var reassignedVariable = { originalName: name, outParamName: makeUniqueName("out_" + nameText) }; + (loopOutParameters || (loopOutParameters = [])).push(reassignedVariable); + } } else { for (var _a = 0, _b = name.elements; _a < _b.length; _a++) { var element = _b[_a]; - collectNames(element.name); + processVariableDeclaration(element.name); } } } @@ -27493,7 +29562,7 @@ var ts; if (emitAsEmbeddedStatement) { emitEmbeddedStatement(node.statement); } - else if (node.statement.kind === 192) { + else if (node.statement.kind === 196) { emitLines(node.statement.statements); } else { @@ -27504,6 +29573,28 @@ var ts; convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; } } + function copyLoopOutParameters(state, copyDirection, emitAsStatements) { + if (state.loopOutParameters) { + for (var _a = 0, _b = state.loopOutParameters; _a < _b.length; _a++) { + var outParam = _b[_a]; + if (copyDirection === 0) { + emitIdentifier(outParam.originalName); + write(" = " + outParam.outParamName); + } + else { + write(outParam.outParamName + " = "); + emitIdentifier(outParam.originalName); + } + if (emitAsStatements) { + write(";"); + writeLine(); + } + else { + write(", "); + } + } + } + } function emitConvertedLoopCall(loop, emitAsBlock) { if (emitAsBlock) { write(" {"); @@ -27518,6 +29609,8 @@ var ts; write("var " + loopResult + " = "); } write(loop.functionName + "(" + loop.paramList + ");"); + writeLine(); + copyLoopOutParameters(loop.state, 0, true); if (!isSimpleLoop) { writeLine(); if (loop.state.nonLocalJumps & 8) { @@ -27527,7 +29620,7 @@ var ts; convertedLoopState.nonLocalJumps |= 8; } else { - write("return " + loopResult + ".value"); + write("return " + loopResult + ".value;"); } writeLine(); } @@ -27589,9 +29682,9 @@ var ts; var endPos = emitToken(86, node.pos); write(" "); endPos = emitToken(17, endPos); - if (node.initializer && node.initializer.kind === 212) { + if (node.initializer && node.initializer.kind === 216) { var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList); if (startIsEmitted) { emitCommaList(variableDeclarationList.declarations); } @@ -27615,7 +29708,7 @@ var ts; } } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 && node.kind === 201) { + if (languageVersion < 2 && node.kind === 205) { emitLoop(node, emitDownLevelForOfStatementWorker); } else { @@ -27626,17 +29719,17 @@ var ts; var endPos = emitToken(86, node.pos); write(" "); endPos = emitToken(17, endPos); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 216) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + tryEmitStartOfVariableDeclarationList(variableDeclarationList); emit(variableDeclarationList.declarations[0]); } } else { emit(node.initializer); } - if (node.kind === 200) { + if (node.kind === 204) { write(" in "); } else { @@ -27651,9 +29744,6 @@ var ts; emitNormalLoopBody(node, true); } } - function emitDownLevelForOfStatement(node) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } function emitDownLevelForOfStatementWorker(node, loop) { var endPos = emitToken(86, node.pos); write(" "); @@ -27675,24 +29765,24 @@ var ts; emitNodeWithoutSourceMap(node.expression); emitEnd(node.expression); write("; "); - emitStart(node.initializer); + emitStart(node.expression); emitNodeWithoutSourceMap(counter); write(" < "); emitNodeWithCommentsAndWithoutSourcemap(rhsReference); write(".length"); - emitEnd(node.initializer); + emitEnd(node.expression); write("; "); - emitStart(node.initializer); + emitStart(node.expression); emitNodeWithoutSourceMap(counter); write("++"); - emitEnd(node.initializer); + emitEnd(node.expression); emitToken(18, node.expression.end); write(" {"); writeLine(); increaseIndent(); var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 212) { + if (node.initializer.kind === 216) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -27714,7 +29804,7 @@ var ts; } else { var assignmentExpression = createBinaryExpression(node.initializer, 56, rhsIterationValue, false); - if (node.initializer.kind === 164 || node.initializer.kind === 165) { + if (node.initializer.kind === 168 || node.initializer.kind === 169) { emitDestructuring(assignmentExpression, true, undefined); } else { @@ -27736,23 +29826,25 @@ var ts; } function emitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 203 ? 2 : 4; + var jump = node.kind === 207 ? 2 : 4; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { + write("return "); + copyLoopOutParameters(convertedLoopState, 1, false); if (!node.label) { - if (node.kind === 203) { + if (node.kind === 207) { convertedLoopState.nonLocalJumps |= 2; - write("return \"break\";"); + write("\"break\";"); } else { convertedLoopState.nonLocalJumps |= 4; - write("return \"continue\";"); + write("\"continue\";"); } } else { - var labelMarker; - if (node.kind === 203) { + var labelMarker = void 0; + if (node.kind === 207) { labelMarker = "break-" + node.label.text; setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); } @@ -27760,12 +29852,12 @@ var ts; labelMarker = "continue-" + node.label.text; setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); } - write("return \"" + labelMarker + "\";"); + write("\"" + labelMarker + "\";"); } return; } } - emitToken(node.kind === 203 ? 70 : 75, node.pos); + emitToken(node.kind === 207 ? 70 : 75, node.pos); emitOptional(" ", node.label); write(";"); } @@ -27818,19 +29910,19 @@ var ts; emitToken(16, node.clauses.end); } function nodeStartPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, node2.end); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end); } function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 241) { + if (node.kind === 245) { write("case "); emit(node.expression); write(":"); @@ -27899,7 +29991,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 218); + } while (node && node.kind !== 222); return node; } function emitContainingModuleName(node) { @@ -27908,13 +30000,13 @@ var ts; } function emitModuleMemberName(node) { emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 2) { + if (ts.getCombinedNodeFlags(node) & 1) { var container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); write("."); } - else if (modulekind !== 5 && modulekind !== 4) { + else if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { write("exports."); } } @@ -27924,20 +30016,20 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(8); zero.text = "0"; - var result = ts.createSynthesizedNode(177); + var result = ts.createSynthesizedNode(181); result.expression = zero; return result; } function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 248) { - ts.Debug.assert(!!(node.flags & 512) || node.kind === 227); - if (modulekind === 1 || modulekind === 2 || modulekind === 3) { - if (!currentSourceFile.symbol.exports["___esModule"]) { - if (languageVersion === 1) { + if (node.parent.kind === 252) { + ts.Debug.assert(!!(node.flags & 512) || node.kind === 231); + if (modulekind === ts.ModuleKind.CommonJS || modulekind === ts.ModuleKind.AMD || modulekind === ts.ModuleKind.UMD) { + if (!isEs6Module) { + if (languageVersion !== 0) { write("Object.defineProperty(exports, \"__esModule\", { value: true });"); writeLine(); } - else if (languageVersion === 0) { + else { write("exports.__esModule = true;"); writeLine(); } @@ -27946,10 +30038,10 @@ var ts; } } function emitExportMemberAssignment(node) { - if (node.flags & 2) { + if (node.flags & 1) { writeLine(); emitStart(node); - if (modulekind === 4 && node.parent === currentSourceFile) { + if (modulekind === ts.ModuleKind.System && node.parent === currentSourceFile) { write(exportFunctionForFile + "(\""); if (node.flags & 512) { write("default"); @@ -27982,7 +30074,7 @@ var ts; } } function emitExportMemberAssignments(name) { - if (modulekind === 4) { + if (modulekind === ts.ModuleKind.System) { return; } if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { @@ -28001,7 +30093,7 @@ var ts; } } function emitExportSpecifierInSystemModule(specifier) { - ts.Debug.assert(modulekind === 4); + ts.Debug.assert(modulekind === ts.ModuleKind.System); if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) { return; } @@ -28015,7 +30107,7 @@ var ts; emitEnd(specifier.name); write(";"); } - function emitAssignment(name, value, shouldEmitCommaBeforeAssignment) { + function emitAssignment(name, value, shouldEmitCommaBeforeAssignment, nodeForSourceMap) { if (shouldEmitCommaBeforeAssignment) { write(", "); } @@ -28025,63 +30117,75 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(name); write("\", "); } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 || name.parent.kind === 163); - if (isVariableDeclarationOrBindingElement) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 215 || name.parent.kind === 167); + emitStart(isFirstVariableDeclaration(nodeForSourceMap) ? nodeForSourceMap.parent : nodeForSourceMap); + withTemporaryNoSourceMap(function () { + if (isVariableDeclarationOrBindingElement) { + emitModuleMemberName(name.parent); + } + else { + emit(name); + } + write(" = "); + emit(value); + }); + emitEnd(nodeForSourceMap, true); if (exportChanged) { write(")"); } } - function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment) { + function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment, sourceMapNode) { var identifier = createTempVariable(0); if (!canDefineTempVariablesInPlace) { recordTempDeclaration(identifier); } - emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment); + emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment, sourceMapNode || expression.parent); return identifier; } + function isFirstVariableDeclaration(root) { + return root.kind === 215 && + root.parent.kind === 216 && + root.parent.declarations[0] === root; + } function emitDestructuring(root, isAssignmentExpressionStatement, value) { var emitCount = 0; var canDefineTempVariablesInPlace = false; - if (root.kind === 211) { - var isExported = ts.getCombinedNodeFlags(root) & 2; + if (root.kind === 215) { + var isExported = ts.getCombinedNodeFlags(root) & 1; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } - else if (root.kind === 138) { + else if (root.kind === 140) { canDefineTempVariablesInPlace = true; } - if (root.kind === 181) { + if (root.kind === 185) { emitAssignmentExpression(root); } else { ts.Debug.assert(!isAssignmentExpressionStatement); + if (isFirstVariableDeclaration(root)) { + sourceMap.changeEmitSourcePos(); + } emitBindingElement(root, value); } - function ensureIdentifier(expr, reuseIdentifierExpressions) { + function ensureIdentifier(expr, reuseIdentifierExpressions, sourceMapNode) { if (expr.kind === 69 && reuseIdentifierExpressions) { return expr; } - var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0); + var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0, sourceMapNode); emitCount++; return identifier; } - function createDefaultValueCheck(value, defaultValue) { - value = ensureIdentifier(value, true); - var equals = ts.createSynthesizedNode(181); + function createDefaultValueCheck(value, defaultValue, sourceMapNode) { + value = ensureIdentifier(value, true, sourceMapNode); + var equals = ts.createSynthesizedNode(185); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(32); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(182); + var cond = ts.createSynthesizedNode(186); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(53); cond.whenTrue = whenTrue; @@ -28095,15 +30199,21 @@ var ts; return node; } function createPropertyAccessForDestructuringProperty(object, propName) { - var syntheticName = ts.createSynthesizedNode(propName.kind); - syntheticName.text = propName.text; - if (syntheticName.kind !== 69) { - return createElementAccessExpression(object, syntheticName); + var index; + var nameIsComputed = propName.kind === 138; + if (nameIsComputed) { + index = ensureIdentifier(propName.expression, false, propName); } - return createPropertyAccessExpression(object, syntheticName); + else { + index = ts.createSynthesizedNode(propName.kind); + index.text = ts.unescapeIdentifier(propName.text); + } + return !nameIsComputed && index.kind === 69 + ? createPropertyAccessExpression(object, index) + : createElementAccessExpression(object, index); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(168); + var call = ts.createSynthesizedNode(172); var sliceIdentifier = ts.createSynthesizedNode(69); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -28111,56 +30221,56 @@ var ts; call.arguments[0] = createNumericLiteral(sliceIndex); return call; } - function emitObjectLiteralAssignment(target, value) { + function emitObjectLiteralAssignment(target, value, sourceMapNode) { var properties = target.properties; if (properties.length !== 1) { - value = ensureIdentifier(value, true); + value = ensureIdentifier(value, true, sourceMapNode); } for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { var p = properties_5[_a]; - if (p.kind === 245 || p.kind === 246) { + if (p.kind === 249 || p.kind === 250) { var propName = p.name; - var target_1 = p.kind === 246 ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName)); + var target_1 = p.kind === 250 ? p : p.initializer || propName; + emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName), p); } } } - function emitArrayLiteralAssignment(target, value) { + function emitArrayLiteralAssignment(target, value, sourceMapNode) { var elements = target.elements; if (elements.length !== 1) { - value = ensureIdentifier(value, true); + value = ensureIdentifier(value, true, sourceMapNode); } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187) { - if (e.kind !== 185) { - emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); + if (e.kind !== 191) { + if (e.kind !== 189) { + emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e); } else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i)); + emitDestructuringAssignment(e.expression, createSliceCall(value, i), e); } } } } - function emitDestructuringAssignment(target, value) { - if (target.kind === 246) { + function emitDestructuringAssignment(target, value, sourceMapNode) { + if (target.kind === 250) { if (target.objectAssignmentInitializer) { - value = createDefaultValueCheck(value, target.objectAssignmentInitializer); + value = createDefaultValueCheck(value, target.objectAssignmentInitializer, sourceMapNode); } target = target.name; } - else if (target.kind === 181 && target.operatorToken.kind === 56) { - value = createDefaultValueCheck(value, target.right); + else if (target.kind === 185 && target.operatorToken.kind === 56) { + value = createDefaultValueCheck(value, target.right, sourceMapNode); target = target.left; } - if (target.kind === 165) { - emitObjectLiteralAssignment(target, value); + if (target.kind === 169) { + emitObjectLiteralAssignment(target, value, sourceMapNode); } - else if (target.kind === 164) { - emitArrayLiteralAssignment(target, value); + else if (target.kind === 168) { + emitArrayLiteralAssignment(target, value, sourceMapNode); } else { - emitAssignment(target, value, emitCount > 0); + emitAssignment(target, value, emitCount > 0, sourceMapNode); emitCount++; } } @@ -28171,24 +30281,24 @@ var ts; emit(value); } else if (isAssignmentExpressionStatement) { - emitDestructuringAssignment(target, value); + emitDestructuringAssignment(target, value, ts.nodeIsSynthesized(root) ? target : root); } else { - if (root.parent.kind !== 172) { + if (root.parent.kind !== 176) { write("("); } - value = ensureIdentifier(value, true); - emitDestructuringAssignment(target, value); + value = ensureIdentifier(value, true, root); + emitDestructuringAssignment(target, value, root); write(", "); emit(value); - if (root.parent.kind !== 172) { + if (root.parent.kind !== 176) { write(")"); } } } function emitBindingElement(target, value) { if (target.initializer) { - value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; + value = value ? createDefaultValueCheck(value, target.initializer, target) : target.initializer; } else if (!value) { value = createVoidZero(); @@ -28198,15 +30308,15 @@ var ts; var elements = pattern.elements; var numElements = elements.length; if (numElements !== 1) { - value = ensureIdentifier(value, numElements !== 0); + value = ensureIdentifier(value, numElements !== 0, target); } for (var i = 0; i < numElements; i++) { var element = elements[i]; - if (pattern.kind === 161) { + if (pattern.kind === 165) { var propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } - else if (element.kind !== 187) { + else if (element.kind !== 191) { if (!element.dotDotDotToken) { emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); } @@ -28217,7 +30327,7 @@ var ts; } } else { - emitAssignment(target.name, value, emitCount > 0); + emitAssignment(target.name, value, emitCount > 0, target); emitCount++; } } @@ -28234,12 +30344,23 @@ var ts; } else { var initializer = node.initializer; - if (!initializer && languageVersion < 2) { - var isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & 16384) && - (getCombinedFlagsForIdentifier(node.name) & 8192); - if (isLetDefinedInLoop && - node.parent.parent.kind !== 200 && - node.parent.parent.kind !== 201) { + if (!initializer && + languageVersion < 2 && + node.name.kind === 69) { + var container = ts.getEnclosingBlockScopeContainer(node); + var flags = resolver.getNodeCheckFlags(node); + var isCapturedInFunction = flags & 131072; + var isDeclaredInLoop = flags & 262144; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(container) || + (isCapturedInFunction && isDeclaredInLoop && container.kind === 196 && ts.isIterationStatement(container.parent, false)); + var emittedAsNestedLetDeclaration = ts.getCombinedNodeFlags(node) & 1024 && + !emittedAsTopLevel; + var emitExplicitInitializer = emittedAsNestedLetDeclaration && + container.kind !== 204 && + container.kind !== 205 && + (!resolver.isDeclarationWithCollidingName(node) || + (isDeclaredInLoop && !isCapturedInFunction && !ts.isIterationStatement(container, false))); + if (emitExplicitInitializer) { initializer = createVoidZero(); } } @@ -28257,7 +30378,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 187) { + if (node.kind === 191) { return; } var name = node.name; @@ -28268,20 +30389,14 @@ var ts; ts.forEach(name.elements, emitExportVariableAssignments); } } - function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 211 && node.parent.kind !== 163)) { - return 0; - } - return ts.getCombinedNodeFlags(node.parent); - } function isES6ExportedDeclaration(node) { - return !!(node.flags & 2) && - modulekind === 5 && - node.parent.kind === 248; + return !!(node.flags & 1) && + modulekind === ts.ModuleKind.ES6 && + node.parent.kind === 252; } function emitVariableStatement(node) { var startIsEmitted = false; - if (node.flags & 2) { + if (node.flags & 1) { if (isES6ExportedDeclaration(node)) { write("export "); startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); @@ -28300,12 +30415,12 @@ var ts; write(";"); } } - if (modulekind !== 5 && node.parent === currentSourceFile) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); } } function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { - if (!(node.flags & 2)) { + if (!(node.flags & 1)) { return true; } if (isES6ExportedDeclaration(node)) { @@ -28343,7 +30458,7 @@ var ts; } function emitDefaultValueAssignments(node) { if (languageVersion < 2) { - var tempIndex = 0; + var tempIndex_1 = 0; ts.forEach(node.parameters, function (parameter) { if (parameter.dotDotDotToken) { return; @@ -28355,15 +30470,15 @@ var ts; writeLine(); write("var "); if (hasBindingElements) { - emitDestructuring(parameter, false, tempParameters[tempIndex]); + emitDestructuring(parameter, false, tempParameters[tempIndex_1]); } else { - emit(tempParameters[tempIndex]); + emit(tempParameters[tempIndex_1]); write(" = "); emit(initializer); } write(";"); - tempIndex++; + tempIndex_1++; } } else if (initializer) { @@ -28426,12 +30541,12 @@ var ts; } } function emitAccessor(node) { - write(node.kind === 145 ? "get " : "set "); + write(node.kind === 147 ? "get " : "set "); emit(node.name); emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 174 && languageVersion >= 2; + return node.kind === 178 && languageVersion >= 2; } function emitDeclarationName(node) { if (node.name) { @@ -28442,20 +30557,24 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 173) { + if (node.kind === 177) { return !!node.name; } - if (node.kind === 213) { - return !!node.name || languageVersion < 2; + if (node.kind === 217) { + return !!node.name || modulekind !== ts.ModuleKind.ES6; } } function emitFunctionDeclaration(node) { if (ts.nodeIsMissing(node.body)) { return emitCommentsOnNotEmittedNode(node); } - if (node.kind !== 143 && node.kind !== 142 && - node.parent && node.parent.kind !== 245 && - node.parent.kind !== 168) { + var kind = node.kind, parent = node.parent; + if (kind !== 145 && + kind !== 144 && + parent && + parent.kind !== 249 && + parent.kind !== 172 && + parent.kind !== 168) { emitLeadingComments(node); } emitStart(node); @@ -28476,11 +30595,11 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (modulekind !== 5 && node.kind === 213 && node.parent === currentSourceFile && node.name) { + if (modulekind !== ts.ModuleKind.ES6 && kind === 217 && parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } emitEnd(node); - if (node.kind !== 143 && node.kind !== 142) { + if (kind !== 145 && kind !== 144) { emitTrailingComments(node); } } @@ -28512,35 +30631,36 @@ var ts; } function emitAsyncFunctionBodyForES6(node) { var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 174; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096) !== 0; - var args; + var isArrowFunction = node.kind === 178; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; if (!isArrowFunction) { write(" {"); increaseIndent(); writeLine(); + if (resolver.getNodeCheckFlags(node) & 4096) { + writeLines("\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"); + writeLine(); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + write("const _super = name => super[name];"); + writeLine(); + } write("return"); } write(" __awaiter(this"); if (hasLexicalArguments) { - write(", arguments"); + write(", arguments, "); } else { - write(", void 0"); + write(", void 0, "); } - if (promiseConstructor) { - write(", "); - emitNodeWithoutSourceMap(promiseConstructor); + if (languageVersion >= 2 || !promiseConstructor) { + write("void 0"); } else { - write(", Promise"); - } - if (hasLexicalArguments) { - write(", function* (_arguments)"); - } - else { - write(", function* ()"); + emitEntityNameAsExpression(promiseConstructor, false); } + write(", function* ()"); emitFunctionBody(node); write(")"); if (!isArrowFunction) { @@ -28555,7 +30675,7 @@ var ts; write(" { }"); } else { - if (node.body.kind === 192) { + if (node.body.kind === 196) { emitBlockFunctionBody(node, node.body); } else { @@ -28580,7 +30700,7 @@ var ts; emitSignatureParameters(node); } var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync && languageVersion === 2) { + if (isAsync) { emitAsyncFunctionBodyForES6(node); } else { @@ -28607,14 +30727,13 @@ var ts; } write(" "); var current = body; - while (current.kind === 171) { + while (current.kind === 175) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 165); + emitParenthesizedIf(body, current.kind === 169); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); emitDetachedCommentsAndUpdateCommentsInfo(node.body); @@ -28635,8 +30754,10 @@ var ts; increaseIndent(); writeLine(); emitLeadingComments(node.body); + emitStart(body); write("return "); emit(body); + emitEnd(body); write(";"); emitTrailingComments(node.body); emitTempDeclarations(true); @@ -28646,11 +30767,9 @@ var ts; emitStart(node.body); write("}"); emitEnd(node.body); - scopeEmitEnd(); } function emitBlockFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); emitDetachedCommentsAndUpdateCommentsInfo(body.statements); @@ -28677,25 +30796,23 @@ var ts; decreaseIndent(); } emitToken(16, body.statements.end); - scopeEmitEnd(); } - function findInitialSuperCall(ctor) { - if (ctor.body) { - var statement = ctor.body.statements[0]; - if (statement && statement.kind === 195) { - var expr = statement.expression; - if (expr && expr.kind === 168) { - var func = expr.expression; - if (func && func.kind === 95) { - return statement; - } - } - } + function getSuperCallAtGivenIndex(ctor, index) { + if (!ctor.body) { + return undefined; + } + var statements = ctor.body.statements; + if (!statements || index >= statements.length) { + return undefined; + } + var statement = statements[index]; + if (statement.kind === 199) { + return ts.isSuperCallExpression(statement.expression) ? statement : undefined; } } function emitParameterPropertyAssignments(node) { ts.forEach(node.parameters, function (param) { - if (param.flags & 56) { + if (param.flags & 28) { writeLine(); emitStart(param); emitStart(param.name); @@ -28715,7 +30832,7 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(memberName); write("]"); } - else if (memberName.kind === 136) { + else if (memberName.kind === 138) { emitComputedPropertyName(memberName); } else { @@ -28727,7 +30844,7 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 141 && isStatic === ((member.flags & 64) !== 0) && member.initializer) { + if (member.kind === 143 && isStatic === ((member.flags & 32) !== 0) && member.initializer) { properties.push(member); } } @@ -28748,7 +30865,7 @@ var ts; emit(receiver); } else { - if (property.flags & 64) { + if (property.flags & 32) { emitDeclarationName(node); } else { @@ -28767,11 +30884,11 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 191) { + if (member.kind === 195) { writeLine(); write(";"); } - else if (member.kind === 143 || node.kind === 142) { + else if (member.kind === 145 || node.kind === 144) { if (!member.body) { return emitCommentsOnNotEmittedNode(member); } @@ -28788,7 +30905,7 @@ var ts; write(";"); emitTrailingComments(member); } - else if (member.kind === 145 || member.kind === 146) { + else if (member.kind === 147 || member.kind === 148) { var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); @@ -28838,22 +30955,22 @@ var ts; function emitMemberFunctionsForES6AndHigher(node) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.kind === 143 || node.kind === 142) && !member.body) { + if ((member.kind === 145 || node.kind === 144) && !member.body) { emitCommentsOnNotEmittedNode(member); } - else if (member.kind === 143 || - member.kind === 145 || - member.kind === 146) { + else if (member.kind === 145 || + member.kind === 147 || + member.kind === 148) { writeLine(); emitLeadingComments(member); emitStart(member); - if (member.flags & 64) { + if (member.flags & 32) { write("static "); } - if (member.kind === 145) { + if (member.kind === 147) { write("get "); } - else if (member.kind === 146) { + else if (member.kind === 148) { write("set "); } if (member.asteriskToken) { @@ -28864,7 +30981,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 191) { + else if (member.kind === 195) { writeLine(); write(";"); } @@ -28889,10 +31006,10 @@ var ts; function emitConstructorWorker(node, baseTypeElement) { var hasInstancePropertyWithInitializer = false; ts.forEach(node.members, function (member) { - if (member.kind === 144 && !member.body) { + if (member.kind === 146 && !member.body) { emitCommentsOnNotEmittedNode(member); } - if (member.kind === 141 && member.initializer && (member.flags & 64) === 0) { + if (member.kind === 143 && member.initializer && (member.flags & 32) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -28925,7 +31042,6 @@ var ts; } var startIndex = 0; write(" {"); - scopeEmitStart(node, "constructor"); increaseIndent(); if (ctor) { startIndex = emitDirectivePrologues(ctor.body.statements, true); @@ -28937,7 +31053,7 @@ var ts; emitDefaultValueAssignments(ctor); emitRestParameter(ctor); if (baseTypeElement) { - superCall = findInitialSuperCall(ctor); + superCall = getSuperCallAtGivenIndex(ctor, startIndex); if (superCall) { writeLine(); emit(superCall); @@ -28973,7 +31089,6 @@ var ts; } decreaseIndent(); emitToken(16, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); emitEnd(ctor || node); if (ctor) { emitTrailingComments(ctor); @@ -28992,19 +31107,29 @@ var ts; else { emitClassLikeDeclarationForES6AndHigher(node); } - if (modulekind !== 5 && node.parent === currentSourceFile && node.name) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } } function emitClassLikeDeclarationForES6AndHigher(node) { + var decoratedClassAlias; var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 214) { + if (node.kind === 218) { if (thisNodeIsDecorated) { + if (resolver.getNodeCheckFlags(node) & 524288) { + decoratedClassAlias = ts.unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default")); + decoratedClassAliases[ts.getNodeId(node)] = decoratedClassAlias; + write("let " + decoratedClassAlias + ";"); + writeLine(); + } if (isES6ExportedDeclaration(node) && !(node.flags & 512)) { write("export "); } write("let "); emitDeclarationName(node); + if (decoratedClassAlias !== undefined) { + write(" = " + decoratedClassAlias); + } write(" = "); } else if (isES6ExportedDeclaration(node)) { @@ -29015,7 +31140,7 @@ var ts; } } var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186; + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 190; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0); @@ -29025,7 +31150,7 @@ var ts; write(" = "); } write("class"); - if ((node.name || (node.flags & 512 && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if (node.name || (node.flags & 512 && (staticProperties.length > 0 || modulekind !== ts.ModuleKind.ES6) && !thisNodeIsDecorated)) { write(" "); emitDeclarationName(node); } @@ -29036,15 +31161,14 @@ var ts; } write(" {"); increaseIndent(); - scopeEmitStart(node); writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES6AndHigher(node); decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); if (thisNodeIsDecorated) { + decoratedClassAliases[ts.getNodeId(node)] = undefined; write(";"); } if (isClassExpressionWithStaticProperties) { @@ -29063,26 +31187,36 @@ var ts; else { writeLine(); emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node); + emitDecoratorsOfClass(node, decoratedClassAlias); } - if (!isES6ExportedDeclaration(node) && (node.flags & 2)) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); + if (!(node.flags & 1)) { + return; } - else if (isES6ExportedDeclaration(node) && (node.flags & 512) && thisNodeIsDecorated) { - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); + if (modulekind !== ts.ModuleKind.ES6) { + emitExportMemberAssignment(node); + } + else { + if (node.flags & 512) { + if (thisNodeIsDecorated) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } + } + else if (node.parent.kind !== 252) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emitDeclarationName(node); + emitEnd(node); + write(";"); + } } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 214) { + if (node.kind === 218) { if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -29106,7 +31240,6 @@ var ts; tempParameters = undefined; computedPropertyNamesToGeneratedNames = undefined; increaseIndent(); - scopeEmitStart(node); if (baseTypeNode) { writeLine(); emitStart(baseTypeNode); @@ -29120,7 +31253,7 @@ var ts; emitMemberFunctionsForES5AndLower(node); emitPropertyDeclarations(node, getInitializedProperties(node, true)); writeLine(); - emitDecoratorsOfClass(node); + emitDecoratorsOfClass(node, undefined); writeLine(); emitToken(16, node.members.end, function () { write("return "); @@ -29137,73 +31270,71 @@ var ts; decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); emitStart(node); - write(")("); + write("("); if (baseTypeNode) { emit(baseTypeNode.expression); } - write(")"); - if (node.kind === 214) { + write("))"); + if (node.kind === 218) { write(";"); } emitEnd(node); - if (node.kind === 214) { + if (node.kind === 218) { emitExportMemberAssignment(node); } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); - if (!(member.flags & 64)) { + if (!(member.flags & 32)) { write(".prototype"); } } - function emitDecoratorsOfClass(node) { + function emitDecoratorsOfClass(node, decoratedClassAlias) { emitDecoratorsOfMembers(node, 0); - emitDecoratorsOfMembers(node, 64); - emitDecoratorsOfConstructor(node); + emitDecoratorsOfMembers(node, 32); + emitDecoratorsOfConstructor(node, decoratedClassAlias); } - function emitDecoratorsOfConstructor(node) { + function emitDecoratorsOfConstructor(node, decoratedClassAlias) { var decorators = node.decorators; var constructor = ts.getFirstConstructorWithBody(node); - var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); - if (!decorators && !hasDecoratedParameters) { + var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); + if (!decorators && !firstParameterDecorator) { return; } writeLine(); - emitStart(node); + emitStart(node.decorators || firstParameterDecorator); emitDeclarationName(node); + if (decoratedClassAlias !== undefined) { + write(" = " + decoratedClassAlias); + } write(" = __decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); + } emitSerializedTypeMetadata(node, argumentsWritten >= 0); decreaseIndent(); writeLine(); write("], "); emitDeclarationName(node); - write(");"); - emitEnd(node); + write(")"); + emitEnd(node.decorators || firstParameterDecorator); + write(";"); writeLine(); } function emitDecoratorsOfMembers(node, staticFlag) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.flags & 64) !== staticFlag) { + if ((member.flags & 32) !== staticFlag) { continue; } if (!ts.nodeCanBeDecorated(member)) { continue; } - if (!ts.nodeOrChildIsDecorated(member)) { - continue; - } var decorators = void 0; var functionLikeMember = void 0; if (ts.isAccessor(member)) { @@ -29219,107 +31350,106 @@ var ts; } else { decorators = member.decorators; - if (member.kind === 143) { + if (member.kind === 145) { functionLikeMember = member; } } + var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); + if (!decorators && !firstParameterDecorator) { + continue; + } writeLine(); - emitStart(member); + emitStart(decorators || firstParameterDecorator); write("__decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + } emitSerializedTypeMetadata(member, argumentsWritten > 0); decreaseIndent(); writeLine(); write("], "); - emitStart(member.name); emitClassMemberPrefix(node, member); write(", "); emitExpressionForPropertyName(member.name); - emitEnd(member.name); if (languageVersion > 0) { - if (member.kind !== 141) { + if (member.kind !== 143) { write(", null"); } else { write(", void 0"); } } - write(");"); - emitEnd(member); + write(")"); + emitEnd(decorators || firstParameterDecorator); + write(";"); writeLine(); } } function emitDecoratorsOfParameters(node, leadingComma) { var argumentsWritten = 0; if (node) { - var parameterIndex = 0; + var parameterIndex_1 = 0; for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) { var parameter = _b[_a]; if (ts.nodeIsDecorated(parameter)) { var decorators = parameter.decorators; argumentsWritten += emitList(decorators, 0, decorators.length, true, false, leadingComma, true, function (decorator) { - emitStart(decorator); - write("__param(" + parameterIndex + ", "); + write("__param(" + parameterIndex_1 + ", "); emit(decorator.expression); write(")"); - emitEnd(decorator); }); leadingComma = true; } - ++parameterIndex; + parameterIndex_1++; } } return argumentsWritten; } function shouldEmitTypeMetadata(node) { switch (node.kind) { - case 143: case 145: - case 146: - case 141: + case 147: + case 148: + case 143: return true; } return false; } function shouldEmitReturnTypeMetadata(node) { switch (node.kind) { - case 143: + case 145: return true; } return false; } function shouldEmitParamTypesMetadata(node) { switch (node.kind) { - case 214: - case 143: - case 146: + case 218: + case 145: + case 148: return true; } return false; } function emitSerializedTypeOfNode(node) { switch (node.kind) { - case 214: + case 218: write("Function"); return; - case 141: + case 143: emitSerializedTypeNode(node.type); return; - case 138: + case 140: emitSerializedTypeNode(node.type); return; - case 145: + case 147: emitSerializedTypeNode(node.type); return; - case 146: + case 148: emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); return; } @@ -29335,39 +31465,40 @@ var ts; case 103: write("void 0"); return; - case 160: + case 162: emitSerializedTypeNode(node.type); return; - case 152: - case 153: - write("Function"); - return; - case 156: - case 157: - write("Array"); - return; - case 150: - case 120: - write("Boolean"); - return; - case 130: - case 9: - write("String"); - return; - case 128: - write("Number"); - return; - case 131: - write("Symbol"); - return; - case 151: - emitSerializedTypeReferenceNode(node); - return; case 154: case 155: + write("Function"); + return; case 158: case 159: + write("Array"); + return; + case 152: + case 120: + write("Boolean"); + return; + case 131: + case 164: + write("String"); + return; + case 129: + write("Number"); + return; + case 132: + write("Symbol"); + return; + case 153: + emitSerializedTypeReferenceNode(node); + return; + case 156: + case 157: + case 160: + case 161: case 117: + case 163: break; default: ts.Debug.fail("Cannot serialize unexpected type node."); @@ -29381,8 +31512,7 @@ var ts; while (ts.isDeclaration(location) || ts.isTypeNode(location)) { location = location.parent; } - var typeName = ts.cloneEntityName(node.typeName); - typeName.parent = location; + var typeName = ts.cloneEntityName(node.typeName, location); var result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case ts.TypeReferenceSerializationKind.Unknown: @@ -29431,8 +31561,8 @@ var ts; } function emitSerializedParameterTypesOfNode(node) { if (node) { - var valueDeclaration; - if (node.kind === 214) { + var valueDeclaration = void 0; + if (node.kind === 218) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -29448,10 +31578,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 156) { + if (parameterType.kind === 158) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 151 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType.kind === 153 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -29522,9 +31652,10 @@ var ts; return; } if (!shouldHoistDeclarationInSystemJsModule(node)) { - if (!(node.flags & 2) || isES6ExportedDeclaration(node)) { + var isES6ExportedEnum = isES6ExportedDeclaration(node); + if (!(node.flags & 1) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 221))) { emitStart(node); - if (isES6ExportedDeclaration(node)) { + if (isES6ExportedEnum) { write("export "); } write("var "); @@ -29541,19 +31672,17 @@ var ts; emitEnd(node.name); write(") {"); increaseIndent(); - scopeEmitStart(node); emitLines(node.members); decreaseIndent(); writeLine(); emitToken(16, node.members.end); - scopeEmitEnd(); write(")("); emitModuleMemberName(node); write(" || ("); emitModuleMemberName(node); write(" = {}));"); emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 2 && !shouldHoistDeclarationInSystemJsModule(node)) { + if (!isES6ExportedDeclaration(node) && node.flags & 1 && !shouldHoistDeclarationInSystemJsModule(node)) { writeLine(); emitStart(node); write("var "); @@ -29563,8 +31692,8 @@ var ts; emitEnd(node); write(";"); } - if (modulekind !== 5 && node.parent === currentSourceFile) { - if (modulekind === 4 && (node.flags & 2)) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { + if (modulekind === ts.ModuleKind.System && (node.flags & 1)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -29604,7 +31733,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 218) { + if (moduleDeclaration.body.kind === 222) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -29615,6 +31744,9 @@ var ts; function isModuleMergedWithES6Class(node) { return languageVersion === 2 && !!(resolver.getNodeCheckFlags(node) & 32768); } + function isFirstDeclarationOfKind(node, declarations, kind) { + return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); + } function emitModuleDeclaration(node) { var shouldEmit = shouldEmitModuleDeclaration(node); if (!shouldEmit) { @@ -29623,15 +31755,18 @@ var ts; var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); + var isES6ExportedNamespace = isES6ExportedDeclaration(node); + if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 222)) { + emitStart(node); + if (isES6ExportedNamespace) { + write("export "); + } + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); } emitStart(node); write("(function ("); @@ -29639,7 +31774,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 219) { + if (node.body.kind === 223) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; @@ -29655,7 +31790,6 @@ var ts; else { write("{"); increaseIndent(); - scopeEmitStart(node); emitCaptureThisForNodeIfNecessary(node); writeLine(); emit(node.body); @@ -29663,10 +31797,9 @@ var ts; writeLine(); var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(16, moduleBlock.statements.end); - scopeEmitEnd(); } write(")("); - if ((node.flags & 2) && !isES6ExportedDeclaration(node)) { + if ((node.flags & 1) && !isES6ExportedDeclaration(node)) { emit(node.name); write(" = "); } @@ -29676,7 +31809,7 @@ var ts; write(" = {}));"); emitEnd(node); if (!isES6ExportedDeclaration(node) && node.name.kind === 69 && node.parent === currentSourceFile) { - if (modulekind === 4 && (node.flags & 2)) { + if (modulekind === ts.ModuleKind.System && (node.flags & 1)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -29688,8 +31821,8 @@ var ts; } } function tryRenameExternalModule(moduleName) { - if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) { - return "\"" + currentSourceFile.renamedDependencies[moduleName.text] + "\""; + if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { + return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; } @@ -29712,16 +31845,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 221) { + if (node.kind === 225) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 228) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 222 && node.importClause && !!node.importClause.name; + return node.kind === 226 && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -29730,7 +31863,7 @@ var ts; ts.forEachChild(node, emitExportImportAssignments); } function emitImportDeclaration(node) { - if (modulekind !== 5) { + if (modulekind !== ts.ModuleKind.ES6) { return emitExternalImportDeclaration(node); } if (node.importClause) { @@ -29748,7 +31881,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 224) { + if (node.importClause.namedBindings.kind === 228) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -29774,21 +31907,24 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 && (node.flags & 2) !== 0; + var isExportedImport = node.kind === 225 && (node.flags & 1) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); - if (modulekind !== 2) { + var varOrConst = (languageVersion <= 1) ? "var " : "const "; + if (modulekind !== ts.ModuleKind.AMD) { emitLeadingComments(node); emitStart(node); if (namespaceDeclaration && !isDefaultImport(node)) { - if (!isExportedImport) - write("var "); + if (!isExportedImport) { + write(varOrConst); + } + ; emitModuleMemberName(namespaceDeclaration); write(" = "); } else { - var isNakedImport = 222 && !node.importClause; + var isNakedImport = 226 && !node.importClause; if (!isNakedImport) { - write("var "); + write(varOrConst); write(getGeneratedNameForNode(node)); write(" = "); } @@ -29813,7 +31949,7 @@ var ts; write(";"); } else if (namespaceDeclaration && isDefaultImport(node)) { - write("var "); + write(varOrConst); emitModuleMemberName(namespaceDeclaration); write(" = "); write(getGeneratedNameForNode(node)); @@ -29829,7 +31965,7 @@ var ts; return; } if (resolver.isReferencedAliasDeclaration(node) || - (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { + (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { emitLeadingComments(node); emitStart(node); var variableDeclarationIsHoisted = shouldHoistVariable(node, true); @@ -29840,7 +31976,7 @@ var ts; write("export "); write("var "); } - else if (!(node.flags & 2)) { + else if (!(node.flags & 1)) { write("var "); } } @@ -29862,13 +31998,13 @@ var ts; } } function emitExportDeclaration(node) { - ts.Debug.assert(modulekind !== 4); - if (modulekind !== 5) { + ts.Debug.assert(modulekind !== ts.ModuleKind.System); + if (modulekind !== ts.ModuleKind.ES6) { if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { emitStart(node); var generatedName = getGeneratedNameForNode(node); if (node.exportClause) { - if (modulekind !== 2) { + if (modulekind !== ts.ModuleKind.AMD) { write("var "); write(generatedName); write(" = "); @@ -29893,15 +32029,17 @@ var ts; } } else { - writeLine(); - write("__export("); - if (modulekind !== 2) { - emitRequire(ts.getExternalModuleName(node)); + if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + writeLine(); + write("__export("); + if (modulekind !== ts.ModuleKind.AMD) { + emitRequire(ts.getExternalModuleName(node)); + } + else { + write(generatedName); + } + write(");"); } - else { - write(generatedName); - } - write(");"); } emitEnd(node); } @@ -29926,7 +32064,7 @@ var ts; } } function emitExportOrImportSpecifierList(specifiers, shouldEmit) { - ts.Debug.assert(modulekind === 5); + ts.Debug.assert(modulekind === ts.ModuleKind.ES6); var needsComma = false; for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { var specifier = specifiers_1[_a]; @@ -29945,14 +32083,14 @@ var ts; } function emitExportAssignment(node) { if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { - if (modulekind === 5) { + if (modulekind === ts.ModuleKind.ES6) { writeLine(); emitStart(node); write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 213 && - expression.kind !== 214) { + if (expression.kind !== 217 && + expression.kind !== 218) { write(";"); } emitEnd(node); @@ -29960,7 +32098,7 @@ var ts; else { writeLine(); emitStart(node); - if (modulekind === 4) { + if (modulekind === ts.ModuleKind.System) { write(exportFunctionForFile + "(\"default\","); emit(node.expression); write(")"); @@ -29985,26 +32123,28 @@ var ts; externalImports = []; exportSpecifiers = {}; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 222: + case 226: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, true)) { externalImports.push(node); } break; - case 221: - if (node.moduleReference.kind === 232 && resolver.isReferencedAliasDeclaration(node)) { + case 225: + if (node.moduleReference.kind === 236 && resolver.isReferencedAliasDeclaration(node)) { externalImports.push(node); } break; - case 228: + case 232: if (node.moduleSpecifier) { if (!node.exportClause) { - externalImports.push(node); - hasExportStars = true; + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } } else if (resolver.isValueAliasDeclaration(node)) { externalImports.push(node); @@ -30018,7 +32158,7 @@ var ts; } } break; - case 227: + case 231: if (node.isExportEquals && !exportEquals) { exportEquals = node; } @@ -30027,7 +32167,7 @@ var ts; } } function emitExportStarHelper() { - if (hasExportStars) { + if (hasExportStarsToExportValues) { writeLine(); write("function __export(m) {"); increaseIndent(); @@ -30041,16 +32181,22 @@ var ts; function getLocalNameForExternalImport(node) { var namespaceDeclaration = getNamespaceDeclarationNode(node); if (namespaceDeclaration && !isDefaultImport(node)) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); + return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); } - if (node.kind === 222 && node.importClause) { + if (node.kind === 226 && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 228 && node.moduleSpecifier) { + if (node.kind === 232 && node.moduleSpecifier) { return getGeneratedNameForNode(node); } } - function getExternalModuleNameText(importNode) { + function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { + if (emitRelativePathAsModuleName) { + var name_28 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_28) { + return "\"" + name_28 + "\""; + } + } var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); @@ -30065,8 +32211,8 @@ var ts; var started = false; for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { var importNode = externalImports_1[_a]; - var skipNode = importNode.kind === 228 || - (importNode.kind === 222 && !importNode.importClause); + var skipNode = importNode.kind === 232 || + (importNode.kind === 226 && !importNode.importClause); if (skipNode) { continue; } @@ -30084,14 +32230,14 @@ var ts; } } function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) { - if (!hasExportStars) { + if (!hasExportStarsToExportValues) { return undefined; } if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; - if (externalImport.kind === 228 && externalImport.exportClause) { + if (externalImport.kind === 232 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -30106,7 +32252,7 @@ var ts; increaseIndent(); var started = false; if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; ++i) { + for (var i = 0; i < exportedDeclarations.length; i++) { writeExportedName(exportedDeclarations[i]); } } @@ -30120,7 +32266,7 @@ var ts; } for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 228) { + if (externalImport.kind !== 232) { continue; } var exportDecl = externalImport; @@ -30192,13 +32338,13 @@ var ts; writeLine(); write("var "); var seen = {}; - for (var i = 0; i < hoistedVars.length; ++i) { + for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_28 = local.kind === 69 + var name_29 = local.kind === 69 ? local : local.name; - if (name_28) { - var text = ts.unescapeIdentifier(name_28.text); + if (name_29) { + var text = ts.unescapeIdentifier(name_29.text); if (ts.hasProperty(seen, text)) { continue; } @@ -30209,14 +32355,14 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 214 || local.kind === 218 || local.kind === 217) { + if (local.kind === 218 || local.kind === 222 || local.kind === 221) { emitDeclarationName(local); } else { emit(local); } var flags = ts.getCombinedNodeFlags(local.kind === 69 ? local.parent : local); - if (flags & 2) { + if (flags & 1) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -30230,7 +32376,7 @@ var ts; var f = hoistedFunctionDeclarations_1[_a]; writeLine(); emit(f); - if (f.flags & 2) { + if (f.flags & 1) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -30240,24 +32386,24 @@ var ts; } return exportedDeclarations; function visit(node) { - if (node.flags & 4) { + if (node.flags & 2) { return; } - if (node.kind === 213) { + if (node.kind === 217) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 214) { + if (node.kind === 218) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 217) { + if (node.kind === 221) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -30266,7 +32412,7 @@ var ts; } return; } - if (node.kind === 218) { + if (node.kind === 222) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -30275,17 +32421,17 @@ var ts; } return; } - if (node.kind === 211 || node.kind === 163) { + if (node.kind === 215 || node.kind === 167) { if (shouldHoistVariable(node, false)) { - var name_29 = node.name; - if (name_29.kind === 69) { + var name_30 = node.name; + if (name_30.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_29); + hoistedVars.push(name_30); } else { - ts.forEachChild(name_29, visit); + ts.forEachChild(name_30, visit); } } return; @@ -30310,11 +32456,11 @@ var ts; if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) { return false; } - return (ts.getCombinedNodeFlags(node) & 24576) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 248; + return (ts.getCombinedNodeFlags(node) & 3072) === 0 || + ts.getEnclosingBlockScopeContainer(node).kind === 252; } function isCurrentFileSystemExternalModule() { - return modulekind === 4 && ts.isExternalModule(currentSourceFile); + return modulekind === ts.ModuleKind.System && isCurrentFileExternalModule; } function emitSystemModuleBody(node, dependencyGroups, startIndex) { emitVariableDeclarationsForImports(); @@ -30335,7 +32481,7 @@ var ts; } function emitSetters(exportStarFunction, dependencyGroups) { write("setters:["); - for (var i = 0; i < dependencyGroups.length; ++i) { + for (var i = 0; i < dependencyGroups.length; i++) { if (i !== 0) { write(","); } @@ -30349,29 +32495,29 @@ var ts; var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { - case 222: + case 226: if (!entry.importClause) { break; } - case 221: + case 225: ts.Debug.assert(importVariableName !== ""); writeLine(); write(importVariableName + " = " + parameterName + ";"); writeLine(); break; - case 228: + case 232: ts.Debug.assert(importVariableName !== ""); if (entry.exportClause) { writeLine(); write(exportFunctionForFile + "({"); writeLine(); increaseIndent(); - for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) { - if (i_2 !== 0) { + for (var i_1 = 0, len = entry.exportClause.elements.length; i_1 < len; i_1++) { + if (i_1 !== 0) { write(","); writeLine(); } - var e = entry.exportClause.elements[i_2]; + var e = entry.exportClause.elements[i_1]; write("\""); emitNodeWithCommentsAndWithoutSourcemap(e.name); write("\": " + parameterName + "[\""); @@ -30400,13 +32546,13 @@ var ts; write("execute: function() {"); increaseIndent(); writeLine(); - for (var i = startIndex; i < node.statements.length; ++i) { + for (var i = startIndex; i < node.statements.length; i++) { var statement = node.statements[i]; switch (statement.kind) { - case 213: - case 222: + case 217: + case 226: continue; - case 228: + case 232: if (!statement.moduleSpecifier) { for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { var element = _b[_a]; @@ -30414,7 +32560,7 @@ var ts; } } continue; - case 221: + case 225: if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { continue; } @@ -30427,27 +32573,36 @@ var ts; writeLine(); write("}"); } - function emitSystemModule(node) { + function writeModuleName(node, emitRelativePathAsModuleName) { + var moduleName = node.moduleName; + if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) { + write("\"" + moduleName + "\", "); + } + } + function emitSystemModule(node, emitRelativePathAsModuleName) { collectExternalModuleInfo(node); ts.Debug.assert(!exportFunctionForFile); exportFunctionForFile = makeUniqueName("exports"); + contextObjectForFile = makeUniqueName("context"); writeLine(); write("System.register("); - if (node.moduleName) { - write("\"" + node.moduleName + "\", "); - } + writeModuleName(node, emitRelativePathAsModuleName); write("["); var groupIndices = {}; var dependencyGroups = []; - for (var i = 0; i < externalImports.length; ++i) { - var text = getExternalModuleNameText(externalImports[i]); - if (ts.hasProperty(groupIndices, text)) { - var groupIndex = groupIndices[text]; + for (var i = 0; i < externalImports.length; i++) { + var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); + if (text === undefined) { + continue; + } + var key = text.substr(1, text.length - 2); + if (ts.hasProperty(groupIndices, key)) { + var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; } else { - groupIndices[text] = dependencyGroups.length; + groupIndices[key] = dependencyGroups.length; dependencyGroups.push([externalImports[i]]); } if (i !== 0) { @@ -30455,10 +32610,13 @@ var ts; } write(text); } - write("], function(" + exportFunctionForFile + ") {"); + write("], function(" + exportFunctionForFile + ", " + contextObjectForFile + ") {"); writeLine(); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); + writeLine(); + write("var __moduleName = " + contextObjectForFile + " && " + contextObjectForFile + ".id;"); + writeLine(); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -30466,7 +32624,7 @@ var ts; writeLine(); write("});"); } - function getAMDDependencyNames(node, includeNonAmdDependencies) { + function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { var aliasedModuleNames = []; var unaliasedModuleNames = []; var importAliasNames = []; @@ -30482,7 +32640,7 @@ var ts; } for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { var importNode = externalImports_4[_c]; - var externalModuleName = getExternalModuleNameText(importNode); + var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { aliasedModuleNames.push(externalModuleName); @@ -30494,8 +32652,8 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } - function emitAMDDependencies(node, includeNonAmdDependencies) { - var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies); + function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { + var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName); emitAMDDependencyList(dependencyNames); write(", "); emitAMDFactoryHeader(dependencyNames); @@ -30522,17 +32680,15 @@ var ts; } write(") {"); } - function emitAMDModule(node) { + function emitAMDModule(node, emitRelativePathAsModuleName) { emitEmitHelpers(node); collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.moduleName) { - write("\"" + node.moduleName + "\", "); - } - emitAMDDependencies(node, true); + writeModuleName(node, emitRelativePathAsModuleName); + emitAMDDependencies(node, true, emitRelativePathAsModuleName); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30543,7 +32699,7 @@ var ts; write("});"); } function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, false); + var startIndex = emitDirectivePrologues(node.statements, false, !compilerOptions.noImplicitUseStrict); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -30562,7 +32718,7 @@ var ts; writeLines(" }\n})("); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, true); + var startIndex = emitDirectivePrologues(node.statements, true, !compilerOptions.noImplicitUseStrict); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30576,7 +32732,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; var startIndex = emitDirectivePrologues(node.statements, false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); @@ -30632,7 +32788,8 @@ var ts; if (result) { result = result.replace(/&(\w+);/g, function (s, m) { if (entities[m] !== undefined) { - return String.fromCharCode(entities[m]); + var ch = String.fromCharCode(entities[m]); + return ch === "\"" ? "\\\"" : ch; } else { return s; @@ -30641,6 +32798,16 @@ var ts; } return result; } + function isJsxChildEmittable(child) { + if (child.kind === 244) { + return !!child.expression; + } + else if (child.kind === 240) { + return !!getTextToEmit(child); + } + return true; + } + ; function getTextToEmit(node) { switch (compilerOptions.jsx) { case 2: @@ -30684,23 +32851,40 @@ var ts; } } } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { + function isUseStrictPrologue(node) { + return !!node.expression.text.match(/use strict/); + } + function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { + if (writeUseStrict) { + if (startWithNewLine) { + writeLine(); + } + write("\"use strict\";"); + } + } + function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { + var foundUseStrict = false; + for (var i = 0; i < statements.length; i++) { if (ts.isPrologueDirective(statements[i])) { + if (isUseStrictPrologue(statements[i])) { + foundUseStrict = true; + } if (startWithNewLine || i > 0) { writeLine(); } emit(statements[i]); } else { + ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); return i; } } + ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); return statements.length; } function writeLines(text) { var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; ++i) { + for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line.length) { writeLine(); @@ -30710,22 +32894,22 @@ var ts; } function emitEmitHelpers(node) { if (!compilerOptions.noEmitHelpers) { - if ((languageVersion < 2) && (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8)) { + if ((languageVersion < 2) && (!extendsEmitted && node.flags & 262144)) { writeLines(extendsHelper); extendsEmitted = true; } - if (!decorateEmitted && resolver.getNodeCheckFlags(node) & 16) { + if (!decorateEmitted && node.flags & 524288) { writeLines(decorateHelper); if (compilerOptions.emitDecoratorMetadata) { writeLines(metadataHelper); } decorateEmitted = true; } - if (!paramEmitted && resolver.getNodeCheckFlags(node) & 32) { + if (!paramEmitted && node.flags & 1048576) { writeLines(paramHelper); paramEmitted = true; } - if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & 64) { + if (!awaiterEmitted && node.flags & 2097152) { writeLines(awaiterHelper); awaiterEmitted = true; } @@ -30736,15 +32920,20 @@ var ts; emitShebang(); emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1]; - emitModule(node); + if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { + var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ts.ModuleKind.CommonJS]; + emitModule(node); + } + else { + bundleEmitDelegates[modulekind](node, true); + } } else { var startIndex = emitDirectivePrologues(node.statements, false); externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -30752,12 +32941,15 @@ var ts; } emitLeadingComments(node.endOfFileToken); } + function emit(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + } function emitNodeWithCommentsAndWithoutSourcemap(node) { emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); } function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { if (node) { - if (node.flags & 4) { + if (node.flags & 2) { return emitCommentsOnNotEmittedNode(node); } if (isSpecializedCommentHandling(node)) { @@ -30773,35 +32965,55 @@ var ts; } } } + function emitNodeWithSourceMap(node) { + if (node) { + emitStart(node); + emitNodeWithoutSourceMap(node); + emitEnd(node); + } + } function emitNodeWithoutSourceMap(node) { if (node) { emitJavaScriptWorker(node); } } + function changeSourceMapEmit(writer) { + sourceMap = writer; + emitStart = writer.emitStart; + emitEnd = writer.emitEnd; + emitPos = writer.emitPos; + setSourceFile = writer.setSourceFile; + } + function withTemporaryNoSourceMap(callback) { + var prevSourceMap = sourceMap; + setSourceMapWriterEmit(ts.getNullSourceMapWriter()); + callback(); + setSourceMapWriterEmit(prevSourceMap); + } function isSpecializedCommentHandling(node) { switch (node.kind) { - case 215: - case 213: - case 222: - case 221: - case 216: - case 227: + case 219: + case 217: + case 226: + case 225: + case 220: + case 231: return true; } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 193: + case 197: return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 218: + case 222: return shouldEmitModuleDeclaration(node); - case 217: + case 221: return shouldEmitEnumDeclaration(node); } ts.Debug.assert(!isSpecializedCommentHandling(node)); - if (node.kind !== 192 && + if (node.kind !== 196 && node.parent && - node.parent.kind === 174 && + node.parent.kind === 178 && node.parent.body === node && compilerOptions.target <= 1) { return false; @@ -30812,13 +33024,13 @@ var ts; switch (node.kind) { case 69: return emitIdentifier(node); - case 138: + case 140: return emitParameter(node); - case 143: - case 142: - return emitMethod(node); case 145: - case 146: + case 144: + return emitMethod(node); + case 147: + case 148: return emitAccessor(node); case 97: return emitThis(node); @@ -30838,142 +33050,142 @@ var ts; case 13: case 14: return emitLiteral(node); - case 183: - return emitTemplateExpression(node); - case 190: - return emitTemplateSpan(node); - case 233: - case 234: - return emitJsxElement(node); - case 236: - return emitJsxText(node); - case 240: - return emitJsxExpression(node); - case 135: - return emitQualifiedName(node); - case 161: - return emitObjectBindingPattern(node); - case 162: - return emitArrayBindingPattern(node); - case 163: - return emitBindingElement(node); - case 164: - return emitArrayLiteral(node); - case 165: - return emitObjectLiteral(node); - case 245: - return emitPropertyAssignment(node); - case 246: - return emitShorthandPropertyAssignment(node); - case 136: - return emitComputedPropertyName(node); - case 166: - return emitPropertyAccess(node); - case 167: - return emitIndexedAccess(node); - case 168: - return emitCallExpression(node); - case 169: - return emitNewExpression(node); - case 170: - return emitTaggedTemplateExpression(node); - case 171: - return emit(node.expression); - case 189: - return emit(node.expression); - case 172: - return emitParenExpression(node); - case 213: - case 173: - case 174: - return emitFunctionDeclaration(node); - case 175: - return emitDeleteExpression(node); - case 176: - return emitTypeOfExpression(node); - case 177: - return emitVoidExpression(node); - case 178: - return emitAwaitExpression(node); - case 179: - return emitPrefixUnaryExpression(node); - case 180: - return emitPostfixUnaryExpression(node); - case 181: - return emitBinaryExpression(node); - case 182: - return emitConditionalExpression(node); - case 185: - return emitSpreadElementExpression(node); - case 184: - return emitYieldExpression(node); case 187: - return; - case 192: - case 219: - return emitBlock(node); - case 193: - return emitVariableStatement(node); + return emitTemplateExpression(node); case 194: - return write(";"); - case 195: - return emitExpressionStatement(node); - case 196: - return emitIfStatement(node); - case 197: - return emitDoStatement(node); - case 198: - return emitWhileStatement(node); - case 199: - return emitForStatement(node); - case 201: - case 200: - return emitForInOrForOfStatement(node); - case 202: - case 203: - return emitBreakOrContinueStatement(node); - case 204: - return emitReturnStatement(node); - case 205: - return emitWithStatement(node); - case 206: - return emitSwitchStatement(node); - case 241: - case 242: - return emitCaseOrDefaultClause(node); - case 207: - return emitLabeledStatement(node); - case 208: - return emitThrowStatement(node); - case 209: - return emitTryStatement(node); + return emitTemplateSpan(node); + case 237: + case 238: + return emitJsxElement(node); + case 240: + return emitJsxText(node); case 244: - return emitCatchClause(node); - case 210: - return emitDebuggerStatement(node); - case 211: - return emitVariableDeclaration(node); - case 186: - return emitClassExpression(node); - case 214: - return emitClassDeclaration(node); - case 215: - return emitInterfaceDeclaration(node); + return emitJsxExpression(node); + case 137: + return emitQualifiedName(node); + case 165: + return emitObjectBindingPattern(node); + case 166: + return emitArrayBindingPattern(node); + case 167: + return emitBindingElement(node); + case 168: + return emitArrayLiteral(node); + case 169: + return emitObjectLiteral(node); + case 249: + return emitPropertyAssignment(node); + case 250: + return emitShorthandPropertyAssignment(node); + case 138: + return emitComputedPropertyName(node); + case 170: + return emitPropertyAccess(node); + case 171: + return emitIndexedAccess(node); + case 172: + return emitCallExpression(node); + case 173: + return emitNewExpression(node); + case 174: + return emitTaggedTemplateExpression(node); + case 175: + return emit(node.expression); + case 193: + return emit(node.expression); + case 176: + return emitParenExpression(node); case 217: - return emitEnumDeclaration(node); - case 247: - return emitEnumMember(node); - case 218: - return emitModuleDeclaration(node); - case 222: - return emitImportDeclaration(node); - case 221: - return emitImportEqualsDeclaration(node); - case 228: - return emitExportDeclaration(node); - case 227: - return emitExportAssignment(node); + case 177: + case 178: + return emitFunctionDeclaration(node); + case 179: + return emitDeleteExpression(node); + case 180: + return emitTypeOfExpression(node); + case 181: + return emitVoidExpression(node); + case 182: + return emitAwaitExpression(node); + case 183: + return emitPrefixUnaryExpression(node); + case 184: + return emitPostfixUnaryExpression(node); + case 185: + return emitBinaryExpression(node); + case 186: + return emitConditionalExpression(node); + case 189: + return emitSpreadElementExpression(node); + case 188: + return emitYieldExpression(node); + case 191: + return; + case 196: + case 223: + return emitBlock(node); + case 197: + return emitVariableStatement(node); + case 198: + return write(";"); + case 199: + return emitExpressionStatement(node); + case 200: + return emitIfStatement(node); + case 201: + return emitDoStatement(node); + case 202: + return emitWhileStatement(node); + case 203: + return emitForStatement(node); + case 205: + case 204: + return emitForInOrForOfStatement(node); + case 206: + case 207: + return emitBreakOrContinueStatement(node); + case 208: + return emitReturnStatement(node); + case 209: + return emitWithStatement(node); + case 210: + return emitSwitchStatement(node); + case 245: + case 246: + return emitCaseOrDefaultClause(node); + case 211: + return emitLabeledStatement(node); + case 212: + return emitThrowStatement(node); + case 213: + return emitTryStatement(node); case 248: + return emitCatchClause(node); + case 214: + return emitDebuggerStatement(node); + case 215: + return emitVariableDeclaration(node); + case 190: + return emitClassExpression(node); + case 218: + return emitClassDeclaration(node); + case 219: + return emitInterfaceDeclaration(node); + case 221: + return emitEnumDeclaration(node); + case 251: + return emitEnumMember(node); + case 222: + return emitModuleDeclaration(node); + case 226: + return emitImportDeclaration(node); + case 225: + return emitImportEqualsDeclaration(node); + case 232: + return emitExportDeclaration(node); + case 231: + return emitExportAssignment(node); + case 252: return emitSourceFileNode(node); } } @@ -30981,7 +33193,7 @@ var ts; return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } function getLeadingCommentsWithoutDetachedComments() { - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); + var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -30991,10 +33203,10 @@ var ts; return leadingComments; } function isTripleSlashComment(comment) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 && + if (currentText.charCodeAt(comment.pos + 1) === 47 && comment.pos + 2 < comment.end && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 47) { - var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end); + currentText.charCodeAt(comment.pos + 2) === 47) { + var textSubStr = currentText.substring(comment.pos, comment.end); return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? true : false; @@ -31003,20 +33215,20 @@ var ts; } function getLeadingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 248 || node.pos !== node.parent.pos) { + if (node.parent.kind === 252 || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { return getLeadingCommentsWithoutDetachedComments(); } else { - return ts.getLeadingCommentRangesOfNode(node, currentSourceFile); + return ts.getLeadingCommentRangesOfNodeFromText(node, currentText); } } } } function getTrailingCommentsToEmit(node) { if (node.parent) { - if (node.parent.kind === 248 || node.end !== node.parent.end) { - return ts.getTrailingCommentRanges(currentSourceFile.text, node.end); + if (node.parent.kind === 252 || node.end !== node.parent.end) { + return ts.getTrailingCommentRanges(currentText, node.end); } } } @@ -31039,22 +33251,22 @@ var ts; leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); } } - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment); } function emitTrailingComments(node) { if (compilerOptions.removeComments) { return; } var trailingComments = getTrailingCommentsToEmit(node); - ts.emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, trailingComments, false, newLine, writeComment); } function emitTrailingCommentsOfPosition(pos) { if (compilerOptions.removeComments) { return; } - var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos); - ts.emitComments(currentSourceFile, writer, trailingComments, true, newLine, writeComment); + var trailingComments = ts.getTrailingCommentRanges(currentText, pos); + ts.emitComments(currentText, currentLineMap, writer, trailingComments, true, newLine, writeComment); } function emitLeadingCommentsOfPositionWorker(pos) { if (compilerOptions.removeComments) { @@ -31065,13 +33277,13 @@ var ts; leadingComments = getLeadingCommentsWithoutDetachedComments(); } else { - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); + leadingComments = ts.getLeadingCommentRanges(currentText, pos); } - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); - ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, true, newLine, writeComment); } function emitDetachedCommentsAndUpdateCommentsInfo(node) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); + var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments); if (currentDetachedCommentInfo) { if (detachedCommentsInfo) { detachedCommentsInfo.push(currentDetachedCommentInfo); @@ -31081,18 +33293,30 @@ var ts; } } } + function writeComment(text, lineMap, writer, comment, newLine) { + emitPos(comment.pos); + ts.writeCommentRange(text, lineMap, writer, comment, newLine); + emitPos(comment.end); + } function emitShebang() { - var shebang = ts.getShebang(currentSourceFile.text); + var shebang = ts.getShebang(currentText); if (shebang) { write(shebang); + writeLine(); } } - var _a; + var _a, _b; } - function emitFile(jsFilePath, sourceFile) { - emitJavaScript(jsFilePath, sourceFile); - if (compilerOptions.declaration) { - ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); + function emitFile(_a, sourceFiles, isBundledEmit) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; + } + if (declarationFilePath) { + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } } } @@ -31105,11 +33329,11 @@ var ts; ts.ioReadTime = 0; ts.ioWriteTime = 0; var emptyArray = []; - ts.version = "1.8.0"; - function findConfigFile(searchPath) { + ts.version = "1.9.0"; + function findConfigFile(searchPath, fileExists) { var fileName = "tsconfig.json"; while (true) { - if (ts.sys.fileExists(fileName)) { + if (fileExists(fileName)) { return fileName; } var parentPath = ts.getDirectoryPath(searchPath); @@ -31128,86 +33352,331 @@ var ts; return ts.normalizePath(referencedFileName); } ts.resolveTripleslashReference = resolveTripleslashReference; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var moduleResolution = compilerOptions.moduleResolution !== undefined - ? compilerOptions.moduleResolution - : compilerOptions.module === 1 ? 2 : 1; - switch (moduleResolution) { - case 2: return nodeModuleNameResolver(moduleName, containingFile, host); - case 1: return classicNameResolver(moduleName, containingFile, compilerOptions, host); - } + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); } - ts.resolveModuleName = resolveModuleName; - function nodeModuleNameResolver(moduleName, containingFile, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { - var failedLookupLocations = []; - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host); - if (resolvedFileName) { - return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceModuleResolution && host.trace !== undefined; + } + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return str.indexOf(suffix, expectedPos) === expectedPos; + } + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + if (ts.isRootedDiskPath(moduleName)) { + return false; + } + var i = moduleName.lastIndexOf("./", 1); + var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46); + return !startsWithDotSlashOrDotDotSlash; + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); } - resolvedFileName = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); - return resolvedFileName - ? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } else { - return loadModuleFromNodeModules(moduleName, containingDirectory, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); } } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var longestMatchPrefixLength = -1; + var matchedPattern; + var matchedStar; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + for (var key in state.compilerOptions.paths) { + var pattern = key; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (moduleName.length >= prefix.length + suffix.length && + startsWith(moduleName, prefix) && + endsWith(moduleName, suffix)) { + if (prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = prefix.length; + matchedPattern = pattern; + matchedStar = moduleName.substr(prefix.length, moduleName.length - suffix.length); + } + } + } + else if (pattern === moduleName) { + matchedPattern = pattern; + matchedStar = undefined; + break; + } + } + } + if (matchedPattern) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPattern); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPattern]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("\*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var isExternalLibraryImport = false; + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function loadNodeModuleFromFile(candidate, failedLookupLocation, host) { - return ts.forEach(ts.moduleFileExtensions, tryLoad); + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + return ts.forEach(extensions, tryLoad); function tryLoad(ext) { + if (ext === ".tsx" && state.skipTsx) { + return undefined; + } var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (host.fileExists(fileName)) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName); + } return fileName; } else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } failedLookupLocation.push(fileName); return undefined; } } } - function loadNodeModuleFromDirectory(candidate, failedLookupLocation, host) { + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { var packageJsonPath = ts.combinePaths(candidate, "package.json"); - if (host.fileExists(packageJsonPath)) { - var jsonContent; + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var jsonContent = void 0; try { - var jsonText = host.readFile(packageJsonPath); + var jsonText = state.host.readFile(packageJsonPath); jsonContent = jsonText ? JSON.parse(jsonText) : { typings: undefined }; } catch (e) { jsonContent = { typings: undefined }; } if (jsonContent.typings) { - var result = loadNodeModuleFromFile(ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); - if (result) { - return result; + if (typeof jsonContent.typings === "string") { + var typingsFile = ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile); + } + var result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typingsFile), state.host), state); + if (result) { + return result; + } + } + else if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings); + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_typings_field); } } } else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } failedLookupLocation.push(packageJsonPath); } - return loadNodeModuleFromFile(ts.combinePaths(candidate, "index"), failedLookupLocation, host); + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } - function loadModuleFromNodeModules(moduleName, directory, host) { - var failedLookupLocations = []; + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { directory = ts.normalizeSlashes(directory); while (true) { var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var result = loadNodeModuleFromFile(candidate, failedLookupLocations, host); + var result = loadModuleFromFile(candidate, ts.supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { - return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; + return result; } - result = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); + result = loadNodeModuleFromDirectory(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { - return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; + return result; } } var parentPath = ts.getDirectoryPath(directory); @@ -31216,42 +33685,36 @@ var ts; } directory = parentPath; } - return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - function nameStartsWithDotSlashOrDotDotSlash(name) { - var i = name.lastIndexOf("./", 1); - return i === 0 || (i === 1 && name.charCodeAt(0) === 46); + return undefined; } function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - if (moduleName.indexOf("!") != -1) { - return { resolvedModule: undefined, failedLookupLocations: [] }; - } - var searchPath = ts.getDirectoryPath(containingFile); - var searchName; + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } var referencedSourceFile; - while (true) { - searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - referencedSourceFile = ts.forEach(ts.supportedExtensions, function (extension) { - if (extension === ".tsx" && !compilerOptions.jsx) { - return undefined; + if (moduleHasNonRelativeName(moduleName)) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + break; } - var candidate = searchName + extension; - if (host.fileExists(candidate)) { - return candidate; + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + break; } - else { - failedLookupLocations.push(candidate); - } - }); - if (referencedSourceFile) { - break; + containingDirectory = parentPath; } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); } return referencedSourceFile ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } @@ -31259,11 +33722,9 @@ var ts; } ts.classicNameResolver = classicNameResolver; ts.defaultInitCompilerOptions = { - module: 1, - target: 0, + module: ts.ModuleKind.CommonJS, + target: 1, noImplicitAny: false, - outDir: "built", - rootDir: ".", sourceMap: false }; function createCompilerHost(options, setParentNodes) { @@ -31329,14 +33790,16 @@ var ts; getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); } + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + trace: function (s) { return ts.sys.write(s + newLine); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); } }; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -31374,12 +33837,30 @@ var ts; var noDiagnosticsTypeChecker; var classifiableNames; var skipDefaultLib = options.noLib; + var supportedExtensions = ts.getSupportedExtensions(options); var start = new Date().getTime(); host = host || createCompilerHost(options); + var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var currentDirectory = host.getCurrentDirectory(); var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) - : (function (moduleNames, containingFile) { return ts.map(moduleNames, function (moduleName) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }); }); + : (function (moduleNames, containingFile) { + var resolvedModuleNames = []; + var lookup = {}; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedName = void 0; + if (ts.hasProperty(lookup, moduleName)) { + resolvedName = lookup[moduleName]; + } + else { + resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule; + lookup[moduleName] = resolvedName; + } + resolvedModuleNames.push(resolvedName); + } + return resolvedModuleNames; + }); var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (oldProgram) { @@ -31388,7 +33869,8 @@ var ts; (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx)) { + (oldOptions.jsx !== options.jsx) || + (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } @@ -31398,9 +33880,7 @@ var ts; processRootFile(host.getDefaultLibFileName(options), true); } } - verifyCompilerOptions(); oldProgram = undefined; - ts.programTime += new Date().getTime() - start; program = { getRootFileNames: function () { return rootNames; }, getSourceFile: getSourceFile, @@ -31414,7 +33894,7 @@ var ts; getTypeChecker: getTypeChecker, getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: function () { return commonSourceDirectory; }, + getCommonSourceDirectory: getCommonSourceDirectory, emit: emit, getCurrentDirectory: function () { return currentDirectory; }, getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, @@ -31423,7 +33903,23 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; } }; + verifyCompilerOptions(); + ts.programTime += new Date().getTime() - start; return program; + function getCommonSourceDirectory() { + if (typeof commonSourceDirectory === "undefined") { + if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(files); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); @@ -31466,10 +33962,13 @@ var ts; if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { return false; } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + return false; + } if (resolveModuleNamesWorker) { - var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); + var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); - for (var i = 0; i < moduleNames.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); var resolutionChanged = oldResolution @@ -31490,7 +33989,7 @@ var ts; } newSourceFiles.push(newSourceFile); } - for (var i = 0, len = newSourceFiles.length; i < len; ++i) { + for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; @@ -31511,7 +34010,8 @@ var ts; getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, - writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }) + writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }), + isEmitBlocked: isEmitBlocked }; } function getDiagnosticsProducingTypeChecker() { @@ -31524,9 +34024,22 @@ var ts; var _this = this; return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { - if (options.noEmitOnError && getPreEmitDiagnostics(program, undefined, cancellationToken).length > 0) { - return { diagnostics: [], sourceMaps: undefined, emitSkipped: true }; + var declarationDiagnostics = []; + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emitSkipped: true }; + } + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { diagnostics: diagnostics, sourceMaps: undefined, emitSkipped: true }; + } } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); var start = new Date().getTime(); @@ -31579,12 +34092,166 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? + getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : + typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } + function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var diagnostics = []; + walk(sourceFile); + return diagnostics; + function walk(node) { + if (!node) { + return false; + } + switch (node.kind) { + case 225: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return true; + case 231: + if (node.isExportEquals) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 218: + var classDeclaration = node; + if (checkModifiers(classDeclaration.modifiers) || + checkTypeParameters(classDeclaration.typeParameters)) { + return true; + } + break; + case 247: + var heritageClause = node; + if (heritageClause.token === 106) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 219: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 222: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 220: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return true; + case 145: + case 144: + case 146: + case 147: + case 148: + case 177: + case 217: + case 178: + case 217: + var functionDeclaration = node; + if (checkModifiers(functionDeclaration.modifiers) || + checkTypeParameters(functionDeclaration.typeParameters) || + checkTypeAnnotation(functionDeclaration.type)) { + return true; + } + break; + case 197: + var variableStatement = node; + if (checkModifiers(variableStatement.modifiers)) { + return true; + } + break; + case 215: + var variableDeclaration = node; + if (checkTypeAnnotation(variableDeclaration.type)) { + return true; + } + break; + case 172: + case 173: + var expression = node; + if (expression.typeArguments && expression.typeArguments.length > 0) { + var start_2 = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 140: + var parameter = node; + if (parameter.modifiers) { + var start_3 = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return true; + } + if (parameter.questionToken) { + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return true; + } + if (parameter.type) { + diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 143: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 221: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 175: + 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 141: + if (!options.experimentalDecorators) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + return true; + } + return ts.forEachChild(node, walk); + } + function checkTypeParameters(typeParameters) { + if (typeParameters) { + var start_4 = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkTypeAnnotation(type) { + if (type) { + diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkModifiers(modifiers) { + if (modifiers) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 112: + case 110: + case 111: + case 127: + case 122: + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + case 113: + case 82: + case 74: + case 77: + case 115: + } + } + } + return false; + } + }); + } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (!ts.isDeclarationFile(sourceFile)) { @@ -31617,21 +34284,32 @@ var ts; function moduleNameIsEqualTo(a, b) { return a.text === b.text; } + function getTextOfLiteral(literal) { + return literal.text; + } function collectExternalModuleReferences(file) { if (file.imports) { return; } + var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isExternalModuleFile = ts.isExternalModule(file); var imports; + var moduleAugmentations; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; - collect(node, true); + collectModuleReferences(node, false); + if (isJavaScriptFile) { + collectRequireCalls(node); + } } file.imports = imports || emptyArray; - function collect(node, allowRelativeModuleNames) { + file.moduleAugmentations = moduleAugmentations || emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 222: - case 221: - case 228: + case 226: + case 225: + case 232: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9) { break; @@ -31639,17 +34317,31 @@ var ts; if (!moduleNameExpr.text) { break; } - if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { + if (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { (imports || (imports = [])).push(moduleNameExpr); } break; - case 218: - if (node.name.kind === 9 && (node.flags & 4 || ts.isDeclarationFile(file))) { - ts.forEachChild(node.body, function (node) { - collect(node, false); - }); + case 222: + if (ts.isAmbientModule(node) && (inAmbientModule || node.flags & 2 || ts.isDeclarationFile(file))) { + var moduleName = node.name; + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { + (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); + } + else if (!inAmbientModule) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); + } + } } - break; + } + } + function collectRequireCalls(node) { + if (ts.isRequireCall(node, true)) { + (imports || (imports = [])).push(node.arguments[0]); + } + else { + ts.forEachChild(node, collectRequireCalls); } } } @@ -31657,9 +34349,9 @@ var ts; var diagnosticArgument; var diagnostic; if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; + diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; @@ -31677,7 +34369,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -31701,10 +34393,10 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function findSourceFile(fileName, normalizedAbsolutePath, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(normalizedAbsolutePath)) { - var file_1 = filesByName.get(normalizedAbsolutePath); - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== normalizedAbsolutePath) { + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + if (filesByName.contains(path)) { + var file_1 = filesByName.get(path); + if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } return file_1; @@ -31717,16 +34409,16 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); - filesByName.set(normalizedAbsolutePath, file); + filesByName.set(path, file); if (file) { - file.path = normalizedAbsolutePath; + file.path = path; if (host.useCaseSensitiveFileNames()) { - var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); + var existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(normalizedAbsolutePath, file); + filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -31736,7 +34428,6 @@ var ts; } processImportedModules(file, basePath); if (isDefaultLib) { - file.isDefaultLib = true; files.unshift(file); } else { @@ -31756,19 +34447,22 @@ var ts; } function processImportedModules(file, basePath) { collectExternalModuleReferences(file); - if (file.imports.length) { + if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = {}; - var moduleNames = ts.map(file.imports, function (name) { return name.text; }); + var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); - for (var i = 0; i < file.imports.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - if (resolution && !options.noResolve) { + var shouldAddFile = resolution && + !options.noResolve && + i < file.imports.length; + if (shouldAddFile) { var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { - if (!ts.isExternalModule(importedFile)) { - var start_2 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); + if (!ts.isExternalModule(importedFile) && importedFile.statements.length) { + var start_5 = ts.getTokenPosOfNode(file.imports[i], file); + fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { var firstRef = importedFile.referencedFiles[0]; @@ -31785,7 +34479,7 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var commonPathComponents; - ts.forEach(files, function (sourceFile) { + var failed = ts.forEach(files, function (sourceFile) { if (ts.isDeclarationFile(sourceFile)) { return; } @@ -31796,10 +34490,9 @@ var ts; return; } for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; + return true; } commonPathComponents.length = i; break; @@ -31809,14 +34502,20 @@ var ts; commonPathComponents.length = sourcePathComponents.length; } }); + if (failed) { + return ""; + } + if (!commonPathComponents) { + return currentDirectory; + } return ts.getNormalizedPathFromPathComponents(commonPathComponents); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -31850,14 +34549,33 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } - if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap")); + } + if (options.paths && options.baseUrl === undefined) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!hasZeroOrOneAsteriskCharacter(key)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); + } + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var subst = _a[_i]; + if (!hasZeroOrOneAsteriskCharacter(subst)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); + } + } } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } + if (options.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); + } } if (options.out && options.outFile) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); @@ -31866,16 +34584,15 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } - if (options.sourceRoot) { + if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } - return; } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); if (options.isolatedModules) { - if (!options.module && languageVersion < 2) { + if (options.module === ts.ModuleKind.None && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -31884,25 +34601,22 @@ var ts; programDiagnostics.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) { + else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } - if (options.module === 5 && languageVersion < 2) { + if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } + if (outFile && options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + } if (options.outDir || options.sourceRoot || - (options.mapRoot && - (!outFile || firstExternalModuleSourceFile !== undefined))) { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { - commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); - } - else { - commonSourceDirectory = computeCommonSourceDirectory(files); - } - if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { - commonSourceDirectory += ts.directorySeparator; + options.mapRoot) { + var dir = getCommonSourceDirectory(); + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { @@ -31919,10 +34633,42 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } + else if (options.allowJs && options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } + if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + } + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + if (filesByName.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + } + if (emitFilesSeen.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + } + else { + emitFilesSeen.set(emitFilePath, true); + } + } + } + } + function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); } } ts.createProgram = createProgram; @@ -31932,12 +34678,12 @@ var ts; var BreakpointResolver; (function (BreakpointResolver) { function spanInSourceFileAtLocation(sourceFile, position) { - if (sourceFile.flags & 4096) { + if (sourceFile.isDeclarationFile) { return undefined; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) { + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { return undefined; @@ -31948,14 +34694,23 @@ var ts; } return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); + } + function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent)); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { - if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { return spanInNode(node); } return spanInNode(otherwiseOnNode); } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } @@ -31964,99 +34719,90 @@ var ts; } function spanInNode(node) { if (node) { - if (ts.isExpression(node)) { - if (node.parent.kind === 197) { - return spanInPreviousNode(node); - } - if (node.parent.kind === 199) { - return textSpan(node); - } - if (node.parent.kind === 181 && node.parent.operatorToken.kind === 24) { - return textSpan(node); - } - if (node.parent.kind === 174 && node.parent.body === node) { - return textSpan(node); - } - } switch (node.kind) { - case 193: + case 197: return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 211: - case 141: - case 140: - return spanInVariableDeclaration(node); - case 138: - return spanInParameterDeclaration(node); - case 213: + case 215: case 143: case 142: + return spanInVariableDeclaration(node); + case 140: + return spanInParameterDeclaration(node); + case 217: case 145: - case 146: case 144: - case 173: - case 174: + case 147: + case 148: + case 146: + case 177: + case 178: return spanInFunctionDeclaration(node); - case 192: + case 196: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } - case 219: + case 223: return spanInBlock(node); - case 244: + case 248: return spanInBlock(node.block); - case 195: - return textSpan(node.expression); - case 204: - return textSpan(node.getChildAt(0), node.expression); - case 198: - return textSpan(node, ts.findNextToken(node.expression, node)); - case 197: - return spanInNode(node.statement); - case 210: - return textSpan(node.getChildAt(0)); - case 196: - return textSpan(node, ts.findNextToken(node.expression, node)); - case 207: - return spanInNode(node.statement); - case 203: - case 202: - return textSpan(node.getChildAt(0), node.label); case 199: - return spanInForStatement(node); - case 200: - case 201: - return textSpan(node, ts.findNextToken(node.expression, node)); - case 206: - return textSpan(node, ts.findNextToken(node.expression, node)); - case 241: - case 242: - return spanInNode(node.statements[0]); - case 209: - return spanInBlock(node.tryBlock); + return textSpan(node.expression); case 208: + return textSpan(node.getChildAt(0), node.expression); + case 202: + return textSpanEndingAtNextToken(node, node.expression); + case 201: + return spanInNode(node.statement); + case 214: + return textSpan(node.getChildAt(0)); + case 200: + return textSpanEndingAtNextToken(node, node.expression); + case 211: + return spanInNode(node.statement); + case 207: + case 206: + return textSpan(node.getChildAt(0), node.label); + case 203: + return spanInForStatement(node); + case 204: + return textSpanEndingAtNextToken(node, node.expression); + case 205: + return spanInInitializerOfForLike(node); + case 210: + return textSpanEndingAtNextToken(node, node.expression); + case 245: + case 246: + return spanInNode(node.statements[0]); + case 213: + return spanInBlock(node.tryBlock); + case 212: return textSpan(node, node.expression); - case 227: + case 231: return textSpan(node, node.expression); - case 221: + case 225: return textSpan(node, node.moduleReference); + case 226: + return textSpan(node, node.moduleSpecifier); + case 232: + return textSpan(node, node.moduleSpecifier); case 222: - return textSpan(node, node.moduleSpecifier); - case 228: - return textSpan(node, node.moduleSpecifier); - case 218: if (ts.getModuleInstanceState(node) !== 1) { return undefined; } - case 214: - case 217: - case 247: - case 168: - case 169: + case 218: + case 221: + case 251: + case 167: return textSpan(node); - case 205: + case 209: return spanInNode(node.statement); - case 215: - case 216: + case 141: + return spanInNodeArray(node.parent.decorators); + case 165: + case 166: + return spanInBindingPattern(node); + case 219: + case 220: return undefined; case 23: case 1: @@ -32067,6 +34813,8 @@ var ts; return spanInOpenBraceToken(node); case 16: return spanInCloseBraceToken(node); + case 20: + return spanInCloseBracketToken(node); case 17: return spanInOpenParenToken(node); case 18: @@ -32082,56 +34830,119 @@ var ts; case 72: case 85: return spanInNextNode(node); + case 136: + return spanInOfKeyword(node); default: - if (node.parent.kind === 245 && node.parent.name === node) { + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); + } + if ((node.kind === 69 || + node.kind == 189 || + node.kind === 249 || + node.kind === 250) && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + return textSpan(node); + } + if (node.kind === 185) { + var binaryExpression = node; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); + } + if (binaryExpression.operatorToken.kind === 56 && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { + return textSpan(node); + } + if (binaryExpression.operatorToken.kind === 24) { + return spanInNode(binaryExpression.left); + } + } + if (ts.isExpression(node)) { + switch (node.parent.kind) { + case 201: + return spanInPreviousNode(node); + case 141: + return spanInNode(node.parent); + case 203: + case 205: + return textSpan(node); + case 185: + if (node.parent.operatorToken.kind === 24) { + return textSpan(node); + } + break; + case 178: + if (node.parent.body === node) { + return textSpan(node); + } + break; + } + } + if (node.parent.kind === 249 && + node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } - if (node.parent.kind === 171 && node.parent.type === node) { - return spanInNode(node.parent.expression); + if (node.parent.kind === 175 && node.parent.type === node) { + return spanInNextNode(node.parent.type); } if (ts.isFunctionLike(node.parent) && node.parent.type === node) { return spanInPreviousNode(node); } + if ((node.parent.kind === 215 || + node.parent.kind === 140)) { + var paramOrVarDecl = node.parent; + if (paramOrVarDecl.initializer === node || + paramOrVarDecl.type === node || + ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + } + if (node.parent.kind === 185) { + var binaryExpression = node.parent; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && + (binaryExpression.right === node || + binaryExpression.operatorToken === node)) { + return spanInPreviousNode(node); + } + } return spanInNode(node.parent); } } + function textSpanFromVariableDeclaration(variableDeclaration) { + var declarations = variableDeclaration.parent.declarations; + if (declarations && declarations[0] === variableDeclaration) { + return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); + } + else { + return textSpan(variableDeclaration); + } + } function spanInVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.parent.kind === 200 || - variableDeclaration.parent.parent.kind === 201) { + if (variableDeclaration.parent.parent.kind === 204) { return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.parent.kind === 193; - var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 199 && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); - var declarations = isParentVariableStatement - ? variableDeclaration.parent.parent.declarationList.declarations - : isDeclarationOfForStatement - ? variableDeclaration.parent.parent.initializer.declarations - : undefined; - if (variableDeclaration.initializer || (variableDeclaration.flags & 2)) { - if (declarations && declarations[0] === variableDeclaration) { - if (isParentVariableStatement) { - return textSpan(variableDeclaration.parent, variableDeclaration); - } - else { - ts.Debug.assert(isDeclarationOfForStatement); - return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); - } - } - else { - return textSpan(variableDeclaration); - } + if (ts.isBindingPattern(variableDeclaration.name)) { + return spanInBindingPattern(variableDeclaration.name); } - else if (declarations && declarations[0] !== variableDeclaration) { - var indexOfCurrentDeclaration = ts.indexOf(declarations, variableDeclaration); - return spanInVariableDeclaration(declarations[indexOfCurrentDeclaration - 1]); + if (variableDeclaration.initializer || + (variableDeclaration.flags & 1) || + variableDeclaration.parent.parent.kind === 205) { + return textSpanFromVariableDeclaration(variableDeclaration); + } + var declarations = variableDeclaration.parent.declarations; + if (declarations && declarations[0] !== variableDeclaration) { + return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); } } function canHaveSpanInParameterDeclaration(parameter) { return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - !!(parameter.flags & 8) || !!(parameter.flags & 16); + !!(parameter.flags & 4) || !!(parameter.flags & 8); } function spanInParameterDeclaration(parameter) { - if (canHaveSpanInParameterDeclaration(parameter)) { + if (ts.isBindingPattern(parameter.name)) { + return spanInBindingPattern(parameter.name); + } + else if (canHaveSpanInParameterDeclaration(parameter)) { return textSpan(parameter); } else { @@ -32146,8 +34957,8 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 2) || - (functionDeclaration.parent.kind === 214 && functionDeclaration.kind !== 144); + return !!(functionDeclaration.flags & 1) || + (functionDeclaration.parent.kind === 218 && functionDeclaration.kind !== 146); } function spanInFunctionDeclaration(functionDeclaration) { if (!functionDeclaration.body) { @@ -32167,31 +34978,34 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 218: + case 222: if (ts.getModuleInstanceState(block.parent) !== 1) { return undefined; } - case 198: - case 196: + case 202: case 200: - case 201: + case 204: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); - case 199: + case 203: + case 205: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } return spanInNode(block.statements[0]); } + function spanInInitializerOfForLike(forLikeStaement) { + if (forLikeStaement.initializer.kind === 216) { + var variableDeclarationList = forLikeStaement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + return spanInNode(forLikeStaement.initializer); + } + } function spanInForStatement(forStatement) { if (forStatement.initializer) { - if (forStatement.initializer.kind === 212) { - var variableDeclarationList = forStatement.initializer; - if (variableDeclarationList.declarations.length > 0) { - return spanInNode(variableDeclarationList.declarations[0]); - } - } - else { - return spanInNode(forStatement.initializer); - } + return spanInInitializerOfForLike(forStatement); } if (forStatement.condition) { return textSpan(forStatement.condition); @@ -32200,84 +35014,142 @@ var ts; return textSpan(forStatement.incrementor); } } + function spanInBindingPattern(bindingPattern) { + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 191 ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + if (bindingPattern.parent.kind === 167) { + return textSpan(bindingPattern.parent); + } + return textSpanFromVariableDeclaration(bindingPattern.parent); + } + function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { + ts.Debug.assert(node.kind !== 166 && node.kind !== 165); + var elements = node.kind === 168 ? + node.elements : + node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 191 ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + return textSpan(node.parent.kind === 185 ? node.parent : node); + } function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 217: + case 221: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 214: + case 218: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 220: + case 224: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } return spanInNode(node.parent); } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 219: + case 223: if (ts.getModuleInstanceState(node.parent.parent) !== 1) { return undefined; } - case 217: - case 214: + case 221: + case 218: return textSpan(node); - case 192: + case 196: if (ts.isFunctionBlock(node.parent)) { return textSpan(node); } - case 244: + case 248: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 220: + case 224: var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; + case 165: + var bindingPattern = node.parent; + return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + var objectLiteral = node.parent; + return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral); + } + return spanInNode(node.parent); + } + } + function spanInCloseBracketToken(node) { + switch (node.parent.kind) { + case 166: + var bindingPattern = node.parent; + return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + var arrayLiteral = node.parent; + return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral); + } return spanInNode(node.parent); } } function spanInOpenParenToken(node) { - if (node.parent.kind === 197) { + if (node.parent.kind === 201 || + node.parent.kind === 172 || + node.parent.kind === 173) { return spanInPreviousNode(node); } + if (node.parent.kind === 176) { + return spanInNextNode(node); + } return spanInNode(node.parent); } function spanInCloseParenToken(node) { switch (node.parent.kind) { - case 173: - case 213: - case 174: - case 143: - case 142: + case 177: + case 217: + case 178: case 145: - case 146: case 144: - case 198: - case 197: - case 199: + case 147: + case 148: + case 146: + case 202: + case 201: + case 203: + case 205: + case 172: + case 173: + case 176: return spanInPreviousNode(node); default: return spanInNode(node.parent); } } function spanInColonToken(node) { - if (ts.isFunctionLike(node.parent) || node.parent.kind === 245) { + if (ts.isFunctionLike(node.parent) || + node.parent.kind === 249 || + node.parent.kind === 140) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 171) { - return spanInNode(node.parent.expression); + if (node.parent.kind === 175) { + return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 197) { - return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); + if (node.parent.kind === 201) { + return textSpanEndingAtNextToken(node, node.parent.expression); + } + return spanInNode(node.parent); + } + function spanInOfKeyword(node) { + if (node.parent.kind === 205) { + return spanInNextNode(node); } return spanInNode(node.parent); } @@ -32354,7 +35226,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 174; + return ts.isFunctionBlock(node) && node.parent.kind !== 178; } var depth = 0; var maxDepth = 20; @@ -32366,26 +35238,26 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 192: + case 196: if (!ts.isFunctionBlock(n)) { - var parent_7 = n.parent; + var parent_9 = n.parent; var openBrace = ts.findChildOfKind(n, 15, sourceFile); var closeBrace = ts.findChildOfKind(n, 16, sourceFile); - if (parent_7.kind === 197 || - parent_7.kind === 200 || - parent_7.kind === 201 || - parent_7.kind === 199 || - parent_7.kind === 196 || - parent_7.kind === 198 || - parent_7.kind === 205 || - parent_7.kind === 244) { - addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); + if (parent_9.kind === 201 || + parent_9.kind === 204 || + parent_9.kind === 205 || + parent_9.kind === 203 || + parent_9.kind === 200 || + parent_9.kind === 202 || + parent_9.kind === 209 || + parent_9.kind === 248) { + addOutliningSpan(parent_9, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_7.kind === 209) { - var tryStatement = parent_7; + if (parent_9.kind === 213) { + var tryStatement = parent_9; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_9, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -32405,23 +35277,23 @@ var ts; }); break; } - case 219: { + case 223: { var openBrace = ts.findChildOfKind(n, 15, sourceFile); var closeBrace = ts.findChildOfKind(n, 16, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 214: - case 215: - case 217: - case 165: - case 220: { + case 218: + case 219: + case 221: + case 169: + case 224: { var openBrace = ts.findChildOfKind(n, 15, sourceFile); var closeBrace = ts.findChildOfKind(n, 16, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 164: + case 168: var openBracket = ts.findChildOfKind(n, 19, sourceFile); var closeBracket = ts.findChildOfKind(n, 20, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); @@ -32448,28 +35320,28 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_30 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_30); + for (var name_31 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_31); if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_30); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_31); if (!matches) { continue; } - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; if (patternMatcher.patternContainsDots) { var containers = getContainers(declaration); if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_30); + matches = patternMatcher.getMatches(containers, name_31); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_30, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_31, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -32506,7 +35378,7 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 136) { + else if (declaration.name.kind === 138) { return tryAddComputedPropertyName(declaration.name.expression, containers, true); } else { @@ -32523,7 +35395,7 @@ var ts; } return true; } - if (expression.kind === 166) { + if (expression.kind === 170) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); @@ -32534,7 +35406,7 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 136) { + if (declaration.name.kind === 138) { if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { return undefined; } @@ -32588,7 +35460,7 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile) { + function getNavigationBarItems(sourceFile, compilerOptions) { var hasGlobalNode = false; return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); function getIndent(node) { @@ -32596,14 +35468,14 @@ var ts; var current = node.parent; while (current) { switch (current.kind) { - case 218: + case 222: do { current = current.parent; - } while (current.kind === 218); - case 214: + } while (current.kind === 222); + case 218: + case 221: + case 219: case 217: - case 215: - case 213: indent++; } current = current.parent; @@ -32614,26 +35486,26 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 193: + case 197: ts.forEach(node.declarationList.declarations, visit); break; - case 161: - case 162: + case 165: + case 166: ts.forEach(node.elements, visit); break; - case 228: + case 232: if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 222: + case 226: var importClause = node.importClause; if (importClause) { if (importClause.name) { childNodes.push(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224) { + if (importClause.namedBindings.kind === 228) { childNodes.push(importClause.namedBindings); } else { @@ -32642,20 +35514,20 @@ var ts; } } break; - case 163: - case 211: + case 167: + case 215: if (ts.isBindingPattern(node.name)) { visit(node.name); break; } - case 214: - case 217: - case 215: case 218: - case 213: case 221: - case 226: + case 219: + case 222: + case 217: + case 225: case 230: + case 234: childNodes.push(node); break; } @@ -32690,17 +35562,17 @@ var ts; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { var node = nodes_4[_i]; switch (node.kind) { - case 214: - case 217: - case 215: + case 218: + case 221: + case 219: topLevelNodes.push(node); break; - case 218: + case 222: var moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); break; - case 213: + case 217: var functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); @@ -32711,9 +35583,9 @@ var ts; } } function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 213) { - if (functionDeclaration.body && functionDeclaration.body.kind === 192) { - if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 213 && !isEmpty(s.name.text); })) { + if (functionDeclaration.kind === 217) { + if (functionDeclaration.body && functionDeclaration.body.kind === 196) { + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 217 && !isEmpty(s.name.text); })) { return true; } if (!ts.isFunctionBlock(functionDeclaration.parent)) { @@ -32766,42 +35638,42 @@ var ts; } function createChildItem(node) { switch (node.kind) { - case 138: + case 140: if (ts.isBindingPattern(node.name)) { break; } - if ((node.flags & 1022) === 0) { + if ((node.flags & 959) === 0) { return undefined; } return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 145: + case 144: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); + case 147: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); + case 148: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); + case 151: + return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); + case 251: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 149: + return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); + case 150: + return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); case 143: case 142: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 145: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 146: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 149: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 247: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 148: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 141: - case 140: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 213: + case 217: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 211: - case 163: - var variableDeclarationNode; - var name_31; - if (node.kind === 163) { - name_31 = node.name; + case 215: + case 167: + var variableDeclarationNode = void 0; + var name_32; + if (node.kind === 167) { + name_32 = node.name; variableDeclarationNode = node; - while (variableDeclarationNode && variableDeclarationNode.kind !== 211) { + while (variableDeclarationNode && variableDeclarationNode.kind !== 215) { variableDeclarationNode = variableDeclarationNode.parent; } ts.Debug.assert(variableDeclarationNode !== undefined); @@ -32809,24 +35681,24 @@ var ts; else { ts.Debug.assert(!ts.isBindingPattern(node.name)); variableDeclarationNode = node; - name_31 = node.name; + name_32 = node.name; } if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.constElement); + return createItem(node, getTextOfNode(name_32), ts.ScriptElementKind.constElement); } else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.letElement); + return createItem(node, getTextOfNode(name_32), ts.ScriptElementKind.letElement); } else { - return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.variableElement); + return createItem(node, getTextOfNode(name_32), ts.ScriptElementKind.variableElement); } - case 144: + case 146: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); + case 234: case 230: - case 226: - case 221: - case 223: - case 224: + case 225: + case 227: + case 228: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); } return undefined; @@ -32856,27 +35728,27 @@ var ts; } function createTopLevelItem(node) { switch (node.kind) { - case 248: + case 252: return createSourceFileItem(node); - case 214: - return createClassItem(node); - case 217: - return createEnumItem(node); - case 215: - return createIterfaceItem(node); case 218: + return createClassItem(node); + case 221: + return createEnumItem(node); + case 219: + return createIterfaceItem(node); + case 222: return createModuleItem(node); - case 213: + case 217: return createFunctionItem(node); } return undefined; function getModuleName(moduleDeclaration) { - if (moduleDeclaration.name.kind === 9) { + if (ts.isAmbientModule(moduleDeclaration)) { return getTextOfNode(moduleDeclaration.name); } var result = []; result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 218) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 222) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -32888,7 +35760,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 === 192) { + if (node.body && node.body.kind === 196) { 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)); } @@ -32909,7 +35781,7 @@ var ts; var childItems; if (node.members) { var constructor = ts.forEach(node.members, function (member) { - return member.kind === 144 && member; + return member.kind === 146 && member; }); var nodes = removeDynamicallyNamedProperties(node); if (constructor) { @@ -32930,19 +35802,19 @@ var ts; } } function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 136; }); + return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 138; }); } function removeDynamicallyNamedProperties(node) { return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); } function getInnermostModule(node) { - while (node.body.kind === 218) { + while (node.body.kind === 222) { node = node.body; } return node; } function getNodeSpan(node) { - return node.kind === 248 + return node.kind === 252 ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } @@ -32973,7 +35845,6 @@ var ts; function createPatternMatcher(pattern) { var stringToWordSpans = {}; pattern = pattern.trim(); - var fullPatternSegment = createSegment(pattern); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); return { @@ -33003,7 +35874,7 @@ var ts; return undefined; } var totalMatch = candidateMatch; - for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i--, j--) { + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { var segment = dotSeparatedSegments[i]; var containerName = candidateContainers[j]; var containerMatch = matchSegment(containerName, segment); @@ -33170,33 +36041,6 @@ var ts; } } ts.createPatternMatcher = createPatternMatcher; - function patternMatchCompareTo(match1, match2) { - return compareType(match1, match2) || - compareCamelCase(match1, match2) || - compareCase(match1, match2) || - comparePunctuation(match1, match2); - } - function comparePunctuation(result1, result2) { - if (result1.punctuationStripped !== result2.punctuationStripped) { - return result1.punctuationStripped ? 1 : -1; - } - return 0; - } - function compareCase(result1, result2) { - if (result1.isCaseSensitive !== result2.isCaseSensitive) { - return result1.isCaseSensitive ? -1 : 1; - } - return 0; - } - function compareType(result1, result2) { - return result1.kind - result2.kind; - } - function compareCamelCase(result1, result2) { - if (result1.kind === PatternMatchKind.camelCase && result2.kind === PatternMatchKind.camelCase) { - return result2.camelCaseWeight - result1.camelCaseWeight; - } - return 0; - } function createSegment(text) { return { totalTextChunk: createTextChunk(text), @@ -33226,14 +36070,6 @@ var ts; var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function containsUpperCaseLetter(string) { - for (var i = 0, n = string.length; i < n; i++) { - if (isUpperCaseLetter(string.charCodeAt(i))) { - return true; - } - } - return false; - } function startsWith(string, search) { for (var i = 0, n = search.length; i < n; i++) { if (string.charCodeAt(i) !== search.charCodeAt(i)) { @@ -33282,9 +36118,10 @@ var ts; for (var i = 0; i < pattern.length; i++) { var ch = pattern.charCodeAt(i); if (isWordChar(ch)) { - if (wordLength++ === 0) { + if (wordLength === 0) { wordStart = i; } + wordLength++; } else { if (wordLength > 0) { @@ -33425,21 +36262,21 @@ var ts; var resolvedSignature = typeChecker.getResolvedSignature(call, candidates); cancellationToken.throwIfCancellationRequested(); if (!candidates.length) { - if (ts.isJavaScript(sourceFile.fileName)) { + if (ts.isSourceFileJavaScript(sourceFile)) { return createJavaScriptSignatureHelpItems(argumentInfo); } return undefined; } return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo); function createJavaScriptSignatureHelpItems(argumentInfo) { - if (argumentInfo.invocation.kind !== 168) { + if (argumentInfo.invocation.kind !== 172) { return undefined; } var callExpression = argumentInfo.invocation; var expression = callExpression.expression; var name = expression.kind === 69 ? expression - : expression.kind === 166 + : expression.kind === 170 ? expression.name : undefined; if (!name || !name.text) { @@ -33451,8 +36288,8 @@ var ts; var nameToDeclarations = sourceFile_1.getNamedDeclarations(); var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { - for (var _b = 0, declarations_7 = declarations; _b < declarations_7.length; _b++) { - var declaration = declarations_7[_b]; + for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { + var declaration = declarations_8[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -33468,7 +36305,7 @@ var ts; } } function getImmediatelyContainingArgumentInfo(node) { - if (node.parent.kind === 168 || node.parent.kind === 169) { + if (node.parent.kind === 172 || node.parent.kind === 173) { var callExpression = node.parent; if (node.kind === 25 || node.kind === 17) { @@ -33499,23 +36336,23 @@ var ts; }; } } - else if (node.kind === 11 && node.parent.kind === 170) { + else if (node.kind === 11 && node.parent.kind === 174) { if (ts.isInsideTemplateLiteral(node, position)) { return getArgumentListInfoForTemplate(node.parent, 0); } } - else if (node.kind === 12 && node.parent.parent.kind === 170) { + else if (node.kind === 12 && node.parent.parent.kind === 174) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183); + ts.Debug.assert(templateExpression.kind === 187); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - else if (node.parent.kind === 190 && node.parent.parent.parent.kind === 170) { + else if (node.parent.kind === 194 && node.parent.parent.parent.kind === 174) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183); + ts.Debug.assert(templateExpression.kind === 187); if (node.kind === 14 && !ts.isInsideTemplateLiteral(node, position)) { return undefined; } @@ -33579,7 +36416,7 @@ var ts; var template = taggedTemplate.template; var applicableSpanStart = template.getStart(); var applicableSpanEnd = template.getEnd(); - if (template.kind === 183) { + if (template.kind === 187) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); @@ -33588,7 +36425,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { - for (var n = node; n.kind !== 248; n = n.parent) { + for (var n = node; n.kind !== 252; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -33768,39 +36605,39 @@ var ts; return false; } switch (n.kind) { - case 214: - case 215: - case 217: - case 165: - case 161: - case 155: - case 192: + case 218: case 219: - case 220: - return nodeEndsWith(n, 16, sourceFile); - case 244: - return isCompletedNode(n.block, sourceFile); + case 221: case 169: + case 165: + case 157: + case 196: + case 223: + case 224: + return nodeEndsWith(n, 16, sourceFile); + case 248: + return isCompletedNode(n.block, sourceFile); + case 173: if (!n.arguments) { return true; } - case 168: case 172: - case 160: + case 176: + case 162: return nodeEndsWith(n, 18, sourceFile); - case 152: - case 153: + case 154: + case 155: return isCompletedNode(n.type, sourceFile); - case 144: - case 145: case 146: - case 213: - case 173: - case 143: - case 142: - case 148: case 147: - case 174: + case 148: + case 217: + case 177: + case 145: + case 144: + case 150: + case 149: + case 178: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -33808,62 +36645,62 @@ var ts; return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 18, sourceFile); - case 218: + case 222: return n.body && isCompletedNode(n.body, sourceFile); - case 196: + case 200: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 195: + case 199: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 23); - case 164: - case 162: - case 167: - case 136: - case 157: + case 168: + case 166: + case 171: + case 138: + case 159: return nodeEndsWith(n, 20, sourceFile); - case 149: + case 151: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 20, sourceFile); - case 241: - case 242: + case 245: + case 246: return false; - case 199: - case 200: - case 201: - case 198: + case 203: + case 204: + case 205: + case 202: return isCompletedNode(n.statement, sourceFile); - case 197: + case 201: var hasWhileKeyword = findChildOfKind(n, 104, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 18, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 154: + case 156: return isCompletedNode(n.exprName, sourceFile); - case 176: - case 175: - case 177: - case 184: - case 185: + case 180: + case 179: + case 181: + case 188: + case 189: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 170: + case 174: return isCompletedNode(n.template, sourceFile); - case 183: + case 187: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 190: + case 194: return ts.nodeIsPresent(n.literal); - case 179: + case 183: return isCompletedNode(n.operand, sourceFile); - case 181: + case 185: return isCompletedNode(n.right, sourceFile); - case 182: + case 186: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -33906,7 +36743,7 @@ var ts; ts.findChildOfKind = findChildOfKind; function findContainingList(node) { var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (c.kind === 271 && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 275 && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -33986,7 +36823,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 236) { + if (isToken(n) || n.kind === 240) { return n; } var children = n.getChildren(); @@ -33994,16 +36831,16 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 236) { + if (isToken(n) || n.kind === 240) { return n; } var children = n.getChildren(); for (var i = 0, len = children.length; i < len; i++) { var child = children[i]; - if (position < child.end && (nodeHasTokens(child) || child.kind === 236)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 240)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 236 && start === child.end); + (child.kind === 240 && start === child.end); if (lookInPreviousChild) { var candidate = findRightmostChildNodeWithTokens(children, i); return candidate && findRightmostToken(candidate); @@ -34013,7 +36850,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 248); + ts.Debug.assert(startNode !== undefined || n.kind === 252); if (children.length) { var candidate = findRightmostChildNodeWithTokens(children, children.length); return candidate && findRightmostToken(candidate); @@ -34030,7 +36867,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); - return token && token.kind === 9 && position > token.getStart(); + return token && (token.kind === 9 || token.kind === 164) && position > token.getStart(); } ts.isInString = isInString; function isInComment(sourceFile, position) { @@ -34095,17 +36932,17 @@ var ts; function getNodeModifiers(node) { var flags = ts.getCombinedNodeFlags(node); var result = []; - if (flags & 16) - result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 32) - result.push(ts.ScriptElementKindModifier.protectedMemberModifier); if (flags & 8) + result.push(ts.ScriptElementKindModifier.privateMemberModifier); + if (flags & 16) + result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + if (flags & 4) result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 64) + if (flags & 32) result.push(ts.ScriptElementKindModifier.staticModifier); if (flags & 128) result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 2) + if (flags & 1) result.push(ts.ScriptElementKindModifier.exportedModifier); if (ts.isInAmbientContext(node)) result.push(ts.ScriptElementKindModifier.ambientModifier); @@ -34113,17 +36950,17 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 151 || node.kind === 168) { + if (node.kind === 153 || node.kind === 172) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 214 || node.kind === 215) { + if (ts.isFunctionLike(node) || node.kind === 218 || node.kind === 219) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 && n.kind <= 134; + return n.kind >= 0 && n.kind <= 136; } ts.isToken = isToken; function isWord(kind) { @@ -34139,6 +36976,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 + || kind === 164 || kind === 10 || ts.isTemplateLiteralKind(kind)) { return true; @@ -34181,11 +37019,30 @@ var ts; return true; } ts.compareDataObjects = compareDataObjects; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 168 || + node.kind === 169) { + if (node.parent.kind === 185 && + node.parent.left === node && + node.parent.operatorToken.kind === 56) { + return true; + } + if (node.parent.kind === 205 && + node.parent.initializer === node) { + return true; + } + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 249 ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; })(ts || (ts = {})); var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 138; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 140; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -34366,7 +37223,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 226 || location.parent.kind === 230) && + (location.parent.kind === 230 || location.parent.kind === 234) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -34404,6 +37261,7 @@ var ts; advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, close: function () { ts.Debug.assert(scanner !== undefined); @@ -34467,10 +37325,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { + case 242: + case 239: + case 241: case 238: - case 235: - case 237: - case 234: return node.kind === 69; } } @@ -34658,7 +37516,7 @@ var ts; return false; }; return FormattingContext; - })(); + }()); formatting.FormattingContext = FormattingContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -34679,7 +37537,7 @@ var ts; "flag=" + this.Flag + "]"; }; return Rule; - })(); + }()); formatting.Rule = Rule; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -34709,7 +37567,7 @@ var ts; return new RuleDescriptor(left, right); }; return RuleDescriptor; - })(); + }()); formatting.RuleDescriptor = RuleDescriptor; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -34736,7 +37594,7 @@ var ts; return result; }; return RuleOperation; - })(); + }()); formatting.RuleOperation = RuleOperation; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -34769,7 +37627,7 @@ var ts; }; RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; - })(); + }()); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -34781,21 +37639,21 @@ var ts; function Rules() { this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1)); this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1)); - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 2)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsConditionalOperatorContext), 2)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2)); - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16, 80), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16, 104), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.FromTokens([18, 20, 24, 23])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceBeforeOpenBracket = 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(20, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); + this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); + this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); + this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2)); + this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2)); + this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2)); + this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16, 80), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16, 104), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16, formatting.Shared.TokenRange.FromTokens([18, 20, 24, 23])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8)); this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([69, 3, 73]); @@ -34804,178 +37662,179 @@ var ts; this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2), 1); this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectContext), 8)); + this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8)); this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4)); - this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35, 41), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102, 98, 92, 78, 94, 101, 119]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108, 74]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); + this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); + this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35, 35), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35, 41), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36, 36), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36, 42), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102, 98, 92, 78, 94, 101, 119]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108, 74]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2)); + this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8)); this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(87, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsVoidOpContext), 2)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), 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([100, 85]), 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123, 129]), 69), 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(121, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 127]), 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115, 73, 122, 77, 81, 82, 83, 123, 106, 89, 107, 125, 126, 110, 112, 111, 129, 113, 132]), 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([83, 106])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8)); + this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2)); + this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94, 23), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18, 79, 80, 71]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotForContext), 2)); + this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100, 85]), 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123, 130]), 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); + this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(121, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125, 128]), 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115, 73, 122, 77, 81, 82, 83, 123, 106, 89, 107, 125, 126, 110, 112, 111, 130, 113, 133]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([83, 106])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2)); - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.FromTokens([18, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.FromTokens([17, 19, 27, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectTypeContext), 8)); - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55, 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([115, 69, 82, 77, 73, 113, 112, 110, 111, 123, 129, 19, 37])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2)); + this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22, 69), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53, formatting.Shared.TokenRange.FromTokens([18, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8)); + this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18, 25), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.FromTokens([17, 19, 27, 24])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8)); + this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15, 16), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8)); + this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([115, 69, 82, 77, 73, 113, 112, 110, 111, 123, 130, 19, 37])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2)); this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(87, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8)); this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(37, formatting.Shared.TokenRange.FromTokens([69, 17])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8)); - this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114, 37]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2)); - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsSameLineTokenContext), 2)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118, 87), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.SpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69, formatting.Shared.TokenRange.FromTokens([11, 12])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.HighPriorityCommonRules = - [ - this.IgnoreBeforeComment, this.IgnoreAfterLineComment, - this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, - this.NoSpaceAfterQuestionMark, - this.NoSpaceBeforeDot, this.NoSpaceAfterDot, - this.NoSpaceAfterUnaryPrefixOperator, - this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, - this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, - this.SpaceAfterPostincrementWhenFollowedByAdd, - this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, - this.SpaceAfterPostdecrementWhenFollowedBySubtract, - this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, - 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, - this.NoSpaceBeforeOpenParenInFuncCall, - this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, - this.SpaceAfterVoidOperator, - this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, - this.SpaceBetweenTagAndTemplateString, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, - this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, - this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, - this.SpaceAfterModuleName, - this.SpaceAfterArrow, - this.NoSpaceAfterEllipsis, - this.NoSpaceAfterOptionalParameters, - this.NoSpaceBetweenEmptyInterfaceBraceBrackets, - this.NoSpaceBeforeOpenAngularBracket, - this.NoSpaceBetweenCloseParenAndAngularBracket, - this.NoSpaceAfterOpenAngularBracket, - this.NoSpaceBeforeCloseAngularBracket, - this.NoSpaceAfterCloseAngularBracket, - this.NoSpaceAfterTypeAssertion, - this.SpaceBeforeAt, - this.NoSpaceAfterAt, - this.SpaceAfterDecorator, - ]; - this.LowPriorityCommonRules = - [ - this.NoSpaceBeforeSemicolon, - this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, - this.NoSpaceBeforeComma, - this.NoSpaceBeforeOpenBracket, - this.NoSpaceAfterCloseBracket, - this.SpaceAfterSemicolon, - this.NoSpaceBeforeOpenParenInFuncDecl, - this.SpaceBetweenStatements, this.SpaceAfterTryFinally - ]; - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 8)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114, 37), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114, 37]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2)); + this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118, 87), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69, formatting.Shared.TokenRange.FromTokens([11, 12])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.HighPriorityCommonRules = [ + this.IgnoreBeforeComment, this.IgnoreAfterLineComment, + this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, + this.NoSpaceAfterQuestionMark, + this.NoSpaceBeforeDot, this.NoSpaceAfterDot, + this.NoSpaceAfterUnaryPrefixOperator, + this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, + this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, + this.SpaceAfterPostincrementWhenFollowedByAdd, + this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, + this.SpaceAfterPostdecrementWhenFollowedBySubtract, + this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, + 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, + this.NoSpaceBeforeOpenParenInFuncCall, + this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, + this.SpaceAfterVoidOperator, + this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, + this.NoSpaceBetweenTagAndTemplateString, + this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, + this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, + this.SpaceAfterModuleName, + this.SpaceBeforeArrow, this.SpaceAfterArrow, + this.NoSpaceAfterEllipsis, + this.NoSpaceAfterOptionalParameters, + this.NoSpaceBetweenEmptyInterfaceBraceBrackets, + this.NoSpaceBeforeOpenAngularBracket, + this.NoSpaceBetweenCloseParenAndAngularBracket, + this.NoSpaceAfterOpenAngularBracket, + this.NoSpaceBeforeCloseAngularBracket, + this.NoSpaceAfterCloseAngularBracket, + this.NoSpaceAfterTypeAssertion, + this.SpaceBeforeAt, + this.NoSpaceAfterAt, + this.SpaceAfterDecorator, + ]; + this.LowPriorityCommonRules = [ + this.NoSpaceBeforeSemicolon, + this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, + this.NoSpaceBeforeComma, + this.NoSpaceBeforeOpenBracket, + this.NoSpaceAfterCloseBracket, + this.SpaceAfterSemicolon, + this.NoSpaceBeforeOpenParenInFuncDecl, + this.SpaceBetweenStatements, this.SpaceAfterTryFinally + ]; + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNextTokenNotCloseBracket), 2)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2)); + this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); + this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8)); this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2)); this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8)); this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4), 1); this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4), 1); - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 2)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 8)); - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, 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, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8)); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12, 13]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13, 14])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2)); this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_32 in o) { - if (o[name_32] === rule) { - return name_32; + for (var name_33 in o) { + if (o[name_33] === rule) { + return name_33; } } throw new Error("Unknown rule"); }; Rules.IsForContext = function (context) { - return context.contextNode.kind === 199; + return context.contextNode.kind === 203; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 181: - case 182: - case 189: - case 150: - case 158: - case 159: + case 185: + case 186: + case 193: + case 152: + case 160: + case 161: return true; - case 163: - case 216: - case 221: - case 211: - case 138: - case 247: - case 141: + case 167: + case 220: + case 225: + case 215: case 140: + case 251: + case 143: + case 142: return context.currentTokenSpan.kind === 56 || context.nextTokenSpan.kind === 56; - case 200: + case 204: return context.currentTokenSpan.kind === 90 || context.nextTokenSpan.kind === 90; - case 201: - return context.currentTokenSpan.kind === 134 || context.nextTokenSpan.kind === 134; + case 205: + return context.currentTokenSpan.kind === 136 || context.nextTokenSpan.kind === 136; } return false; }; @@ -34983,7 +37842,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 182; + return context.contextNode.kind === 186; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); @@ -35008,86 +37867,86 @@ var ts; return true; } switch (node.kind) { - case 192: - case 220: - case 165: - case 219: + case 196: + case 224: + case 169: + case 223: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 213: - case 143: - case 142: + case 217: case 145: - case 146: - case 147: - case 173: case 144: - case 174: - case 215: + case 147: + case 148: + case 149: + case 177: + case 146: + case 178: + case 219: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 213 || context.contextNode.kind === 173; + return context.contextNode.kind === 217 || context.contextNode.kind === 177; }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 214: - case 186: - case 215: - case 217: - case 155: case 218: + case 190: + case 219: + case 221: + case 157: + case 222: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 214: case 218: - case 217: - case 192: - case 244: - case 219: - case 206: + case 222: + case 221: + case 196: + case 248: + case 223: + case 210: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 196: - case 206: - case 199: case 200: - case 201: - case 198: - case 209: - case 197: + case 210: + case 203: + case 204: case 205: - case 244: + case 202: + case 213: + case 201: + case 209: + case 248: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 165; + return context.contextNode.kind === 169; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 168; + return context.contextNode.kind === 172; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 169; + return context.contextNode.kind === 173; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); @@ -35095,11 +37954,14 @@ var ts; Rules.IsPreviousTokenNotComma = function (context) { return context.currentTokenSpan.kind !== 24; }; - Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 174; + Rules.IsNextTokenNotCloseBracket = function (context) { + return context.nextTokenSpan.kind !== 20; }; - Rules.IsSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine(); + Rules.IsArrowFunctionContext = function (context) { + return context.contextNode.kind === 178; + }; + Rules.IsNonJsxSameLineTokenContext = function (context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 240; }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); @@ -35114,41 +37976,41 @@ var ts; while (ts.isExpression(node)) { node = node.parent; } - return node.kind === 139; + return node.kind === 141; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 212 && + return context.currentTokenParent.kind === 216 && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { return context.formattingRequestKind !== 2; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 218; + return context.contextNode.kind === 222; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 155; + return context.contextNode.kind === 157; }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { if (token.kind !== 25 && token.kind !== 27) { return false; } switch (parent.kind) { - case 151: - case 171: - case 214: - case 186: - case 215: - case 213: + case 153: + case 175: + case 218: + case 190: + case 219: + case 217: + case 177: + case 178: + case 145: + case 144: + case 149: + case 150: + case 172: case 173: - case 174: - case 143: - case 142: - case 147: - case 148: - case 168: - case 169: - case 188: + case 192: return true; default: return false; @@ -35159,16 +38021,16 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 171; + return context.contextNode.kind === 175; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 && context.currentTokenParent.kind === 177; + return context.currentTokenSpan.kind === 103 && context.currentTokenParent.kind === 181; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 184 && context.contextNode.expression !== undefined; + return context.contextNode.kind === 188 && context.contextNode.expression !== undefined; }; return Rules; - })(); + }()); formatting.Rules = Rules; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -35187,7 +38049,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 134 + 1; + this.mapRowLength = 136 + 1; this.map = new Array(this.mapRowLength * this.mapRowLength); var rulesBucketConstructionStateList = new Array(this.map.length); this.FillRules(rules, rulesBucketConstructionStateList); @@ -35232,7 +38094,7 @@ var ts; return null; }; return RulesMap; - })(); + }()); formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; @@ -35269,7 +38131,7 @@ var ts; this.rulesInsertionIndexBitmap = temp; }; return RulesBucketConstructionState; - })(); + }()); formatting.RulesBucketConstructionState = RulesBucketConstructionState; var RulesBucket = (function () { function RulesBucket() { @@ -35304,7 +38166,7 @@ var ts; state.IncreaseInsertionIndex(position); }; return RulesBucket; - })(); + }()); formatting.RulesBucket = RulesBucket; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -35318,7 +38180,7 @@ var ts; function TokenRangeAccess(from, to, except) { this.tokens = []; for (var token = from; token <= to; token++) { - if (except.indexOf(token) < 0) { + if (ts.indexOf(except, token) < 0) { this.tokens.push(token); } } @@ -35330,7 +38192,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenRangeAccess; - })(); + }()); Shared.TokenRangeAccess = TokenRangeAccess; var TokenValuesAccess = (function () { function TokenValuesAccess(tks) { @@ -35343,7 +38205,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenValuesAccess; - })(); + }()); Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { @@ -35356,14 +38218,14 @@ var ts; return tokenValue === this.token; }; return TokenSingleValueAccess; - })(); + }()); Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { var result = []; - for (var token = 0; token <= 134; token++) { + for (var token = 0; token <= 136; token++) { result.push(token); } return result; @@ -35375,7 +38237,7 @@ var ts; return "[allTokens]"; }; return TokenAllAccess; - })(); + }()); Shared.TokenAllAccess = TokenAllAccess; var TokenRange = (function () { function TokenRange(tokenAccess) { @@ -35405,9 +38267,9 @@ var ts; }; TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3])); - TokenRange.Keywords = TokenRange.FromRange(70, 134); + TokenRange.Keywords = TokenRange.FromRange(70, 136); TokenRange.BinaryOperators = TokenRange.FromRange(25, 68); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90, 91, 134, 116, 124]); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90, 91, 136, 116, 124]); TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41, 42, 50, 49]); TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8, 69, 17, 19, 15, 97, 92]); TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); @@ -35415,9 +38277,9 @@ var ts; TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69, 17, 97, 92]); TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69, 18, 20, 92]); TokenRange.Comments = TokenRange.FromTokens([2, 3]); - TokenRange.TypeNames = TokenRange.FromTokens([69, 128, 130, 120, 131, 103, 117]); + TokenRange.TypeNames = TokenRange.FromTokens([69, 129, 131, 120, 132, 103, 117]); return TokenRange; - })(); + }()); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -35488,6 +38350,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); + } + else { + rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); + } if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } @@ -35513,7 +38383,7 @@ var ts; return rules; }; return RulesProvider; - })(); + }()); formatting.RulesProvider = RulesProvider; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -35586,17 +38456,17 @@ var ts; } function isListElement(parent, node) { switch (parent.kind) { - case 214: - case 215: - return ts.rangeContainsRange(parent.members, node); case 218: - var body = parent.body; - return body && body.kind === 192 && ts.rangeContainsRange(body.statements, node); - case 248: - case 192: case 219: + return ts.rangeContainsRange(parent.members, node); + case 222: + var body = parent.body; + return body && body.kind === 196 && ts.rangeContainsRange(body.statements, node); + case 252: + case 196: + case 223: return ts.rangeContainsRange(parent.statements, node); - case 244: + case 248: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -35660,17 +38530,17 @@ var ts; } function getOwnOrInheritedDelta(n, options, sourceFile) { var previousLine = -1; - var childKind = 0; + var child; while (n) { var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; if (previousLine !== -1 && line !== previousLine) { break; } - if (formatting.SmartIndenter.shouldIndentChildNode(n.kind, childKind)) { + if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { return options.IndentSize; } previousLine = line; - childKind = n.kind; + child = n; n = n.parent; } return 0; @@ -35698,10 +38568,18 @@ var ts; var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined); + trimTrailingWhitespacesForRemainingRange(); + } + } formattingScanner.close(); return edits; function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { - if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos)) { if (inheritedIndentation !== -1) { return inheritedIndentation; } @@ -35718,33 +38596,20 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - if (indentation === -1) { - if (isSomeBlock(node.kind)) { - if (isSomeBlock(parent.kind) || - parent.kind === 248 || - parent.kind === 241 || - parent.kind === 242) { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - else { - indentation = parentDynamicIndentation.getIndentation(); - } - } - else { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); - } - else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - } - } - var delta = formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + } + else if (indentation === -1) { + if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + indentation = parentDynamicIndentation.getIndentation(); + } + else { + indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + } } return { indentation: indentation, @@ -35756,33 +38621,33 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 214: return 73; - case 215: return 107; - case 213: return 87; - case 217: return 217; - case 145: return 123; - case 146: return 129; - case 143: + case 218: return 73; + case 219: return 107; + case 217: return 87; + case 221: return 221; + case 147: return 123; + case 148: return 130; + case 145: if (node.asteriskToken) { return 37; } - case 141: - case 138: + case 143: + case 140: return node.name.kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { return { - getIndentationForComment: function (kind, tokenIndentation) { + getIndentationForComment: function (kind, tokenIndentation, container) { switch (kind) { case 16: case 20: case 18: - return indentation + delta; + return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind) { + getIndentationForToken: function (line, kind, container) { if (nodeStartLine !== line && node.decorators) { if (kind === getFirstNonDecoratorTokenOfNode(node)) { return indentation; @@ -35800,20 +38665,20 @@ var ts; case 55: return indentation; default: - return nodeStartLine !== line ? indentation + delta : indentation; + return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; } }, getIndentation: function () { return indentation; }, - getDelta: function () { return delta; }, + getDelta: function (child) { return getEffectiveDelta(delta, child); }, recomputeIndentation: function (lineAdded) { - if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { indentation += options.IndentSize; } else { indentation -= options.IndentSize; } - if (formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0)) { + if (formatting.SmartIndenter.shouldIndentChildNode(node)) { delta = options.IndentSize; } else { @@ -35822,6 +38687,9 @@ var ts; } } }; + function getEffectiveDelta(delta, child) { + return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0; + } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { @@ -35874,10 +38742,10 @@ var ts; if (ts.isToken(child)) { var tokenInfo = formattingScanner.readTokenInfo(child); ts.Debug.assert(tokenInfo.token.end === child.end); - consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 139 ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 141 ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; @@ -35919,7 +38787,7 @@ var ts; } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -35951,10 +38819,10 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : -1; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); + var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); var indentNextTokenOrTrivia = true; for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { var triviaItem = _a[_i]; @@ -36035,9 +38903,7 @@ var ts; dynamicIndentation.recomputeIndentation(true); } } - trimTrailingWhitespaces = - (rule.Operation.Action & (4 | 2)) && - rule.Flag !== 1; + trimTrailingWhitespaces = !(rule.Operation.Action & 8) && rule.Flag !== 1; } else { trimTrailingWhitespaces = true; @@ -36113,16 +38979,29 @@ var ts; if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { continue; } - var pos = lineEndPosition; - while (pos >= lineStartPosition && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { - pos--; - } - if (pos !== lineEndPosition) { - ts.Debug.assert(pos === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))); - recordDelete(pos + 1, lineEndPosition - pos); + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); } } } + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } function newTextChange(start, len, newText) { return { span: ts.createTextSpan(start, len), newText: newText }; } @@ -36169,20 +39048,20 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 192: - case 219: + case 196: + case 223: return true; } return false; } function getOpenTokenForList(node, list) { switch (node.kind) { + case 146: + case 217: + case 177: + case 145: case 144: - case 213: - case 173: - case 143: - case 142: - case 174: + case 178: if (node.typeParameters === list) { return 25; } @@ -36190,8 +39069,8 @@ var ts; return 17; } break; - case 168: - case 169: + case 172: + case 173: if (node.typeArguments === list) { return 25; } @@ -36199,7 +39078,7 @@ var ts; return 17; } break; - case 151: + case 153: if (node.typeArguments === list) { return 25; } @@ -36227,7 +39106,7 @@ var ts; if (!options.ConvertTabsToSpaces) { var tabs = Math.floor(indentation / options.TabSize); var spaces = indentation - tabs * options.TabSize; - var tabString; + var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; } @@ -36240,7 +39119,7 @@ var ts; return spaces ? tabString + repeat(" ", spaces) : tabString; } else { - var spacesString; + var spacesString = void 0; var quotient = Math.floor(indentation / options.IndentSize); var remainder = indentation % options.IndentSize; if (!internedSpacesIndentation) { @@ -36300,7 +39179,7 @@ var ts; var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } - if (precedingToken.kind === 24 && precedingToken.parent.kind !== 181) { + if (precedingToken.kind === 24 && precedingToken.parent.kind !== 185) { var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1) { return actualIndentation; @@ -36311,7 +39190,7 @@ var ts; var currentStart; var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : 0)) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { currentStart = getStartLineAndCharacterForNode(current, sourceFile); if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) { indentationDelta = 0; @@ -36371,7 +39250,7 @@ var ts; return actualIndentation + indentationDelta; } } - if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { + if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { indentationDelta += options.IndentSize; } current = parent; @@ -36398,7 +39277,7 @@ var ts; } function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && - (parent.kind === 248 || !parentAndChildShareLine); + (parent.kind === 252 || !parentAndChildShareLine); if (!useActualIndentation) { return -1; } @@ -36422,7 +39301,7 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 196 && parent.elseStatement === child) { + if (parent.kind === 200 && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 80, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -36434,23 +39313,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 151: + case 153: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 165: + case 169: return node.parent.properties; - case 164: + case 168: return node.parent.elements; - case 213: - case 173: - case 174: - case 143: - case 142: - case 147: - case 148: { + case 217: + case 177: + case 178: + case 145: + case 144: + case 149: + case 150: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -36461,8 +39340,8 @@ var ts; } break; } - case 169: - case 168: { + case 173: + case 172: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -36490,8 +39369,8 @@ var ts; if (node.kind === 18) { return -1; } - if (node.parent && (node.parent.kind === 168 || - node.parent.kind === 169) && + if (node.parent && (node.parent.kind === 172 || + node.parent.kind === 173) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -36509,10 +39388,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 168: - case 169: - case 166: - case 167: + case 172: + case 173: + case 170: + case 171: node = node.expression; break; default: @@ -36566,79 +39445,79 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 195: - case 214: - case 186: - case 215: - case 217: - case 216: - case 164: - case 192: + case 199: + case 218: + case 190: case 219: - case 165: - case 155: - case 157: + case 221: case 220: - case 242: - case 241: - case 172: - case 166: case 168: + case 196: + case 223: case 169: - case 193: - case 211: - case 227: - case 204: - case 182: - case 162: - case 161: - case 233: - case 234: - case 142: - case 147: - case 148: - case 138: - case 152: - case 153: - case 160: + case 157: + case 159: + case 224: + case 246: + case 245: + case 176: case 170: - case 178: + case 172: + case 173: + case 197: + case 215: + case 231: + case 208: + case 186: + case 166: + case 165: + case 239: + case 238: + case 244: + case 144: + case 149: + case 150: + case 140: + case 154: + case 155: + case 162: + case 174: + case 182: + case 229: return true; } return false; } - function shouldIndentChildNode(parent, child) { - if (nodeContentIsAlwaysIndented(parent)) { - return true; - } - switch (parent) { - case 197: - case 198: - case 200: + function nodeWillIndentChild(parent, child, indentByDefault) { + var childKind = child ? child.kind : 0; + switch (parent.kind) { case 201: - case 199: - case 196: - case 213: - case 173: - case 143: - case 174: - case 144: + case 202: + case 204: + case 205: + case 203: + case 200: + case 217: + case 177: case 145: + case 178: case 146: - return child !== 192; - default: - return false; + case 147: + case 148: + return childKind !== 196; + case 237: + return childKind !== 241; } + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + function shouldIndentChildNode(parent, child) { + return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (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; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; var ts; (function (ts) { ts.servicesVersion = "0.4"; @@ -36658,7 +39537,7 @@ var ts; return undefined; }; return StringScriptSnapshot; - })(); + }()); function fromString(text) { return new StringScriptSnapshot(text); } @@ -36706,13 +39585,18 @@ var ts; ]; var jsDocCompletionEntries; function createNode(kind, pos, end, flags, parent) { - var node = new (ts.getNodeConstructor(kind))(pos, end); + var node = new NodeObject(kind, pos, end); node.flags = flags; node.parent = parent; return node; } var NodeObject = (function () { - function NodeObject() { + function NodeObject(kind, pos, end) { + this.kind = kind; + this.pos = pos; + this.end = end; + this.flags = 0; + this.parent = undefined; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -36746,13 +39630,13 @@ var ts; while (pos < end) { var token = scanner.scan(); var textPos = scanner.getTextPos(); - nodes.push(createNode(token, pos, textPos, 2048, this)); + nodes.push(createNode(token, pos, textPos, 0, this)); pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(271, nodes.pos, nodes.end, 2048, this); + var list = createNode(275, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -36771,27 +39655,27 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 135) { + if (this.kind >= 137) { scanner.setText((sourceFile || this.getSourceFile()).text); children = []; - var pos = this.pos; + var pos_3 = this.pos; var processNode = function (node) { - if (pos < node.pos) { - pos = _this.addSyntheticNodes(children, pos, node.pos); + if (pos_3 < node.pos) { + pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos); } children.push(node); - pos = node.end; + pos_3 = node.end; }; var processNodes = function (nodes) { - if (pos < nodes.pos) { - pos = _this.addSyntheticNodes(children, pos, nodes.pos); + if (pos_3 < nodes.pos) { + pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos); } children.push(_this.createSyntaxList(nodes)); - pos = nodes.end; + pos_3 = nodes.end; }; ts.forEachChild(this, processNode, processNodes); - if (pos < this.end) { - this.addSyntheticNodes(children, pos, this.end); + if (pos_3 < this.end) { + this.addSyntheticNodes(children, pos_3, this.end); } scanner.setText(undefined); } @@ -36818,7 +39702,7 @@ var ts; return undefined; } var child = children[0]; - return child.kind < 135 ? child : child.getFirstToken(sourceFile); + return child.kind < 137 ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { var children = this.getChildren(sourceFile); @@ -36826,10 +39710,10 @@ var ts; if (!child) { return undefined; } - return child.kind < 135 ? child : child.getLastToken(sourceFile); + return child.kind < 137 ? child : child.getLastToken(sourceFile); }; return NodeObject; - })(); + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -36851,7 +39735,7 @@ var ts; return this.documentationComment; }; return SymbolObject; - })(); + }()); function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { var documentationComment = []; var docComments = getJsDocCommentsSeparatedByNewLines(); @@ -36867,23 +39751,23 @@ var ts; var jsDocCommentParts = []; ts.forEach(declarations, function (declaration, indexOfDeclaration) { if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { - var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); - if (canUseParsedParamTagComments && declaration.kind === 138) { - ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { - var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + var sourceFileOfDeclaration_1 = ts.getSourceFileOfNode(declaration); + if (canUseParsedParamTagComments && declaration.kind === 140) { + ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration_1), function (jsDocCommentTextRange) { + var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration_1); if (cleanedParamJsDocComment) { ts.addRange(jsDocCommentParts, cleanedParamJsDocComment); } }); } - if (declaration.kind === 218 && declaration.body.kind === 218) { + if (declaration.kind === 222 && declaration.body.kind === 222) { return; } - while (declaration.kind === 218 && declaration.parent.kind === 218) { + while (declaration.kind === 222 && declaration.parent.kind === 222) { declaration = declaration.parent; } - ts.forEach(getJsDocCommentTextRange(declaration.kind === 211 ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { - var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + ts.forEach(getJsDocCommentTextRange(declaration.kind === 215 ? declaration.parent.parent : declaration, sourceFileOfDeclaration_1), function (jsDocCommentTextRange) { + var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration_1); if (cleanedJsDocComment) { ts.addRange(jsDocCommentParts, cleanedJsDocComment); } @@ -36927,7 +39811,8 @@ var ts; return isName(pos, end, sourceFile, paramTag); } function pushDocCommentLineText(docComments, text, blankLineCount) { - while (blankLineCount--) { + while (blankLineCount) { + blankLineCount--; docComments.push(ts.textPart("")); } docComments.push(ts.textPart(text)); @@ -37124,7 +40009,7 @@ var ts; : undefined; }; return TypeObject; - })(); + }()); var SignatureObject = (function () { function SignatureObject(checker) { this.checker = checker; @@ -37148,11 +40033,11 @@ var ts; return this.documentationComment; }; return SignatureObject; - })(); + }()); var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); - function SourceFileObject() { - _super.apply(this, arguments); + function SourceFileObject(kind, pos, end) { + _super.call(this, kind, pos, end); } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -37192,9 +40077,9 @@ var ts; if (result_2 !== undefined) { return result_2; } - if (declaration.name.kind === 136) { + if (declaration.name.kind === 138) { var expr = declaration.name.expression; - if (expr.kind === 166) { + if (expr.kind === 170) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -37214,9 +40099,9 @@ var ts; } function visit(node) { switch (node.kind) { - case 213: - case 143: - case 142: + case 217: + case 145: + case 144: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -37233,62 +40118,62 @@ var ts; ts.forEachChild(node, visit); } break; - case 214: - case 215: - case 216: - case 217: case 218: - case 221: - case 230: - case 226: - case 221: - case 223: - case 224: - case 145: - case 146: - case 155: - addDeclaration(node); - case 144: - case 193: - case 212: - case 161: - case 162: case 219: + case 220: + case 221: + case 222: + case 225: + case 234: + case 230: + case 225: + case 227: + case 228: + case 147: + case 148: + case 157: + addDeclaration(node); + case 146: + case 197: + case 216: + case 165: + case 166: + case 223: ts.forEachChild(node, visit); break; - case 192: + case 196: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } break; - case 138: - if (!(node.flags & 56)) { + case 140: + if (!(node.flags & 28)) { break; } - case 211: - case 163: + case 215: + case 167: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } - case 247: - case 141: - case 140: + case 251: + case 143: + case 142: addDeclaration(node); break; - case 228: + case 232: if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 222: + case 226: var importClause = node.importClause; if (importClause) { if (importClause.name) { addDeclaration(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224) { + if (importClause.namedBindings.kind === 228) { addDeclaration(importClause.namedBindings); } else { @@ -37301,12 +40186,12 @@ var ts; } }; return SourceFileObject; - })(NodeObject); + }(NodeObject)); var TextChange = (function () { function TextChange() { } return TextChange; - })(); + }()); ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { @@ -37421,8 +40306,14 @@ var ts; ClassificationTypeNames.typeAliasName = "type alias name"; ClassificationTypeNames.parameterName = "parameter name"; ClassificationTypeNames.docCommentTagName = "doc comment tag name"; + ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; + ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; + ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; + ClassificationTypeNames.jsxAttribute = "jsx attribute"; + ClassificationTypeNames.jsxText = "jsx text"; + ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; return ClassificationTypeNames; - })(); + }()); ts.ClassificationTypeNames = ClassificationTypeNames; function displayPartsToString(displayParts) { if (displayParts) { @@ -37436,14 +40327,14 @@ var ts; return false; } return ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 173) { + if (declaration.kind === 177) { return true; } - if (declaration.kind !== 211 && declaration.kind !== 213) { + if (declaration.kind !== 215 && declaration.kind !== 217) { return false; } - for (var parent_8 = declaration.parent; !ts.isFunctionBlock(parent_8); parent_8 = parent_8.parent) { - if (parent_8.kind === 248 || parent_8.kind === 219) { + for (var parent_10 = declaration.parent; !ts.isFunctionBlock(parent_10); parent_10 = parent_10.parent) { + if (parent_10.kind === 252 || parent_10.kind === 223) { return false; } } @@ -37453,7 +40344,6 @@ var ts; function getDefaultCompilerOptions() { return { target: 1, - module: 0, jsx: 1 }; } @@ -37476,12 +40366,14 @@ var ts; }; HostCache.prototype.createEntry = function (fileName, path) { var entry; + var scriptKind = this.host.getScriptKind ? this.host.getScriptKind(fileName) : 0; var scriptSnapshot = this.host.getScriptSnapshot(fileName); if (scriptSnapshot) { entry = { hostFileName: fileName, version: this.host.getScriptVersion(fileName), - scriptSnapshot: scriptSnapshot + scriptSnapshot: scriptSnapshot, + scriptKind: scriptKind ? scriptKind : ts.getScriptKindFromFileName(fileName) }; } this.fileNameToEntry.set(path, entry); @@ -37518,7 +40410,7 @@ var ts; return file && file.scriptSnapshot; }; return HostCache; - })(); + }()); var SyntaxTreeCache = (function () { function SyntaxTreeCache(host) { this.host = host; @@ -37528,10 +40420,11 @@ var ts; if (!scriptSnapshot) { throw new Error("Could not find file: '" + fileName + "'."); } + var scriptKind = this.host.getScriptKind ? this.host.getScriptKind(fileName) : 0; var version = this.host.getScriptVersion(fileName); var sourceFile; if (this.currentFileName !== fileName) { - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2, version, true); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2, version, true, scriptKind); } else if (this.currentFileVersion !== version) { var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); @@ -37546,7 +40439,7 @@ var ts; return this.currentSourceFile; }; return SyntaxTreeCache; - })(); + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; @@ -37554,6 +40447,7 @@ var ts; function transpileModule(input, transpileOptions) { var options = transpileOptions.compilerOptions ? ts.clone(transpileOptions.compilerOptions) : getDefaultCompilerOptions(); options.isolatedModules = true; + options.suppressOutputPathCheck = true; options.allowNonTsExtensions = true; options.noLib = true; options.noResolve = true; @@ -37574,7 +40468,7 @@ var ts; sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); outputText = text; } }, @@ -37584,7 +40478,8 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; } + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; } }; var program = ts.createProgram([inputFileName], options, compilerHost); var diagnostics; @@ -37604,11 +40499,10 @@ var ts; return output.outputText; } ts.transpile = transpile; - function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents) { + function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents); + var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); - sourceFile.nameTable = sourceFile.identifiers; return sourceFile; } ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; @@ -37617,7 +40511,7 @@ var ts; if (textChangeRange) { if (version !== sourceFile.version) { if (!ts.disableIncrementalParsing) { - var newText; + var newText = void 0; var prefix = textChangeRange.span.start !== 0 ? sourceFile.text.substr(0, textChangeRange.span.start) : ""; @@ -37648,21 +40542,15 @@ var ts; } } } - return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true); + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, true, sourceFile.scriptKind); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createGetCanonicalFileName(useCaseSensitivefileNames) { - return useCaseSensitivefileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); - } - ts.createGetCanonicalFileName = createGetCanonicalFileName; function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { if (currentDirectory === void 0) { currentDirectory = ""; } var buckets = {}; - var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx; + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + +"|" + settings.allowJs; } function getBucketForCompilationSettings(settings, createIfMissing) { var key = getKeyFromCompilationSettings(settings); @@ -37673,7 +40561,7 @@ var ts; return bucket; } function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = ts.lookUp(buckets, name); var sourceFiles = []; entries.forEachValue(function (key, entry) { @@ -37689,21 +40577,21 @@ var ts; sourceFiles: sourceFiles }; }); - return JSON.stringify(bucketInfoArray, null, 2); + return JSON.stringify(bucketInfoArray, undefined, 2); } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, true); + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, true, scriptKind); } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, false); + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, false, scriptKind); } - function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { + function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(compilationSettings, true); var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = bucket.get(path); 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); + var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false, scriptKind); entry = { sourceFile: sourceFile, languageServiceRefCount: 0, @@ -37740,8 +40628,9 @@ var ts; }; } ts.createDocumentRegistry = createDocumentRegistry; - function preProcessFile(sourceText, readImportFiles) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } var referencedFiles = []; var importedFiles = []; var ambientExternalModules; @@ -37775,98 +40664,58 @@ var ts; end: pos + importPath.length }); } - function processImport() { - scanner.setText(sourceText); - var token = scanner.scan(); - while (token !== 1) { - if (token === 122) { - token = scanner.scan(); - if (token === 125) { - token = scanner.scan(); - if (token === 9) { - recordAmbientExternalModule(); - continue; - } - } - } - else if (token === 89) { + function tryConsumeDeclare() { + var token = scanner.getToken(); + if (token === 122) { + token = scanner.scan(); + if (token === 125) { token = scanner.scan(); if (token === 9) { - recordModuleName(); - continue; - } - else { - if (token === 69 || ts.isKeyword(token)) { - token = scanner.scan(); - if (token === 133) { - token = scanner.scan(); - if (token === 9) { - recordModuleName(); - continue; - } - } - else if (token === 56) { - token = scanner.scan(); - if (token === 127) { - token = scanner.scan(); - if (token === 17) { - token = scanner.scan(); - if (token === 9) { - recordModuleName(); - continue; - } - } - } - } - else if (token === 24) { - token = scanner.scan(); - } - else { - continue; - } - } - if (token === 15) { - token = scanner.scan(); - while (token !== 16) { - token = scanner.scan(); - } - if (token === 16) { - token = scanner.scan(); - if (token === 133) { - token = scanner.scan(); - if (token === 9) { - recordModuleName(); - } - } - } - } - else if (token === 37) { - token = scanner.scan(); - if (token === 116) { - token = scanner.scan(); - if (token === 69 || ts.isKeyword(token)) { - token = scanner.scan(); - if (token === 133) { - token = scanner.scan(); - if (token === 9) { - recordModuleName(); - } - } - } - } - } + recordAmbientExternalModule(); } } - else if (token === 82) { - token = scanner.scan(); + return true; + } + return false; + } + function tryConsumeImport() { + var token = scanner.getToken(); + if (token === 89) { + token = scanner.scan(); + if (token === 9) { + recordModuleName(); + return true; + } + else { + if (token === 69 || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 134) { + token = scanner.scan(); + if (token === 9) { + recordModuleName(); + return true; + } + } + else if (token === 56) { + if (tryConsumeRequireCall(true)) { + return true; + } + } + else if (token === 24) { + token = scanner.scan(); + } + else { + return true; + } + } if (token === 15) { token = scanner.scan(); - while (token !== 16) { + while (token !== 16 && token !== 1) { token = scanner.scan(); } if (token === 16) { token = scanner.scan(); - if (token === 133) { + if (token === 134) { token = scanner.scan(); if (token === 9) { recordModuleName(); @@ -37876,38 +40725,135 @@ var ts; } else if (token === 37) { token = scanner.scan(); - if (token === 133) { + if (token === 116) { token = scanner.scan(); - if (token === 9) { - recordModuleName(); - } - } - } - else if (token === 89) { - token = scanner.scan(); - if (token === 69 || ts.isKeyword(token)) { - token = scanner.scan(); - if (token === 56) { + if (token === 69 || ts.isKeyword(token)) { token = scanner.scan(); - if (token === 127) { + if (token === 134) { token = scanner.scan(); - if (token === 17) { - token = scanner.scan(); - if (token === 9) { - recordModuleName(); - } + if (token === 9) { + recordModuleName(); } } } } } } + return true; + } + return false; + } + function tryConsumeExport() { + var token = scanner.getToken(); + if (token === 82) { token = scanner.scan(); + if (token === 15) { + token = scanner.scan(); + while (token !== 16 && token !== 1) { + token = scanner.scan(); + } + if (token === 16) { + token = scanner.scan(); + if (token === 134) { + token = scanner.scan(); + if (token === 9) { + recordModuleName(); + } + } + } + } + else if (token === 37) { + token = scanner.scan(); + if (token === 134) { + token = scanner.scan(); + if (token === 9) { + recordModuleName(); + } + } + } + else if (token === 89) { + token = scanner.scan(); + if (token === 69 || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 56) { + if (tryConsumeRequireCall(true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? scanner.scan() : scanner.getToken(); + if (token === 128) { + token = scanner.scan(); + if (token === 17) { + token = scanner.scan(); + if (token === 9) { + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = scanner.getToken(); + if (token === 69 && scanner.getTokenValue() === "define") { + token = scanner.scan(); + if (token !== 17) { + return true; + } + token = scanner.scan(); + if (token === 9) { + token = scanner.scan(); + if (token === 24) { + token = scanner.scan(); + } + else { + return true; + } + } + if (token !== 19) { + return true; + } + token = scanner.scan(); + var i = 0; + while (token !== 20 && token !== 1) { + if (token === 9) { + recordModuleName(); + i++; + } + token = scanner.scan(); + } + return true; + } + return false; + } + function processImports() { + scanner.setText(sourceText); + scanner.scan(); + while (true) { + if (scanner.getToken() === 1) { + break; + } + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(false) || tryConsumeDefine()))) { + continue; + } + else { + scanner.scan(); + } } scanner.setText(undefined); } if (readImportFiles) { - processImport(); + processImports(); } processTripleSlashDirectives(); return { referencedFiles: referencedFiles, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientExternalModules }; @@ -37915,7 +40861,7 @@ var ts; ts.preProcessFile = preProcessFile; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 207 && referenceNode.label.text === labelName) { + if (referenceNode.kind === 211 && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -37924,16 +40870,16 @@ var ts; } function isJumpStatementTarget(node) { return node.kind === 69 && - (node.parent.kind === 203 || node.parent.kind === 202) && + (node.parent.kind === 207 || node.parent.kind === 206) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { return node.kind === 69 && - node.parent.kind === 207 && + node.parent.kind === 211 && node.parent.label === node; } function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 207; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 211; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -37944,25 +40890,25 @@ var ts; return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } function isRightSideOfQualifiedName(node) { - return node.parent.kind === 135 && node.parent.right === node; + return node.parent.kind === 137 && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 166 && node.parent.name === node; + return node && node.parent && node.parent.kind === 170 && node.parent.name === node; } function isCallExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 168 && node.parent.expression === node; + return node && node.parent && node.parent.kind === 172 && node.parent.expression === node; } function isNewExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 169 && node.parent.expression === node; + return node && node.parent && node.parent.kind === 173 && node.parent.expression === node; } function isNameOfModuleDeclaration(node) { - return node.parent.kind === 218 && node.parent.name === node; + return node.parent.kind === 222 && node.parent.name === node; } function isNameOfFunctionDeclaration(node) { return node.kind === 69 && @@ -37970,22 +40916,22 @@ var ts; } function isNameOfPropertyAssignment(node) { return (node.kind === 69 || node.kind === 9 || node.kind === 8) && - (node.parent.kind === 245 || node.parent.kind === 246) && node.parent.name === node; + (node.parent.kind === 249 || node.parent.kind === 250) && node.parent.name === node; } function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 9 || node.kind === 8) { switch (node.parent.kind) { - case 141: - case 140: - case 245: - case 247: case 143: case 142: + case 249: + case 251: case 145: - case 146: - case 218: + case 144: + case 147: + case 148: + case 222: return node.parent.name === node; - case 167: + case 171: return node.parent.argumentExpression === node; } } @@ -38023,7 +40969,7 @@ var ts; } } var keywordCompletions = []; - for (var i = 70; i <= 134; i++) { + for (var i = 70; i <= 136; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ScriptElementKind.keyword, @@ -38038,17 +40984,17 @@ var ts; return undefined; } switch (node.kind) { - case 248: - case 143: - case 142: - case 213: - case 173: + case 252: case 145: - case 146: - case 214: - case 215: + case 144: case 217: + case 177: + case 147: + case 148: case 218: + case 219: + case 221: + case 222: return node; } } @@ -38056,38 +41002,38 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 218: return ScriptElementKind.moduleElement; - case 214: return ScriptElementKind.classElement; - case 215: return ScriptElementKind.interfaceElement; - case 216: return ScriptElementKind.typeElement; - case 217: return ScriptElementKind.enumElement; - case 211: + case 222: return ScriptElementKind.moduleElement; + case 218: return ScriptElementKind.classElement; + case 219: return ScriptElementKind.interfaceElement; + case 220: return ScriptElementKind.typeElement; + case 221: return ScriptElementKind.enumElement; + case 215: return ts.isConst(node) ? ScriptElementKind.constElement : ts.isLet(node) ? ScriptElementKind.letElement : ScriptElementKind.variableElement; - case 213: return ScriptElementKind.functionElement; - case 145: return ScriptElementKind.memberGetAccessorElement; - case 146: return ScriptElementKind.memberSetAccessorElement; + case 217: return ScriptElementKind.functionElement; + case 147: return ScriptElementKind.memberGetAccessorElement; + case 148: return ScriptElementKind.memberSetAccessorElement; + case 145: + case 144: + return ScriptElementKind.memberFunctionElement; case 143: case 142: - return ScriptElementKind.memberFunctionElement; - case 141: - case 140: return ScriptElementKind.memberVariableElement; - case 149: return ScriptElementKind.indexSignatureElement; - case 148: return ScriptElementKind.constructSignatureElement; - case 147: return ScriptElementKind.callSignatureElement; - case 144: return ScriptElementKind.constructorImplementationElement; - case 137: return ScriptElementKind.typeParameterElement; - case 247: return ScriptElementKind.variableElement; - case 138: return (node.flags & 56) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 221: - case 226: - case 223: + case 151: return ScriptElementKind.indexSignatureElement; + case 150: return ScriptElementKind.constructSignatureElement; + case 149: return ScriptElementKind.callSignatureElement; + case 146: return ScriptElementKind.constructorImplementationElement; + case 139: return ScriptElementKind.typeParameterElement; + case 251: return ScriptElementKind.variableElement; + case 140: return (node.flags & 28) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case 225: case 230: - case 224: + case 227: + case 234: + case 228: return ScriptElementKind.alias; } return ScriptElementKind.unknown; @@ -38106,7 +41052,7 @@ var ts; } }; return CancellationTokenObject; - })(); + }()); function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -38124,7 +41070,7 @@ var ts; host.log(message); } } - var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -38159,7 +41105,8 @@ var ts; (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx); + oldSettings.jsx !== newSettings.jsx || + oldSettings.allowJs !== newSettings.allowJs); var compilerHost = { getSourceFile: getOrCreateSourceFile, getCancellationToken: function () { return cancellationToken; }, @@ -38176,8 +41123,15 @@ var ts; readFile: function (fileName) { var entry = hostCache.getOrCreateEntry(fileName); return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + }, + directoryExists: function (directoryName) { + ts.Debug.assert(!host.resolveModuleNames); + return ts.directoryProbablyExists(directoryName, host); } }; + if (host.trace) { + compilerHost.trace = function (message) { return host.trace(message); }; + } if (host.resolveModuleNames) { compilerHost.resolveModuleNames = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } @@ -38204,14 +41158,18 @@ var ts; if (!changesInCompilationSettingsAffectSyntax) { var oldSourceFile = program && program.getSourceFile(fileName); if (oldSourceFile) { - return documentRegistry.updateDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); + ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + fileName); + return documentRegistry.updateDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } } - return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); + return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } function sourceFileUpToDate(sourceFile) { + if (!sourceFile) { + return false; + } var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); - return sourceFile && sourceFile.version === hostCache.getVersion(path); + return sourceFile.version === hostCache.getVersion(path); } function programUpToDate() { if (!program) { @@ -38250,9 +41208,6 @@ var ts; function getSemanticDiagnostics(fileName) { synchronizeHostData(); var targetSourceFile = getValidSourceFile(fileName); - if (ts.isJavaScript(fileName)) { - return getJavaScriptSemanticDiagnostics(targetSourceFile); - } var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); if (!program.getCompilerOptions().declaration) { return semanticDiagnostics; @@ -38260,150 +41215,6 @@ var ts; var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return ts.concatenate(semanticDiagnostics, declarationDiagnostics); } - function getJavaScriptSemanticDiagnostics(sourceFile) { - var diagnostics = []; - walk(sourceFile); - return diagnostics; - function walk(node) { - if (!node) { - return false; - } - switch (node.kind) { - case 221: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 227: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; - case 214: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 243: - var heritageClause = node; - if (heritageClause.token === 106) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 215: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 218: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 216: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 143: - case 142: - case 144: - case 145: - case 146: - case 173: - case 213: - case 174: - case 213: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; - } - break; - case 193: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 211: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 168: - case 169: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 138: - var parameter = node; - if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return true; - } - if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, '?')); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 141: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 217: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 171: - 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 139: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112: - case 110: - case 111: - case 122: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - case 113: - case 82: - case 74: - case 77: - case 115: - } - } - } - return false; - } - } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); @@ -38427,22 +41238,16 @@ var ts; return undefined; } if (performCharacterChecks) { - if (!ts.isIdentifierStart(name.charCodeAt(0), target)) { + if (!ts.isIdentifier(name, target)) { return undefined; } - for (var i = 1, n = name.length; i < n; i++) { - if (!ts.isIdentifierPart(name.charCodeAt(i), target)) { - return undefined; - } - } } return name; } function getCompletionData(fileName, position) { var typeChecker = program.getTypeChecker(); - var syntacticStart = new Date().getTime(); var sourceFile = getValidSourceFile(fileName); - var isJavaScriptFile = ts.isJavaScript(fileName); + var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; var start = new Date().getTime(); var currentToken = ts.getTokenAtPosition(sourceFile, position); @@ -38461,9 +41266,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { - case 269: - case 267: - case 268: + case 273: + case 271: + case 272: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -38484,9 +41289,9 @@ var ts; log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); var contextToken = previousToken; if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_3 = new Date().getTime(); + var start_6 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_3)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); } var node = currentToken; var isRightOfDot = false; @@ -38498,13 +41303,13 @@ var ts; log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent_9 = contextToken.parent, kind = contextToken.kind; + var parent_11 = contextToken.parent, kind = contextToken.kind; if (kind === 21) { - if (parent_9.kind === 166) { + if (parent_11.kind === 170) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent_9.kind === 135) { + else if (parent_11.kind === 137) { node = contextToken.parent.left; isRightOfDot = true; } @@ -38517,8 +41322,9 @@ var ts; isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 && contextToken.parent.kind === 237) { + else if (kind === 39 && contextToken.parent.kind === 241) { isStartingCloseTag = true; + location = contextToken; } } } @@ -38542,7 +41348,10 @@ var ts; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; - symbols = [typeChecker.getSymbolAtLocation(tagName)]; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (!typeChecker.isUnknownSymbol(tagSymbol)) { + symbols = [tagSymbol]; + } isMemberCompletion = true; isNewIdentifierLocation = false; } @@ -38556,7 +41365,7 @@ var ts; function getTypeScriptMemberSymbols() { isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 || node.kind === 135 || node.kind === 166) { + if (node.kind === 69 || node.kind === 137 || node.kind === 170) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol && symbol.flags & 8388608) { symbol = typeChecker.getAliasedSymbol(symbol); @@ -38601,8 +41410,8 @@ var ts; return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { - var attrsType; - if ((jsxContainer.kind === 234) || (jsxContainer.kind === 235)) { + var attrsType = void 0; + if ((jsxContainer.kind === 238) || (jsxContainer.kind === 239)) { attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); @@ -38642,15 +41451,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 236) { + if (contextToken.kind === 240) { return true; } if (contextToken.kind === 27 && contextToken.parent) { - if (contextToken.parent.kind === 235) { + if (contextToken.parent.kind === 239) { return true; } - if (contextToken.parent.kind === 237 || contextToken.parent.kind === 234) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 233; + if (contextToken.parent.kind === 241 || contextToken.parent.kind === 238) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 237; } } return false; @@ -38660,40 +41469,40 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 24: - return containingNodeKind === 168 - || containingNodeKind === 144 - || containingNodeKind === 169 - || containingNodeKind === 164 - || containingNodeKind === 181 - || containingNodeKind === 152; + return containingNodeKind === 172 + || containingNodeKind === 146 + || containingNodeKind === 173 + || containingNodeKind === 168 + || containingNodeKind === 185 + || containingNodeKind === 154; case 17: - return containingNodeKind === 168 - || containingNodeKind === 144 - || containingNodeKind === 169 - || containingNodeKind === 172 - || containingNodeKind === 160; + return containingNodeKind === 172 + || containingNodeKind === 146 + || containingNodeKind === 173 + || containingNodeKind === 176 + || containingNodeKind === 162; case 19: - return containingNodeKind === 164 - || containingNodeKind === 149 - || containingNodeKind === 136; + return containingNodeKind === 168 + || containingNodeKind === 151 + || containingNodeKind === 138; case 125: case 126: return true; case 21: - return containingNodeKind === 218; + return containingNodeKind === 222; case 15: - return containingNodeKind === 214; + return containingNodeKind === 218; case 56: - return containingNodeKind === 211 - || containingNodeKind === 181; + return containingNodeKind === 215 + || containingNodeKind === 185; case 12: - return containingNodeKind === 183; + return containingNodeKind === 187; case 13: - return containingNodeKind === 190; + return containingNodeKind === 194; case 112: case 110: case 111: - return containingNodeKind === 141; + return containingNodeKind === 143; } switch (previousToken.getText()) { case "public": @@ -38706,11 +41515,12 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 + || contextToken.kind === 164 || contextToken.kind === 10 || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_4 = contextToken.getStart(); + var start_7 = contextToken.getStart(); var end = contextToken.getEnd(); - if (start_4 < position && position < end) { + if (start_7 < position && position < end) { return true; } if (position === end) { @@ -38724,12 +41534,12 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 165) { + if (objectLikeContainer.kind === 169) { isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 161) { + else if (objectLikeContainer.kind === 165) { isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (ts.isVariableLike(rootDeclaration)) { @@ -38755,9 +41565,9 @@ var ts; return true; } function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 225 ? - 222 : - 228; + var declarationKind = namedImportsOrExports.kind === 229 ? + 226 : + 232; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -38778,9 +41588,9 @@ var ts; switch (contextToken.kind) { case 15: case 24: - var parent_10 = contextToken.parent; - if (parent_10 && (parent_10.kind === 165 || parent_10.kind === 161)) { - return parent_10; + var parent_12 = contextToken.parent; + if (parent_12 && (parent_12.kind === 169 || parent_12.kind === 165)) { + return parent_12; } break; } @@ -38793,8 +41603,8 @@ var ts; case 15: case 24: switch (contextToken.parent.kind) { - case 225: case 229: + case 233: return contextToken.parent; } } @@ -38803,34 +41613,34 @@ var ts; } function tryGetContainingJsxElement(contextToken) { if (contextToken) { - var parent_11 = contextToken.parent; + var parent_13 = contextToken.parent; switch (contextToken.kind) { case 26: case 39: case 69: - case 238: - case 239: - if (parent_11 && (parent_11.kind === 234 || parent_11.kind === 235)) { - return parent_11; + case 242: + case 243: + if (parent_13 && (parent_13.kind === 238 || parent_13.kind === 239)) { + return parent_13; } - else if (parent_11.kind === 238) { - return parent_11.parent; + else if (parent_13.kind === 242) { + return parent_13.parent; } break; case 9: - if (parent_11 && ((parent_11.kind === 238) || (parent_11.kind === 239))) { - return parent_11.parent; + if (parent_13 && ((parent_13.kind === 242) || (parent_13.kind === 243))) { + return parent_13.parent; } break; case 16: - if (parent_11 && - parent_11.kind === 240 && - parent_11.parent && - (parent_11.parent.kind === 238)) { - return parent_11.parent.parent; + if (parent_13 && + parent_13.kind === 244 && + parent_13.parent && + (parent_13.parent.kind === 242)) { + return parent_13.parent.parent; } - if (parent_11 && parent_11.kind === 239) { - return parent_11.parent; + if (parent_13 && parent_13.kind === 243) { + return parent_13.parent; } break; } @@ -38839,16 +41649,16 @@ var ts; } function isFunction(kind) { switch (kind) { - case 173: - case 174: - case 213: - case 143: - case 142: + case 177: + case 178: + case 217: case 145: - case 146: + case 144: case 147: case 148: case 149: + case 150: + case 151: return true; } return false; @@ -38857,66 +41667,66 @@ var ts; var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 24: - return containingNodeKind === 211 || - containingNodeKind === 212 || - containingNodeKind === 193 || - containingNodeKind === 217 || + return containingNodeKind === 215 || + containingNodeKind === 216 || + containingNodeKind === 197 || + containingNodeKind === 221 || isFunction(containingNodeKind) || - containingNodeKind === 214 || - containingNodeKind === 186 || - containingNodeKind === 215 || - containingNodeKind === 162 || - containingNodeKind === 216; + containingNodeKind === 218 || + containingNodeKind === 190 || + containingNodeKind === 219 || + containingNodeKind === 166 || + containingNodeKind === 220; case 21: - return containingNodeKind === 162; + return containingNodeKind === 166; case 54: - return containingNodeKind === 163; + return containingNodeKind === 167; case 19: - return containingNodeKind === 162; + return containingNodeKind === 166; case 17: - return containingNodeKind === 244 || + return containingNodeKind === 248 || isFunction(containingNodeKind); case 15: - return containingNodeKind === 217 || - containingNodeKind === 215 || - containingNodeKind === 155; + return containingNodeKind === 221 || + containingNodeKind === 219 || + containingNodeKind === 157; case 23: - return containingNodeKind === 140 && + return containingNodeKind === 142 && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 215 || - contextToken.parent.parent.kind === 155); + (contextToken.parent.parent.kind === 219 || + contextToken.parent.parent.kind === 157); case 25: - return containingNodeKind === 214 || - containingNodeKind === 186 || - containingNodeKind === 215 || - containingNodeKind === 216 || + return containingNodeKind === 218 || + containingNodeKind === 190 || + containingNodeKind === 219 || + containingNodeKind === 220 || isFunction(containingNodeKind); case 113: - return containingNodeKind === 141; + return containingNodeKind === 143; case 22: - return containingNodeKind === 138 || + return containingNodeKind === 140 || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 162); + contextToken.parent.parent.kind === 166); case 112: case 110: case 111: - return containingNodeKind === 138; + return containingNodeKind === 140; case 116: - return containingNodeKind === 226 || - containingNodeKind === 230 || - containingNodeKind === 224; + return containingNodeKind === 230 || + containingNodeKind === 234 || + containingNodeKind === 228; case 73: case 81: case 107: case 87: case 102: case 123: - case 129: + case 130: case 89: case 108: case 74: case 114: - case 132: + case 133: return true; } switch (contextToken.getText()) { @@ -38947,19 +41757,19 @@ var ts; return false; } function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var exisingImportsOrExports = {}; + var existingImportsOrExports = {}; for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_33 = element.propertyName || element.name; - exisingImportsOrExports[name_33.text] = true; + var name_34 = element.propertyName || element.name; + existingImportsOrExports[name_34.text] = true; } - if (ts.isEmpty(exisingImportsOrExports)) { + if (ts.isEmpty(existingImportsOrExports)) { return exportsOfModule; } - return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(exisingImportsOrExports, e.name); }); + return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(existingImportsOrExports, e.name); }); } function filterObjectMembersList(contextualMemberSymbols, existingMembers) { if (!existingMembers || existingMembers.length === 0) { @@ -38968,17 +41778,20 @@ var ts; var existingMemberNames = {}; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; - if (m.kind !== 245 && - m.kind !== 246 && - m.kind !== 163) { + if (m.kind !== 249 && + m.kind !== 250 && + m.kind !== 167 && + m.kind !== 145) { continue; } if (m.getStart() <= position && position <= m.getEnd()) { continue; } var existingName = void 0; - if (m.kind === 163 && m.propertyName) { - existingName = m.propertyName.text; + if (m.kind === 167 && m.propertyName) { + if (m.propertyName.kind === 69) { + existingName = m.propertyName.text; + } } else { existingName = m.name.text; @@ -38994,7 +41807,7 @@ var ts; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } - if (attr.kind === 238) { + if (attr.kind === 242) { seenNames[attr.name.text] = true; } } @@ -39007,45 +41820,57 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isRightOfDot = completionData.isRightOfDot, isJsDocTagName = completionData.isJsDocTagName; - var entries; + var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() }; } - if (isRightOfDot && ts.isJavaScript(fileName)) { - entries = getCompletionEntriesFromSymbols(symbols); - ts.addRange(entries, getJavaScriptCompletionEntries()); + var sourceFile = getValidSourceFile(fileName); + var entries = []; + if (ts.isSourceFileJavaScript(sourceFile)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries); + ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { if (!symbols || symbols.length === 0) { - return undefined; + if (sourceFile.languageVariant === 1 && + location.parent && location.parent.kind === 241) { + var tagName = location.parent.parent.openingElement.tagName; + entries.push({ + name: tagName.text, + kind: undefined, + kindModifiers: undefined, + sortText: "0" + }); + } + else { + return undefined; + } } - entries = getCompletionEntriesFromSymbols(symbols); + getCompletionEntriesFromSymbols(symbols, entries); } if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - function getJavaScriptCompletionEntries() { + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; - var allNames = {}; var target = program.getCompilerOptions().target; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - var nameTable = getNameTable(sourceFile); - for (var name_34 in nameTable) { - if (!allNames[name_34]) { - allNames[name_34] = name_34; - var displayName = getCompletionEntryDisplayName(name_34, target, true); - if (displayName) { - var entry = { - name: displayName, - kind: ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } + var nameTable = getNameTable(sourceFile); + for (var name_35 in nameTable) { + if (nameTable[name_35] === position) { + continue; + } + if (!uniqueNames[name_35]) { + uniqueNames[name_35] = name_35; + var displayName = getCompletionEntryDisplayName(name_35, target, true); + if (displayName) { + var entry = { + name: displayName, + kind: ScriptElementKind.warning, + kindModifiers: "", + sortText: "1" + }; + entries.push(entry); } } } @@ -39073,25 +41898,24 @@ var ts; sortText: "0" }; } - function getCompletionEntriesFromSymbols(symbols) { + function getCompletionEntriesFromSymbols(symbols, entries) { var start = new Date().getTime(); - var entries = []; + var uniqueNames = {}; if (symbols) { - var nameToSymbol = {}; - for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { - var symbol = symbols_3[_i]; + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; var entry = createCompletionEntry(symbol, location); if (entry) { var id = ts.escapeIdentifier(entry.name); - if (!ts.lookUp(nameToSymbol, id)) { + if (!ts.lookUp(uniqueNames, id)) { entries.push(entry); - nameToSymbol[id] = symbol; + uniqueNames[id] = id; } } } } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); - return entries; + return uniqueNames; } } function getCompletionEntryDetails(fileName, position, entryName) { @@ -39099,8 +41923,8 @@ var ts; var completionData = getCompletionData(fileName, position); if (completionData) { var symbols = completionData.symbols, location_2 = completionData.location; - var target = program.getCompilerOptions().target; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target, false, location_2) === entryName ? s : undefined; }); + var target_2 = program.getCompilerOptions().target; + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target_2, false, location_2) === entryName ? s : undefined; }); if (symbol) { var _a = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location_2, location_2, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; return { @@ -39127,7 +41951,7 @@ var ts; function getSymbolKind(symbol, location) { var flags = symbol.getFlags(); if (flags & 32) - return ts.getDeclarationOfKind(symbol, 186) ? + return ts.getDeclarationOfKind(symbol, 190) ? ScriptElementKind.localClassElement : ScriptElementKind.classElement; if (flags & 384) return ScriptElementKind.enumElement; @@ -39220,17 +42044,17 @@ var ts; if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { symbolKind = ScriptElementKind.memberVariableElement; } - var signature; + var signature = void 0; type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 166) { + if (location.parent && location.parent.kind === 170) { var right = location.parent.name; if (right === location || (right && right.getFullWidth() === 0)) { location = location.parent; } } - var callExpression; - if (location.kind === 168 || location.kind === 169) { + var callExpression = void 0; + if (location.kind === 172 || location.kind === 173) { callExpression = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -39242,7 +42066,7 @@ var ts; if (!signature && candidateSignatures.length) { signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 169 || callExpression.expression.kind === 95; + var useConstructSignatures = callExpression.kind === 173 || callExpression.expression.kind === 95; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { signature = allSignatures.length ? allSignatures[0] : undefined; @@ -39290,21 +42114,21 @@ var ts; } } else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || - (location.kind === 121 && location.parent.kind === 144)) { + (location.kind === 121 && location.parent.kind === 146)) { var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 144 ? type.getConstructSignatures() : type.getCallSignatures(); + var allSignatures = functionDeclaration.kind === 146 ? type.getConstructSignatures() : type.getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 144) { + if (functionDeclaration.kind === 146) { symbolKind = ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 147 && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 149 && !(type.symbol.flags & 2048 || type.symbol.flags & 4096) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -39313,7 +42137,7 @@ var ts; } } if (symbolFlags & 32 && !hasAddedSymbolInfo) { - if (ts.getDeclarationOfKind(symbol, 186)) { + if (ts.getDeclarationOfKind(symbol, 190)) { pushTypePart(ScriptElementKind.localClassElement); } else { @@ -39332,7 +42156,7 @@ var ts; } if (symbolFlags & 524288) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(132)); + displayParts.push(ts.keywordPart(133)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); @@ -39353,7 +42177,7 @@ var ts; } if (symbolFlags & 1536) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 218); + var declaration = ts.getDeclarationOfKind(symbol, 222); var isNamespace = declaration && declaration.name && declaration.name.kind === 69; displayParts.push(ts.keywordPart(isNamespace ? 126 : 125)); displayParts.push(ts.spacePart()); @@ -39374,32 +42198,34 @@ var ts; writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { - var container = ts.getContainingFunction(location); - if (container) { - var signatureDeclaration = ts.getDeclarationOfKind(symbol, 137).parent; - var signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration); - if (signatureDeclaration.kind === 148) { - displayParts.push(ts.keywordPart(92)); + var declaration = ts.getDeclarationOfKind(symbol, 139); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 150) { + displayParts.push(ts.keywordPart(92)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 149 && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); + } + else { + displayParts.push(ts.keywordPart(133)); displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } - else if (signatureDeclaration.kind !== 147 && signatureDeclaration.name) { - addFullSymbolName(signatureDeclaration.symbol); - } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); - } - else { - var declaration = ts.getDeclarationOfKind(symbol, 137).parent; - displayParts.push(ts.keywordPart(132)); - displayParts.push(ts.spacePart()); - addFullSymbolName(declaration.symbol); - writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } } } if (symbolFlags & 8) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 247) { + if (declaration.kind === 251) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -39415,13 +42241,13 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 221) { + if (declaration.kind === 225) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(127)); + displayParts.push(ts.keywordPart(128)); displayParts.push(ts.punctuationPart(17)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); displayParts.push(ts.punctuationPart(18)); @@ -39542,12 +42368,13 @@ var ts; } var typeChecker = program.getTypeChecker(); var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { + if (!symbol || typeChecker.isUnknownSymbol(symbol)) { switch (node.kind) { case 69: - case 166: - case 135: + case 170: + case 137: case 97: + case 163: case 95: var type = typeChecker.getTypeAtLocation(node); if (type) { @@ -39620,8 +42447,8 @@ var ts; var declarations = []; var definition; ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 144) || - (!selectConstructors && (d.kind === 213 || d.kind === 143 || d.kind === 142))) { + if ((selectConstructors && d.kind === 146) || + (!selectConstructors && (d.kind === 217 || d.kind === 145 || d.kind === 144))) { declarations.push(d); if (d.body) definition = d; @@ -39672,20 +42499,22 @@ var ts; } if (symbol.flags & 8388608) { var declaration = symbol.declarations[0]; - if (node.kind === 69 && node.parent === declaration) { + if (node.kind === 69 && + (node.parent === declaration || + (declaration.kind === 230 && declaration.parent && declaration.parent.kind === 229))) { symbol = typeChecker.getAliasedSymbol(symbol); } } - if (node.parent.kind === 246) { + if (node.parent.kind === 250) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; } var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind = getSymbolKind(shorthandSymbol, node); - var shorthandSymbolName = typeChecker.symbolToString(shorthandSymbol); - var shorthandContainerName = typeChecker.symbolToString(symbol.parent, node); - return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName); }); + var shorthandSymbolKind_1 = getSymbolKind(shorthandSymbol, node); + var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); + var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); + return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } return getDefinitionFromSymbol(symbol, node); } @@ -39706,13 +42535,13 @@ var ts; return undefined; } if (type.flags & 16384) { - var result = []; + var result_3 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(result, getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(result_3, getDefinitionFromSymbol(t.symbol, node)); } }); - return result; + return result_3; } if (!type.symbol) { return undefined; @@ -39722,8 +42551,8 @@ var ts; function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile = getCanonicalFileName(ts.normalizeSlashes(fileName)); - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile; }); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -39749,6 +42578,7 @@ var ts; function getSemanticDocumentHighlights(node) { if (node.kind === 69 || node.kind === 97 || + node.kind === 163 || node.kind === 95 || isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) { @@ -39800,75 +42630,75 @@ var ts; switch (node.kind) { case 88: case 80: - if (hasKind(node.parent, 196)) { + if (hasKind(node.parent, 200)) { return getIfElseOccurrences(node.parent); } break; case 94: - if (hasKind(node.parent, 204)) { + if (hasKind(node.parent, 208)) { return getReturnOccurrences(node.parent); } break; case 98: - if (hasKind(node.parent, 208)) { + if (hasKind(node.parent, 212)) { return getThrowOccurrences(node.parent); } break; case 72: - if (hasKind(parent(parent(node)), 209)) { + if (hasKind(parent(parent(node)), 213)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; case 100: case 85: - if (hasKind(parent(node), 209)) { + if (hasKind(parent(node), 213)) { return getTryCatchFinallyOccurrences(node.parent); } break; case 96: - if (hasKind(node.parent, 206)) { + if (hasKind(node.parent, 210)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 71: case 77: - if (hasKind(parent(parent(parent(node))), 206)) { + if (hasKind(parent(parent(parent(node))), 210)) { return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); } break; case 70: case 75: - if (hasKind(node.parent, 203) || hasKind(node.parent, 202)) { + if (hasKind(node.parent, 207) || hasKind(node.parent, 206)) { return getBreakOrContinueStatementOccurrences(node.parent); } break; case 86: - if (hasKind(node.parent, 199) || - hasKind(node.parent, 200) || - hasKind(node.parent, 201)) { + if (hasKind(node.parent, 203) || + hasKind(node.parent, 204) || + hasKind(node.parent, 205)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 104: case 79: - if (hasKind(node.parent, 198) || hasKind(node.parent, 197)) { + if (hasKind(node.parent, 202) || hasKind(node.parent, 201)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 121: - if (hasKind(node.parent, 144)) { + if (hasKind(node.parent, 146)) { return getConstructorOccurrences(node.parent); } break; case 123: - case 129: - if (hasKind(node.parent, 145) || hasKind(node.parent, 146)) { + case 130: + if (hasKind(node.parent, 147) || hasKind(node.parent, 148)) { return getGetAndSetOccurrences(node.parent); } break; default: - if (ts.isModifier(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 193)) { + if (ts.isModifierKind(node.kind) && node.parent && + (ts.isDeclaration(node.parent) || node.parent.kind === 197)) { return getModifierOccurrences(node.kind, node.parent); } } @@ -39880,10 +42710,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 208) { + if (node.kind === 212) { statementAccumulator.push(node); } - else if (node.kind === 209) { + else if (node.kind === 213) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -39903,17 +42733,17 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_12 = child.parent; - if (ts.isFunctionBlock(parent_12) || parent_12.kind === 248) { - return parent_12; + var parent_14 = child.parent; + if (ts.isFunctionBlock(parent_14) || parent_14.kind === 252) { + return parent_14; } - if (parent_12.kind === 209) { - var tryStatement = parent_12; + if (parent_14.kind === 213) { + var tryStatement = parent_14; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_12; + child = parent_14; } return undefined; } @@ -39922,7 +42752,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 203 || node.kind === 202) { + if (node.kind === 207 || node.kind === 206) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -39937,15 +42767,15 @@ var ts; function getBreakOrContinueOwner(statement) { for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { switch (node_2.kind) { - case 206: - if (statement.kind === 202) { + case 210: + if (statement.kind === 206) { continue; } - case 199: - case 200: + case 203: + case 204: + case 205: + case 202: case 201: - case 198: - case 197: if (!statement.label || isLabeledBy(node_2, statement.label.text)) { return node_2; } @@ -39962,24 +42792,24 @@ var ts; function getModifierOccurrences(modifier, declaration) { var container = declaration.parent; if (ts.isAccessibilityModifier(modifier)) { - if (!(container.kind === 214 || - container.kind === 186 || - (declaration.kind === 138 && hasKind(container, 144)))) { + if (!(container.kind === 218 || + container.kind === 190 || + (declaration.kind === 140 && hasKind(container, 146)))) { return undefined; } } else if (modifier === 113) { - if (!(container.kind === 214 || container.kind === 186)) { + if (!(container.kind === 218 || container.kind === 190)) { return undefined; } } else if (modifier === 82 || modifier === 122) { - if (!(container.kind === 219 || container.kind === 248)) { + if (!(container.kind === 223 || container.kind === 252)) { return undefined; } } else if (modifier === 115) { - if (!(container.kind === 214 || declaration.kind === 214)) { + if (!(container.kind === 218 || declaration.kind === 218)) { return undefined; } } @@ -39990,8 +42820,8 @@ var ts; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { - case 219: - case 248: + case 223: + case 252: if (modifierFlag & 128) { nodes = declaration.members.concat(declaration); } @@ -39999,15 +42829,15 @@ var ts; nodes = container.statements; } break; - case 144: + case 146: nodes = container.parameters.concat(container.parent.members); break; - case 214: - case 186: + case 218: + case 190: nodes = container.members; - if (modifierFlag & 56) { + if (modifierFlag & 28) { var constructor = ts.forEach(container.members, function (member) { - return member.kind === 144 && member; + return member.kind === 146 && member; }); if (constructor) { nodes = nodes.concat(constructor.parameters); @@ -40029,17 +42859,17 @@ var ts; function getFlagFromModifier(modifier) { switch (modifier) { case 112: - return 8; - case 110: - return 16; - case 111: - return 32; - case 113: - return 64; - case 82: - return 2; - case 122: return 4; + case 110: + return 8; + case 111: + return 16; + case 113: + return 32; + case 82: + return 1; + case 122: + return 2; case 115: return 128; default: @@ -40060,13 +42890,13 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 145); - tryPushAccessorKeyword(accessorDeclaration.symbol, 146); + tryPushAccessorKeyword(accessorDeclaration.symbol, 147); + tryPushAccessorKeyword(accessorDeclaration.symbol, 148); 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, 123, 129); }); + ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 123, 130); }); } } } @@ -40083,7 +42913,7 @@ var ts; function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86, 104, 79)) { - if (loopNode.kind === 197) { + if (loopNode.kind === 201) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 104)) { @@ -40104,13 +42934,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 199: - case 200: + case 203: + case 204: + case 205: case 201: - case 197: - case 198: + case 202: return getLoopBreakContinueOccurrences(owner); - case 206: + case 210: return getSwitchCaseDefaultOccurrences(owner); } } @@ -40160,7 +42990,7 @@ var ts; } function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); - if (!(func && hasKind(func.body, 192))) { + if (!(func && hasKind(func.body, 196))) { return undefined; } var keywords = []; @@ -40174,7 +43004,7 @@ var ts; } function getIfElseOccurrences(ifStatement) { var keywords = []; - while (hasKind(ifStatement.parent, 196) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 200) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } while (ifStatement) { @@ -40185,7 +43015,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 196)) { + if (!hasKind(ifStatement.elseStatement, 200)) { break; } ifStatement = ifStatement.elseStatement; @@ -40289,7 +43119,7 @@ var ts; return getLabelReferencesInNode(node.parent, node); } } - if (node.kind === 97) { + if (node.kind === 97 || node.kind === 163) { return getReferencesForThisKeyword(node, sourceFiles); } if (node.kind === 95) { @@ -40314,11 +43144,11 @@ var ts; } else { var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName)) { + if (ts.lookUp(nameTable, internedName) !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -40341,10 +43171,8 @@ var ts; textSpan: ts.createTextSpan(declarations[0].getStart(), 0) }; } - function isImportOrExportSpecifierImportSymbol(symbol) { - return (symbol.flags & 8388608) && ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 226 || declaration.kind === 230; - }); + function isImportSpecifierSymbol(symbol) { + return (symbol.flags & 8388608) && !!ts.getDeclarationOfKind(symbol, 230); } function getInternedName(symbol, location, declarations) { if (ts.isImportOrExportSpecifierName(location)) { @@ -40356,13 +43184,13 @@ var ts; } function getSymbolScope(symbol) { var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 173 || valueDeclaration.kind === 186)) { + if (valueDeclaration && (valueDeclaration.kind === 177 || valueDeclaration.kind === 190)) { return valueDeclaration; } if (symbol.flags & (4 | 8192)) { - var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16) ? d : undefined; }); + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 214); + return ts.getAncestor(privateDeclaration, 218); } } if (symbol.flags & 8388608) { @@ -40371,11 +43199,11 @@ var ts; if (symbol.parent || (symbol.flags & 268435456)) { return undefined; } - var scope = undefined; + var scope; var declarations = symbol.getDeclarations(); if (declarations) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; @@ -40383,7 +43211,7 @@ var ts; if (scope && scope !== container) { return undefined; } - if (container.kind === 248 && !ts.isExternalModule(container)) { + if (container.kind === 252 && !ts.isExternalModule(container)) { return undefined; } scope = container; @@ -40464,7 +43292,7 @@ var ts; var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= 0) { + else if (!(referenceSymbol.flags & 67108864) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); } @@ -40528,15 +43356,15 @@ var ts; if (!searchSpaceNode) { return undefined; } - var staticFlag = 64; + var staticFlag = 32; switch (searchSpaceNode.kind) { - case 141: - case 140: case 143: case 142: - case 144: case 145: + case 144: case 146: + case 147: + case 148: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; break; @@ -40553,7 +43381,7 @@ var ts; return; } var container = ts.getSuperContainer(node, false); - if (container && (64 & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + if (container && (32 & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { references.push(getReferenceEntryFromNode(node)); } }); @@ -40562,34 +43390,34 @@ var ts; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); - var staticFlag = 64; + var staticFlag = 32; switch (searchSpaceNode.kind) { - case 143: - case 142: + case 145: + case 144: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } - case 141: - case 140: - case 144: - case 145: + case 143: + case 142: case 146: + case 147: + case 148: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; break; - case 248: + case 252: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } - case 213: - case 173: + case 217: + case 177: break; default: return undefined; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 248) { + if (searchSpaceNode.kind === 252) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -40615,31 +43443,31 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 97) { + if (!node || (node.kind !== 97 && node.kind !== 163)) { return; } var container = ts.getThisContainer(node, false); switch (searchSpaceNode.kind) { - case 173: - case 213: + case 177: + case 217: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 143: - case 142: + case 145: + case 144: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 186: - case 214: - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64) === staticFlag) { + case 190: + case 218: + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 32) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 248: - if (container.kind === 248 && !ts.isExternalModule(container)) { + case 252: + if (container.kind === 252 && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -40649,9 +43477,12 @@ var ts; } function populateSearchSymbolSet(symbol, location) { var result = [symbol]; - if (isImportOrExportSpecifierImportSymbol(symbol)) { + if (isImportSpecifierSymbol(symbol)) { result.push(typeChecker.getAliasedSymbol(symbol)); } + if (location.parent.kind === 234) { + result.push(typeChecker.getExportSpecifierLocalTargetSymbol(location.parent)); + } if (isNameOfPropertyAssignment(location)) { ts.forEach(getPropertySymbolsFromContextualType(location), function (contextualSymbol) { ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); @@ -40661,24 +43492,34 @@ var ts; result.push(shorthandValueSymbol); } } + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 140 && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { if (rootSymbol !== symbol) { result.push(rootSymbol); } if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, {}); } }); return result; } - function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { - if (symbol && symbol.flags & (32 | 64)) { + function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { + if (!symbol) { + return; + } + if (ts.hasProperty(previousIterationSymbolsCache, symbol.name)) { + return; + } + if (symbol.flags & (32 | 64)) { ts.forEach(symbol.getDeclarations(), function (declaration) { - if (declaration.kind === 214) { + if (declaration.kind === 218) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 215) { + else if (declaration.kind === 219) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -40692,7 +43533,8 @@ var ts; if (propertySymbol) { result.push(propertySymbol); } - getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result); + previousIterationSymbolsCache[symbol.name] = symbol; + getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); } } } @@ -40701,12 +43543,18 @@ var ts; if (searchSymbols.indexOf(referenceSymbol) >= 0) { return referenceSymbol; } - if (isImportOrExportSpecifierImportSymbol(referenceSymbol)) { + if (isImportSpecifierSymbol(referenceSymbol)) { var aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol); if (searchSymbols.indexOf(aliasedSymbol) >= 0) { return aliasedSymbol; } } + if (referenceLocation.parent.kind === 234) { + var aliasedSymbol = typeChecker.getExportSpecifierLocalTargetSymbol(referenceLocation.parent); + if (searchSymbols.indexOf(aliasedSymbol) >= 0) { + return aliasedSymbol; + } + } if (isNameOfPropertyAssignment(referenceLocation)) { return ts.forEach(getPropertySymbolsFromContextualType(referenceLocation), function (contextualSymbol) { return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); @@ -40717,9 +43565,9 @@ var ts; return rootSymbol; } if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - var result_3 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3); - return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, {}); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -40728,26 +43576,26 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_35 = node.text; + var name_36 = node.text; if (contextualType) { if (contextualType.flags & 16384) { - var unionProperty = contextualType.getProperty(name_35); + var unionProperty = contextualType.getProperty(name_36); if (unionProperty) { return [unionProperty]; } else { - var result_4 = []; + var result_5 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_35); + var symbol = t.getProperty(name_36); if (symbol) { - result_4.push(symbol); + result_5.push(symbol); } }); - return result_4; + return result_5; } } else { - var symbol_1 = contextualType.getProperty(name_35); + var symbol_1 = contextualType.getProperty(name_36); if (symbol_1) { return [symbol_1]; } @@ -40758,11 +43606,11 @@ var ts; } function getIntersectingMeaningFromDeclarations(meaning, declarations) { if (declarations) { - var lastIterationMeaning; + var lastIterationMeaning = void 0; do { lastIterationMeaning = meaning; - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var declarationMeaning = getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -40792,10 +43640,10 @@ var ts; } var parent = node.parent; if (parent) { - if (parent.kind === 180 || parent.kind === 179) { + if (parent.kind === 184 || parent.kind === 183) { return true; } - else if (parent.kind === 181 && parent.left === node) { + else if (parent.kind === 185 && parent.left === node) { var operator = parent.operatorToken.kind; return 56 <= operator && operator <= 68; } @@ -40806,9 +43654,6 @@ var ts; synchronizeHostData(); return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); } - function containErrors(diagnostics) { - return ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); - } function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -40828,34 +43673,34 @@ var ts; } function getMeaningFromDeclaration(node) { switch (node.kind) { - case 138: - case 211: - case 163: - case 141: case 140: - case 245: - case 246: - case 247: + case 215: + case 167: case 143: case 142: - case 144: + case 249: + case 250: + case 251: case 145: + case 144: case 146: - case 213: - case 173: - case 174: - case 244: - return 1; - case 137: - case 215: - case 216: - case 155: - return 2; - case 214: + case 147: + case 148: case 217: - return 1 | 2; + case 177: + case 178: + case 248: + return 1; + case 139: + case 219: + case 220: + case 157: + return 2; case 218: - if (node.name.kind === 9) { + case 221: + return 1 | 2; + case 222: + if (ts.isAmbientModule(node)) { return 4 | 1; } else if (ts.getModuleInstanceState(node) === 1) { @@ -40864,14 +43709,14 @@ var ts; else { return 4; } + case 229: + case 230: case 225: case 226: - case 221: - case 222: - case 227: - case 228: + case 231: + case 232: return 1 | 2 | 4; - case 248: + case 252: return 4 | 1; } return 1 | 2 | 4; @@ -40880,9 +43725,10 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 151 || - (node.parent.kind === 188 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - node.kind === 97 && !ts.isExpression(node); + return node.parent.kind === 153 || + (node.parent.kind === 192 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 && !ts.isExpression(node)) || + node.kind === 163; } function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); @@ -40890,47 +43736,47 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 166) { - while (root.parent && root.parent.kind === 166) { + if (root.parent.kind === 170) { + while (root.parent && root.parent.kind === 170) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 188 && root.parent.parent.kind === 243) { + if (!isLastClause && root.parent.kind === 192 && root.parent.parent.kind === 247) { var decl = root.parent.parent.parent; - return (decl.kind === 214 && root.parent.parent.token === 106) || - (decl.kind === 215 && root.parent.parent.token === 83); + return (decl.kind === 218 && root.parent.parent.token === 106) || + (decl.kind === 219 && root.parent.parent.token === 83); } return false; } function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 135) { - while (root.parent && root.parent.kind === 135) { + if (root.parent.kind === 137) { + while (root.parent && root.parent.kind === 137) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 151 && !isLastClause; + return root.parent.kind === 153 && !isLastClause; } function isInRightSideOfImport(node) { - while (node.parent.kind === 135) { + while (node.parent.kind === 137) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } function getMeaningFromRightHandSideOfImportEquals(node) { ts.Debug.assert(node.kind === 69); - if (node.parent.kind === 135 && + if (node.parent.kind === 137 && node.parent.right === node && - node.parent.parent.kind === 221) { + node.parent.parent.kind === 225) { return 1 | 2 | 4; } return 4; } function getMeaningFromLocation(node) { - if (node.parent.kind === 227) { + if (node.parent.kind === 231) { return 1 | 2 | 4; } else if (isInRightSideOfImport(node)) { @@ -40964,14 +43810,16 @@ var ts; return; } switch (node.kind) { - case 166: - case 135: + case 170: + case 137: case 9: + case 164: case 84: case 99: case 93: case 95: case 97: + case 163: case 69: break; default: @@ -40983,7 +43831,7 @@ var ts; nodeForStartPos = nodeForStartPos.parent; } else if (isNameOfModuleDeclaration(nodeForStartPos)) { - if (nodeForStartPos.parent.parent.kind === 218 && + if (nodeForStartPos.parent.parent.kind === 222 && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { nodeForStartPos = nodeForStartPos.parent.parent.name; } @@ -41003,17 +43851,17 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); } function checkForClassificationCancellation(kind) { switch (kind) { + case 222: case 218: - case 214: - case 215: - case 213: + case 219: + case 217: cancellationToken.throwIfCancellationRequested(); } } @@ -41061,7 +43909,7 @@ var ts; return undefined; function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 218 && + return declaration.kind === 222 && ts.getModuleInstanceState(declaration) === 1; }); } @@ -41105,6 +43953,12 @@ var ts; case 16: return ClassificationTypeNames.typeAliasName; case 17: return ClassificationTypeNames.parameterName; case 18: return ClassificationTypeNames.docCommentTagName; + case 19: return ClassificationTypeNames.jsxOpenTagName; + case 20: return ClassificationTypeNames.jsxCloseTagName; + case 21: return ClassificationTypeNames.jsxSelfClosingTagName; + case 22: return ClassificationTypeNames.jsxAttribute; + case 23: return ClassificationTypeNames.jsxText; + case 24: return ClassificationTypeNames.jsxAttributeStringLiteralValue; } } function convertClassifications(classifications) { @@ -41194,16 +44048,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); pos = tag.tagName.end; switch (tag.kind) { - case 267: + case 271: processJSDocParameterTag(tag); break; - case 270: + case 274: processJSDocTemplateTag(tag); break; - case 269: + case 273: processElement(tag.typeExpression); break; - case 268: + case 272: processElement(tag.typeExpression); break; } @@ -41238,7 +44092,8 @@ var ts; } } function classifyDisabledMergeCode(text, start, end) { - for (var i = start; i < end; i++) { + var i; + for (i = start; i < end; i++) { if (ts.isLineBreak(text.charCodeAt(i))) { break; } @@ -41258,19 +44113,49 @@ var ts; pushClassification(start, end - start, type); } } - function classifyToken(token) { - if (ts.nodeIsMissing(token)) { - return; + function tryClassifyNode(node) { + if (ts.nodeIsMissing(node)) { + return true; } - var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); - var tokenWidth = token.end - tokenStart; + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 240 && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 240 ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { - var type = classifyTokenType(token.kind, token); + var type = classifiedElementName || classifyTokenType(node.kind, node); if (type) { pushClassification(tokenStart, tokenWidth, type); } } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 239: + if (token.parent.tagName === token) { + return 19; + } + break; + case 241: + if (token.parent.tagName === token) { + return 20; + } + break; + case 238: + if (token.parent.tagName === token) { + return 21; + } + break; + case 242: + if (token.parent.name === token) { + return 22; + } + break; + } + return undefined; } function classifyTokenType(tokenKind, token) { if (ts.isKeyword(tokenKind)) { @@ -41284,16 +44169,17 @@ var ts; if (ts.isPunctuation(tokenKind)) { if (token) { if (tokenKind === 56) { - if (token.parent.kind === 211 || - token.parent.kind === 141 || - token.parent.kind === 138) { + if (token.parent.kind === 215 || + token.parent.kind === 143 || + token.parent.kind === 140 || + token.parent.kind === 242) { return 5; } } - if (token.parent.kind === 181 || - token.parent.kind === 179 || - token.parent.kind === 180 || - token.parent.kind === 182) { + if (token.parent.kind === 185 || + token.parent.kind === 183 || + token.parent.kind === 184 || + token.parent.kind === 186) { return 5; } } @@ -41302,8 +44188,8 @@ var ts; else if (tokenKind === 8) { return 4; } - else if (tokenKind === 9) { - return 6; + else if (tokenKind === 9 || tokenKind === 164) { + return token.parent.kind === 242 ? 24 : 6; } else if (tokenKind === 10) { return 6; @@ -41311,35 +44197,38 @@ var ts; else if (ts.isTemplateLiteralKind(tokenKind)) { return 6; } + else if (tokenKind === 240) { + return 23; + } else if (tokenKind === 69) { if (token) { switch (token.parent.kind) { - case 214: + case 218: if (token.parent.name === token) { return 11; } return; - case 137: + case 139: if (token.parent.name === token) { return 15; } return; - case 215: + case 219: if (token.parent.name === token) { return 13; } return; - case 217: + case 221: if (token.parent.name === token) { return 12; } return; - case 218: + case 222: if (token.parent.name === token) { return 14; } return; - case 138: + case 140: if (token.parent.name === token) { return 17; } @@ -41358,10 +44247,7 @@ var ts; 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); - } - else { + if (!tryClassifyNode(child)) { processElement(child); } } @@ -41443,7 +44329,6 @@ var ts; return []; } function getDocCommentTemplateAtPosition(fileName, position) { - var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; @@ -41456,16 +44341,16 @@ var ts; var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 213: - case 143: - case 144: - case 214: - case 193: - break findOwner; - case 248: - return undefined; + case 217: + case 145: + case 146: case 218: - if (commentOwner.parent.kind === 218) { + case 197: + break findOwner; + case 252: + return undefined; + case 222: + if (commentOwner.parent.kind === 222) { return undefined; } break findOwner; @@ -41478,7 +44363,7 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); - var newLine = host.getNewLine ? host.getNewLine() : "\r\n"; + var newLine = ts.getNewLineOrDefaultFromHost(host); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; @@ -41499,7 +44384,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 193) { + if (commentOwner.kind === 197) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -41509,17 +44394,17 @@ var ts; return emptyArray; } function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 172) { + while (rightHandSide.kind === 176) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 173: - case 174: + case 177: + case 178: return rightHandSide.parameters; - case 186: + case 190: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 144) { + if (member.kind === 146) { return member.parameters; } } @@ -41535,7 +44420,7 @@ var ts; var result = []; if (descriptors.length > 0) { var regExp = getTodoCommentsRegExp(); - var matchArray; + var matchArray = void 0; while (matchArray = regExp.exec(fileContents)) { cancellationToken.throwIfCancellationRequested(); var firstDescriptorCaptureIndex = 3; @@ -41571,8 +44456,8 @@ var ts; function getTodoCommentsRegExp() { var singleLineCommentStart = /(?:\/\/+\s*)/.source; var multiLineCommentStart = /(?:\/\*+\s*)/.source; - var anyNumberOfSpacesAndAsterixesAtStartOfLine = /(?:^(?:\s|\*)*)/.source; - var preamble = "(" + anyNumberOfSpacesAndAsterixesAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")"; var endOfLineOrEndOfComment = /(?:$|\*\/)/.source; var messageRemainder = /(?:.*?)/.source; @@ -41597,12 +44482,16 @@ var ts; var declarations = symbol.getDeclarations(); if (declarations && declarations.length > 0) { var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); if (defaultLibFileName) { - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var current = declarations_10[_i]; - var sourceFile_2 = current.getSourceFile(); - var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); - if (sourceFile_2 && getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var current = declarations_11[_i]; + var sourceFile_3 = current.getSourceFile(); + if (!sourceFile_3) { + continue; + } + var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_3.fileName)); + if (canonicalName === canonicalDefaultLibName) { return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); } } @@ -41612,10 +44501,10 @@ var ts; if (kind) { return { canRename: true, - localizedErrorMessage: undefined, - displayName: displayName, - fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kind: kind, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kindModifiers: getSymbolModifiers(symbol), triggerSpan: ts.createTextSpan(node.getStart(), node.getWidth()) }; @@ -41690,14 +44579,14 @@ var ts; function walk(node) { switch (node.kind) { case 69: - nameTable[node.text] = node.text; + nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; break; case 9: case 8: if (ts.isDeclarationName(node) || - node.parent.kind === 232 || + node.parent.kind === 236 || isArgumentOfElementAccessExpression(node)) { - nameTable[node.text] = node.text; + nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; } break; default: @@ -41708,7 +44597,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 167 && + node.parent.kind === 171 && node.parent.argumentExpression === node; } function createClassifier() { @@ -41730,7 +44619,7 @@ var ts; function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 123 || - keyword2 === 129 || + keyword2 === 130 || keyword2 === 121 || keyword2 === 113) { return true; @@ -41796,7 +44685,7 @@ var ts; } switch (lexState) { case 3: - text = '"\\\n' + text; + text = "\"\\\n" + text; offset = 3; break; case 2: @@ -41846,10 +44735,10 @@ var ts; angleBracketStack--; } else if (token === 117 || - token === 130 || - token === 128 || + token === 131 || + token === 129 || token === 120 || - token === 131) { + token === 132) { if (angleBracketStack > 0 && !syntacticClassifierAbsent) { token = 69; } @@ -41890,7 +44779,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9) { + if (token === 9 || token === 164) { var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { var lastCharIndex = tokenText.length - 1; @@ -42004,7 +44893,7 @@ var ts; } } function isKeyword(token) { - return token >= 70 && token <= 134; + return token >= 70 && token <= 136; } function classFromKind(token) { if (isKeyword(token)) { @@ -42020,6 +44909,7 @@ var ts; case 8: return 4; case 9: + case 164: return 6; case 10: return 7; @@ -42053,18 +44943,8 @@ var ts; ts.getDefaultLibFilePath = getDefaultLibFilePath; function initializeServices() { ts.objectAllocator = { - getNodeConstructor: function (kind) { - function Node(pos, end) { - this.pos = pos; - this.end = end; - this.flags = 0; - this.parent = undefined; - } - var proto = kind === 248 ? new SourceFileObject() : new NodeObject(); - proto.kind = kind; - Node.prototype = proto; - return Node; - }, + getNodeConstructor: function () { return NodeObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, getSignatureConstructor: function () { return SignatureObject; } @@ -42186,9 +45066,6 @@ var ts; this.byteLength = byteLength; this.hrtime = hrtime; this.logger = logger; - this.pendingOperation = false; - this.fileHash = {}; - this.nextFileId = 1; this.changeSeq = 0; this.handlers = (_a = {}, _a[CommandNames.Exit] = function () { @@ -42213,7 +45090,7 @@ var ts; }, _a[CommandNames.Open] = function (request) { var openArgs = request.arguments; - _this.openClientFile(openArgs.file); + _this.openClientFile(openArgs.file, openArgs.fileContent); return { responseRequired: false }; }, _a[CommandNames.Quickinfo] = function (request) { @@ -42393,10 +45270,6 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.errorCheck = function (file, project) { - this.syntacticCheck(file, project); - this.semanticCheck(file, project); - }; Session.prototype.reloadProjects = function () { this.projectService.reloadProjects(); }; @@ -42427,11 +45300,12 @@ var ts; var index = 0; var checkOne = function () { if (matchSeq(seq)) { - var checkSpec = checkList[index++]; - if (checkSpec.project.getSourceFileFromName(checkSpec.fileName, requireOpen)) { - _this.syntacticCheck(checkSpec.fileName, checkSpec.project); + var checkSpec_1 = checkList[index]; + index++; + if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) { + _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); _this.immediateId = setImmediate(function () { - _this.semanticCheck(checkSpec.fileName, checkSpec.project); + _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); _this.immediateId = undefined; if (checkList.length > index) { _this.errorTimer = setTimeout(checkOne, followMs); @@ -42646,9 +45520,9 @@ var ts; symbolDisplayString: displayString }; }; - Session.prototype.openClientFile = function (fileName) { + Session.prototype.openClientFile = function (fileName, fileContent) { var file = ts.normalizePath(fileName); - this.projectService.openClientFile(file); + this.projectService.openClientFile(file, fileContent); }; Session.prototype.getQuickInfo = function (line, offset, fileName) { var file = ts.normalizePath(fileName); @@ -42720,7 +45594,7 @@ var ts; }; var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); var hasIndent = 0; - var i, len; + var i = void 0, len = void 0; for (i = 0, len = lineText.length; i < len; i++) { if (lineText.charAt(i) == " ") { hasIndent++; @@ -42959,8 +45833,8 @@ var ts; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var _a = this.getProjectInfo(fileName, true), configFileName = _a.configFileName, fileNamesInProject = _a.fileNames; - fileNamesInProject = fileNamesInProject.filter(function (value, index, array) { return value.indexOf("lib.d.ts") < 0; }); + var fileNames = this.getProjectInfo(fileName, true).fileNames; + var fileNamesInProject = fileNames.filter(function (value, index, array) { return value.indexOf("lib.d.ts") < 0; }); var highPriorityFiles = []; var mediumPriorityFiles = []; var lowPriorityFiles = []; @@ -43051,7 +45925,7 @@ var ts; } }; return Session; - })(); + }()); server.Session = Session; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); @@ -43113,7 +45987,7 @@ var ts; return this.snap().getChangeRange(oldSnapshot); }; return ScriptInfo; - })(); + }()); server.ScriptInfo = ScriptInfo; var LSHost = (function () { function LSHost(host, project) { @@ -43126,7 +46000,8 @@ var ts; this.filenameToScript = ts.createFileMap(); this.moduleResolutionHost = { fileExists: function (fileName) { return _this.fileExists(fileName); }, - readFile: function (fileName) { return _this.host.readFile(fileName); } + readFile: function (fileName) { return _this.host.readFile(fileName); }, + directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } }; } LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { @@ -43135,8 +46010,8 @@ var ts; var newResolutions = {}; var resolvedModules = []; var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { - var moduleName = moduleNames_1[_i]; + for (var _i = 0, moduleNames_2 = moduleNames; _i < moduleNames_2.length; _i++) { + var moduleName = moduleNames_2[_i]; var resolution = ts.lookUp(newResolutions, moduleName); if (!resolution) { var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, moduleName); @@ -43192,6 +46067,9 @@ var ts; LSHost.prototype.getScriptFileNames = function () { return this.roots.map(function (root) { return root.fileName; }); }; + LSHost.prototype.getScriptKind = function () { + return 0; + }; LSHost.prototype.getScriptVersion = function (filename) { return this.getScriptInfo(filename).svc.latestVersion().toString(); }; @@ -43253,12 +46131,10 @@ var ts; throw new Error("No script with name '" + filename + "'"); }; LSHost.prototype.resolvePath = function (path) { - var start = new Date().getTime(); var result = this.host.resolvePath(path); return result; }; LSHost.prototype.fileExists = function (path) { - var start = new Date().getTime(); var result = this.host.fileExists(path); return result; }; @@ -43295,32 +46171,8 @@ var ts; return { line: lineOffset.line, offset: lineOffset.offset + 1 }; }; return LSHost; - })(); + }()); server.LSHost = LSHost; - function getAbsolutePath(filename, directory) { - var rootLength = ts.getRootLength(filename); - if (rootLength > 0) { - return filename; - } - else { - var splitFilename = filename.split("/"); - var splitDir = directory.split("/"); - var i = 0; - var dirTail = 0; - var sflen = splitFilename.length; - while ((i < sflen) && (splitFilename[i].charAt(0) == ".")) { - var dots = splitFilename[i]; - if (dots == "..") { - dirTail++; - } - else if (dots != ".") { - return undefined; - } - i++; - } - return splitDir.slice(0, splitDir.length - dirTail).concat(splitFilename.slice(i)).join("/"); - } - } var Project = (function () { function Project(projectService, projectOptions) { this.projectService = projectService; @@ -43329,6 +46181,9 @@ var ts; this.filenameToSourceFile = {}; this.updateGraphSeq = 0; this.openRefCount = 0; + if (projectOptions && projectOptions.files) { + projectOptions.compilerOptions.allowNonTsExtensions = true; + } this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); } Project.prototype.addOpenRef = function () { @@ -43399,11 +46254,12 @@ var ts; Project.prototype.setProjectOptions = function (projectOptions) { this.projectOptions = projectOptions; if (projectOptions.compilerOptions) { + projectOptions.compilerOptions.allowNonTsExtensions = true; this.compilerService.setCompilerOptions(projectOptions.compilerOptions); } }; return Project; - })(); + }()); server.Project = Project; function copyListRemovingItem(item, list) { var copiedList = []; @@ -43427,7 +46283,7 @@ var ts; this.openFileRootsConfigured = []; this.directoryWatchersForTsconfig = {}; this.directoryWatchersRefCount = {}; - this.timerForDetectingProjectFilelistChanges = {}; + this.timerForDetectingProjectFileListChanges = {}; this.addDefaultHostConfiguration(); } ProjectService.prototype.addDefaultHostConfiguration = function () { @@ -43460,22 +46316,22 @@ var ts; } }; ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName)) { + if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) { return; } this.log("Detected source file changes: " + fileName); - this.startTimerForDetectingProjectFilelistChanges(project); + this.startTimerForDetectingProjectFileListChanges(project); }; - ProjectService.prototype.startTimerForDetectingProjectFilelistChanges = function (project) { + ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) { var _this = this; - if (this.timerForDetectingProjectFilelistChanges[project.projectFilename]) { - clearTimeout(this.timerForDetectingProjectFilelistChanges[project.projectFilename]); + if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) { + clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]); } - this.timerForDetectingProjectFilelistChanges[project.projectFilename] = setTimeout(function () { return _this.handleProjectFilelistChanges(project); }, 250); + this.timerForDetectingProjectFileListChanges[project.projectFilename] = setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250); }; - ProjectService.prototype.handleProjectFilelistChanges = function (project) { + ProjectService.prototype.handleProjectFileListChanges = function (project) { var _this = this; - var _a = this.configFileToProjectOptions(project.projectFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, error = _a.error; + var projectOptions = this.configFileToProjectOptions(project.projectFilename).projectOptions; var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { @@ -43490,7 +46346,7 @@ var ts; return; } this.log("Detected newly added tsconfig file: " + fileName); - var _a = this.configFileToProjectOptions(fileName), succeeded = _a.succeeded, projectOptions = _a.projectOptions, error = _a.error; + var projectOptions = this.configFileToProjectOptions(fileName).projectOptions; var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { @@ -43609,7 +46465,8 @@ var ts; else { for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { var directory = _a[_i]; - if (!(--project.projectService.directoryWatchersRefCount[directory])) { + project.projectService.directoryWatchersRefCount[directory]--; + if (!project.projectService.directoryWatchersRefCount[directory]) { this.log("Close directory watcher for: " + directory); project.projectService.directoryWatchersForTsconfig[directory].close(); delete project.projectService.directoryWatchersForTsconfig[directory]; @@ -43809,14 +46666,14 @@ var ts; filename = ts.normalizePath(filename); return ts.lookUp(this.filenameToScriptInfo, filename); }; - ProjectService.prototype.openFile = function (fileName, openedByClient) { + ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent) { var _this = this; fileName = ts.normalizePath(fileName); var info = ts.lookUp(this.filenameToScriptInfo, fileName); if (!info) { - var content; + var content = void 0; if (this.host.fileExists(fileName)) { - content = this.host.readFile(fileName); + content = fileContent || this.host.readFile(fileName); } if (!content) { if (openedByClient) { @@ -43824,16 +46681,18 @@ var ts; } } if (content !== undefined) { - var indentSize; info = new ScriptInfo(this.host, fileName, content, openedByClient); info.setFormatOptions(this.getFormatCodeOptions()); this.filenameToScriptInfo[fileName] = info; if (!info.isOpen) { - info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); }); + info.fileWatcher = this.host.watchFile(ts.toPath(fileName, fileName, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { _this.watchedFileChanged(fileName); }); } } } if (info) { + if (fileContent) { + info.svc.reload(fileContent); + } if (openedByClient) { info.isOpen = true; } @@ -43842,9 +46701,13 @@ var ts; }; ProjectService.prototype.findConfigFile = function (searchPath) { while (true) { - var fileName = ts.combinePaths(searchPath, "tsconfig.json"); - if (this.host.fileExists(fileName)) { - return fileName; + var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json"); + if (this.host.fileExists(tsconfigFileName)) { + return tsconfigFileName; + } + var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json"); + if (this.host.fileExists(jsconfigFileName)) { + return jsconfigFileName; } var parentPath = ts.getDirectoryPath(searchPath); if (parentPath === searchPath) { @@ -43854,9 +46717,9 @@ var ts; } return undefined; }; - ProjectService.prototype.openClientFile = function (fileName) { + ProjectService.prototype.openClientFile = function (fileName, fileContent) { this.openOrUpdateConfiguredProjectForFile(fileName); - var info = this.openFile(fileName, true); + var info = this.openFile(fileName, true, fileContent); this.addOpenFile(info); this.printProjects(); return info; @@ -43972,7 +46835,7 @@ var ts; return { succeeded: false, error: rawConfig.error }; } else { - var parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath); + var parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath, {}, configFilename); ts.Debug.assert(!!parsedCommandLine.fileNames); if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { return { succeeded: false, error: { errorMsg: "tsconfig option errors" } }; @@ -43996,22 +46859,22 @@ var ts; return error; } else { - var project = this.createProject(configFilename, projectOptions); + var project_1 = this.createProject(configFilename, projectOptions); for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { var rootFilename = _b[_i]; if (this.host.fileExists(rootFilename)) { var info = this.openFile(rootFilename, clientFileName == rootFilename); - project.addRoot(info); + project_1.addRoot(info); } else { return { errorMsg: "specified file " + rootFilename + " not found" }; } } - project.finishGraph(); - project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); }); + project_1.finishGraph(); + project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); this.log("Add recursive watcher for: " + ts.getDirectoryPath(configFilename)); - project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(configFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - return { success: true, project: project }; + project_1.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(configFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project_1, path); }, true); + return { success: true, project: project_1 }; } }; ProjectService.prototype.updateConfiguredProject = function (project) { @@ -44025,10 +46888,10 @@ var ts; return error; } else { - var oldFileNames = project.compilerService.host.roots.map(function (info) { return info.fileName; }); - var newFileNames = projectOptions.files; - var fileNamesToRemove = oldFileNames.filter(function (f) { return newFileNames.indexOf(f) < 0; }); - var fileNamesToAdd = newFileNames.filter(function (f) { return oldFileNames.indexOf(f) < 0; }); + var oldFileNames_1 = project.compilerService.host.roots.map(function (info) { return info.fileName; }); + var newFileNames_1 = projectOptions.files; + var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); + var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); for (var _i = 0, fileNamesToRemove_1 = fileNamesToRemove; _i < fileNamesToRemove_1.length; _i++) { var fileName = fileNamesToRemove_1[_i]; var info = this.getScriptInfo(fileName); @@ -44070,7 +46933,7 @@ var ts; return project; }; return ProjectService; - })(); + }()); server.ProjectService = ProjectService; var CompilerService = (function () { function CompilerService(project, opt) { @@ -44081,7 +46944,9 @@ var ts; this.setCompilerOptions(opt); } else { - this.setCompilerOptions(ts.getDefaultCompilerOptions()); + var defaultOpts = ts.getDefaultCompilerOptions(); + defaultOpts.allowNonTsExtensions = true; + this.setCompilerOptions(defaultOpts); } this.languageService = ts.createLanguageService(this.host, this.documentRegistry); this.classifier = ts.createClassifier(); @@ -44107,11 +46972,12 @@ var ts; InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, PlaceOpenBraceOnNewLineForFunctions: false, PlaceOpenBraceOnNewLineForControlBlocks: false }; return CompilerService; - })(); + }()); server.CompilerService = CompilerService; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; @@ -44130,7 +46996,7 @@ var ts; BaseLineIndexWalker.prototype.leaf = function (rangeStart, rangeLength, ll) { }; return BaseLineIndexWalker; - })(); + }()); var EditWalker = (function (_super) { __extends(EditWalker, _super); function EditWalker() { @@ -44314,7 +47180,7 @@ var ts; } }; return EditWalker; - })(BaseLineIndexWalker); + }(BaseLineIndexWalker)); var TextChange = (function () { function TextChange(pos, deleteLen, insertedText) { this.pos = pos; @@ -44325,7 +47191,7 @@ var ts; return ts.createTextChangeRange(ts.createTextSpan(this.pos, this.deleteLen), this.insertedText ? this.insertedText.length : 0); }; return TextChange; - })(); + }()); server.TextChange = TextChange; var ScriptVersionCache = (function () { function ScriptVersionCache() { @@ -44429,7 +47295,7 @@ var ts; ScriptVersionCache.changeLengthThreshold = 256; ScriptVersionCache.maxVersions = 8; return ScriptVersionCache; - })(); + }()); server.ScriptVersionCache = ScriptVersionCache; var LineIndexSnapshot = (function () { function LineIndexSnapshot(version, cache) { @@ -44448,7 +47314,8 @@ var ts; var count = 1; var pos = 0; this.index.every(function (ll, s, len) { - starts[count++] = pos; + starts[count] = pos; + count++; pos += ll.text.length; return true; }, 0); @@ -44456,9 +47323,9 @@ var ts; }; LineIndexSnapshot.prototype.getLineMapper = function () { var _this = this; - return (function (line) { + return function (line) { return _this.index.lineNumberToInfo(line).offset; - }); + }; }; LineIndexSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { if (this.version <= scriptVersion) { @@ -44473,7 +47340,7 @@ var ts; return this.getTextChangeRangeSinceVersion(oldSnap.version); }; return LineIndexSnapshot; - })(); + }()); server.LineIndexSnapshot = LineIndexSnapshot; var LineIndex = (function () { function LineIndex() { @@ -44555,7 +47422,7 @@ var ts; } } else { - var checkText; + var checkText = void 0; if (this.checkEdits) { checkText = editFlat(this.getText(0, this.root.charCount()), pos, deleteLength, newText); } @@ -44645,7 +47512,7 @@ var ts; return { lines: lines, lineMap: lineStarts }; }; return LineIndex; - })(); + }()); server.LineIndex = LineIndex; var LineNode = (function () { function LineNode() { @@ -44694,7 +47561,8 @@ var ts; while (adjustedStart >= childCharCount) { this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, CharRangeSection.PreStart); adjustedStart -= childCharCount; - child = this.children[++childIndex]; + childIndex++; + child = this.children[childIndex]; childCharCount = child.charCount(); } if ((adjustedStart + rangeLength) <= childCharCount) { @@ -44707,14 +47575,16 @@ var ts; return; } var adjustedLength = rangeLength - (childCharCount - adjustedStart); - child = this.children[++childIndex]; + childIndex++; + child = this.children[childIndex]; childCharCount = child.charCount(); while (adjustedLength > childCharCount) { if (this.execWalk(0, childCharCount, walkFns, childIndex, CharRangeSection.Mid)) { return; } adjustedLength -= childCharCount; - child = this.children[++childIndex]; + childIndex++; + child = this.children[childIndex]; childCharCount = child.charCount(); } if (adjustedLength > 0) { @@ -44832,7 +47702,8 @@ var ts; if (childIndex < clen) { splitNode = new LineNode(); while (childIndex < clen) { - splitNode.add(this.children[childIndex++]); + splitNode.add(this.children[childIndex]); + childIndex++; } splitNode.updateCounts(); } @@ -44870,7 +47741,9 @@ var ts; var nodeIndex = 0; childIndex++; while ((childIndex < lineCollectionCapacity) && (nodeIndex < nodeCount)) { - this.children[childIndex++] = nodes[nodeIndex++]; + this.children[childIndex] = nodes[nodeIndex]; + childIndex++; + nodeIndex++; } var splitNodes = []; var splitNodeCount = 0; @@ -44883,7 +47756,8 @@ var ts; } var splitNode = splitNodes[0]; while (nodeIndex < nodeCount) { - splitNode.add(nodes[nodeIndex++]); + splitNode.add(nodes[nodeIndex]); + nodeIndex++; if (splitNode.children.length === lineCollectionCapacity) { splitNodeIndex++; splitNode = splitNodes[splitNodeIndex]; @@ -44916,7 +47790,7 @@ var ts; return this.totalLines; }; return LineNode; - })(); + }()); server.LineNode = LineNode; var LineLeaf = (function () { function LineLeaf(text) { @@ -44941,7 +47815,7 @@ var ts; return 1; }; return LineLeaf; - })(); + }()); server.LineLeaf = LineLeaf; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); @@ -44949,9 +47823,7 @@ var ts; (function (ts) { var server; (function (server) { - var nodeproto = require("_debugger"); var readline = require("readline"); - var path = require("path"); var fs = require("fs"); var rl = readline.createInterface({ input: process.stdin, @@ -45019,7 +47891,7 @@ var ts; } }; return Logger; - })(); + }()); var IOSession = (function (_super) { __extends(IOSession, _super); function IOSession(host, logger) { @@ -45041,7 +47913,7 @@ var ts; }); }; return IOSession; - })(server.Session); + }(server.Session)); function parseLoggingEnvironmentString(logEnvStr) { var logEnv = {}; var args = logEnvStr.split(" "); @@ -45116,7 +47988,6 @@ var ts; var ScriptSnapshotShimAdapter = (function () { function ScriptSnapshotShimAdapter(scriptSnapshotShim) { this.scriptSnapshotShim = scriptSnapshotShim; - this.lineStartPositions = null; } ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { return this.scriptSnapshotShim.getText(start, end); @@ -45139,7 +48010,7 @@ var ts; } }; return ScriptSnapshotShimAdapter; - })(); + }()); var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { var _this = this; @@ -45155,6 +48026,9 @@ var ts; }); }; } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } LanguageServiceShimHostAdapter.prototype.log = function (s) { if (this.loggingEnabled) { @@ -45190,12 +48064,17 @@ var ts; return this.files = JSON.parse(encoded); }; LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { - if (this.files && this.files.indexOf(fileName) < 0) { - return undefined; - } var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); }; + LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { + if ("getScriptKind" in this.shimHost) { + return this.shimHost.getScriptKind(fileName); + } + else { + return 0; + } + }; LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) { return this.shimHost.getScriptVersion(fileName); }; @@ -45220,15 +48099,10 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { - try { - return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); - } - catch (e) { - return ""; - } + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; return LanguageServiceShimHostAdapter; - })(); + }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; var ThrottledCancellationToken = (function () { function ThrottledCancellationToken(hostCancellationToken) { @@ -45245,19 +48119,17 @@ var ts; return false; }; return ThrottledCancellationToken; - })(); + }()); var CoreServicesShimHostAdapter = (function () { function CoreServicesShimHostAdapter(shimHost) { + var _this = this; this.shimHost = shimHost; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude) { - var encoded; - try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); - } - catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension); - } + var encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -45267,18 +48139,19 @@ var ts; return this.shimHost.readFile(fileName); }; return CoreServicesShimHostAdapter; - })(); + }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; if (logPerformance) { logger.log(actionDescription); - var start = Date.now(); + start = Date.now(); } var result = action(); if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof (result) === "string") { + if (typeof result === "string") { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -45311,7 +48184,7 @@ var ts; this.factory.unregisterShim(this); }; return ShimBase; - })(); + }()); function realizeDiagnostics(diagnostics, newLine) { return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); } @@ -45349,9 +48222,7 @@ var ts; _super.prototype.dispose.call(this, dummy); }; LanguageServiceShimObject.prototype.refresh = function (throwOnError) { - this.forwardJSONCall("refresh(" + throwOnError + ")", function () { - return null; - }); + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); }; LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { var _this = this; @@ -45366,29 +48237,19 @@ var ts; }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { var _this = this; @@ -45413,62 +48274,39 @@ var ts; }; LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { - var quickInfo = _this.languageService.getQuickInfoAtPosition(fileName, position); - return quickInfo; - }); + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { var _this = this; - return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { - var spanInfo = _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); - return spanInfo; - }); + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); }; LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { - var spanInfo = _this.languageService.getBreakpointStatementAtPosition(fileName, position); - return spanInfo; - }); + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { - var signatureInfo = _this.languageService.getSignatureHelpItems(fileName, position); - return signatureInfo; - }); + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); }; LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getTypeDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { - return _this.languageService.getRenameInfo(fileName, position); - }); + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); }; LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { - return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); - }); + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); }; LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { - var textRanges = _this.languageService.getBraceMatchingAtPosition(fileName, position); - return textRanges; - }); + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options) { var _this = this; @@ -45479,21 +48317,15 @@ var ts; }; LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getReferencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { var _this = this; - return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { - return _this.languageService.findReferences(fileName, position); - }); + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); }; LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getOccurrencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { var _this = this; @@ -45505,40 +48337,31 @@ var ts; }; LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { - var completion = _this.languageService.getCompletionsAtPosition(fileName, position); - return completion; - }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")", function () { - var details = _this.languageService.getCompletionEntryDetails(fileName, position, entryName); - return details; - }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options) { var _this = this; return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); - return edits; + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options) { var _this = this; return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForDocument(fileName, localOptions); - return edits; + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options) { var _this = this; return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); - return edits; + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { @@ -45547,42 +48370,26 @@ var ts; }; LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { - var items = _this.languageService.getNavigateToItems(searchValue, maxResultCount); - return items; - }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; - return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { - var items = _this.languageService.getNavigationBarItems(fileName); - return items; - }); + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; - return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { - var items = _this.languageService.getOutliningSpans(fileName); - return items; - }); + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); }; LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { var _this = this; - return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { - var items = _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); - return items; - }); + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); }; LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { var _this = this; - return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { - var output = _this.languageService.getEmitOutput(fileName); - output.emitOutputStatus = output.emitSkipped ? 1 : 0; - return output; - }); + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); }; return LanguageServiceShimObject; - })(ShimBase); + }(ShimBase)); function convertClassifications(classifications) { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } @@ -45600,17 +48407,17 @@ var ts; }; ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); - var items = classification.entries; var result = ""; - for (var i = 0; i < items.length; i++) { - result += items[i].length + "\n"; - result += items[i].classification + "\n"; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; } result += classification.finalLexState; return result; }; return ClassifierShimObject; - })(ShimBase); + }(ShimBase)); var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { @@ -45635,7 +48442,7 @@ var ts; }; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength())); + var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), true, true); var convertResult = { referencedFiles: [], importedFiles: [], @@ -45668,24 +48475,23 @@ var ts; return { options: {}, files: [], - errors: [realizeDiagnostic(result.error, '\r\n')] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } - var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(ts.normalizeSlashes(fileName))); + var normalizedFileName = ts.normalizeSlashes(fileName); + var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), {}, normalizedFileName); return { options: configFile.options, files: configFile.fileNames, - errors: realizeDiagnostics(configFile.errors, '\r\n') + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { - return this.forwardJSONCall("getDefaultCompilationSettings()", function () { - return ts.getDefaultCompilerOptions(); - }); + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); }; return CoreServicesShimObject; - })(ShimBase); + }(ShimBase)); var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; @@ -45696,7 +48502,7 @@ var ts; TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { try { if (this.documentRegistry === undefined) { - this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var hostAdapter = new LanguageServiceShimHostAdapter(host); var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); @@ -45728,7 +48534,7 @@ var ts; }; TypeScriptServicesFactory.prototype.close = function () { this._shims = []; - this.documentRegistry = ts.createDocumentRegistry(); + this.documentRegistry = undefined; }; TypeScriptServicesFactory.prototype.registerShim = function (shim) { this._shims.push(shim); @@ -45743,7 +48549,7 @@ var ts; throw new Error("Invalid operation"); }; return TypeScriptServicesFactory; - })(); + }()); ts.TypeScriptServicesFactory = TypeScriptServicesFactory; if (typeof module !== "undefined" && module.exports) { module.exports = ts; @@ -45756,4 +48562,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "1.6"; +var toolsVersion = "1.9"; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 972ebfa472d..1ad5a4bc28d 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -160,166 +160,170 @@ declare namespace ts { IsKeyword = 124, ModuleKeyword = 125, NamespaceKeyword = 126, - RequireKeyword = 127, - NumberKeyword = 128, - SetKeyword = 129, - StringKeyword = 130, - SymbolKeyword = 131, - TypeKeyword = 132, - FromKeyword = 133, - OfKeyword = 134, - QualifiedName = 135, - ComputedPropertyName = 136, - TypeParameter = 137, - Parameter = 138, - Decorator = 139, - PropertySignature = 140, - PropertyDeclaration = 141, - MethodSignature = 142, - MethodDeclaration = 143, - Constructor = 144, - GetAccessor = 145, - SetAccessor = 146, - CallSignature = 147, - ConstructSignature = 148, - IndexSignature = 149, - TypePredicate = 150, - TypeReference = 151, - FunctionType = 152, - ConstructorType = 153, - TypeQuery = 154, - TypeLiteral = 155, - ArrayType = 156, - TupleType = 157, - UnionType = 158, - IntersectionType = 159, - ParenthesizedType = 160, - ObjectBindingPattern = 161, - ArrayBindingPattern = 162, - BindingElement = 163, - ArrayLiteralExpression = 164, - ObjectLiteralExpression = 165, - PropertyAccessExpression = 166, - ElementAccessExpression = 167, - CallExpression = 168, - NewExpression = 169, - TaggedTemplateExpression = 170, - TypeAssertionExpression = 171, - ParenthesizedExpression = 172, - FunctionExpression = 173, - ArrowFunction = 174, - DeleteExpression = 175, - TypeOfExpression = 176, - VoidExpression = 177, - AwaitExpression = 178, - PrefixUnaryExpression = 179, - PostfixUnaryExpression = 180, - BinaryExpression = 181, - ConditionalExpression = 182, - TemplateExpression = 183, - YieldExpression = 184, - SpreadElementExpression = 185, - ClassExpression = 186, - OmittedExpression = 187, - ExpressionWithTypeArguments = 188, - AsExpression = 189, - TemplateSpan = 190, - SemicolonClassElement = 191, - Block = 192, - VariableStatement = 193, - EmptyStatement = 194, - ExpressionStatement = 195, - IfStatement = 196, - DoStatement = 197, - WhileStatement = 198, - ForStatement = 199, - ForInStatement = 200, - ForOfStatement = 201, - ContinueStatement = 202, - BreakStatement = 203, - ReturnStatement = 204, - WithStatement = 205, - SwitchStatement = 206, - LabeledStatement = 207, - ThrowStatement = 208, - TryStatement = 209, - DebuggerStatement = 210, - VariableDeclaration = 211, - VariableDeclarationList = 212, - FunctionDeclaration = 213, - ClassDeclaration = 214, - InterfaceDeclaration = 215, - TypeAliasDeclaration = 216, - EnumDeclaration = 217, - ModuleDeclaration = 218, - ModuleBlock = 219, - CaseBlock = 220, - ImportEqualsDeclaration = 221, - ImportDeclaration = 222, - ImportClause = 223, - NamespaceImport = 224, - NamedImports = 225, - ImportSpecifier = 226, - ExportAssignment = 227, - ExportDeclaration = 228, - NamedExports = 229, - ExportSpecifier = 230, - MissingDeclaration = 231, - ExternalModuleReference = 232, - JsxElement = 233, - JsxSelfClosingElement = 234, - JsxOpeningElement = 235, - JsxText = 236, - JsxClosingElement = 237, - JsxAttribute = 238, - JsxSpreadAttribute = 239, - JsxExpression = 240, - CaseClause = 241, - DefaultClause = 242, - HeritageClause = 243, - CatchClause = 244, - PropertyAssignment = 245, - ShorthandPropertyAssignment = 246, - EnumMember = 247, - SourceFile = 248, - JSDocTypeExpression = 249, - JSDocAllType = 250, - JSDocUnknownType = 251, - JSDocArrayType = 252, - JSDocUnionType = 253, - JSDocTupleType = 254, - JSDocNullableType = 255, - JSDocNonNullableType = 256, - JSDocRecordType = 257, - JSDocRecordMember = 258, - JSDocTypeReference = 259, - JSDocOptionalType = 260, - JSDocFunctionType = 261, - JSDocVariadicType = 262, - JSDocConstructorType = 263, - JSDocThisType = 264, - JSDocComment = 265, - JSDocTag = 266, - JSDocParameterTag = 267, - JSDocReturnTag = 268, - JSDocTypeTag = 269, - JSDocTemplateTag = 270, - SyntaxList = 271, - Count = 272, + ReadonlyKeyword = 127, + RequireKeyword = 128, + NumberKeyword = 129, + SetKeyword = 130, + StringKeyword = 131, + SymbolKeyword = 132, + TypeKeyword = 133, + FromKeyword = 134, + GlobalKeyword = 135, + OfKeyword = 136, + QualifiedName = 137, + ComputedPropertyName = 138, + TypeParameter = 139, + Parameter = 140, + Decorator = 141, + PropertySignature = 142, + PropertyDeclaration = 143, + MethodSignature = 144, + MethodDeclaration = 145, + Constructor = 146, + GetAccessor = 147, + SetAccessor = 148, + CallSignature = 149, + ConstructSignature = 150, + IndexSignature = 151, + TypePredicate = 152, + TypeReference = 153, + FunctionType = 154, + ConstructorType = 155, + TypeQuery = 156, + TypeLiteral = 157, + ArrayType = 158, + TupleType = 159, + UnionType = 160, + IntersectionType = 161, + ParenthesizedType = 162, + ThisType = 163, + StringLiteralType = 164, + ObjectBindingPattern = 165, + ArrayBindingPattern = 166, + BindingElement = 167, + ArrayLiteralExpression = 168, + ObjectLiteralExpression = 169, + PropertyAccessExpression = 170, + ElementAccessExpression = 171, + CallExpression = 172, + NewExpression = 173, + TaggedTemplateExpression = 174, + TypeAssertionExpression = 175, + ParenthesizedExpression = 176, + FunctionExpression = 177, + ArrowFunction = 178, + DeleteExpression = 179, + TypeOfExpression = 180, + VoidExpression = 181, + AwaitExpression = 182, + PrefixUnaryExpression = 183, + PostfixUnaryExpression = 184, + BinaryExpression = 185, + ConditionalExpression = 186, + TemplateExpression = 187, + YieldExpression = 188, + SpreadElementExpression = 189, + ClassExpression = 190, + OmittedExpression = 191, + ExpressionWithTypeArguments = 192, + AsExpression = 193, + TemplateSpan = 194, + SemicolonClassElement = 195, + Block = 196, + VariableStatement = 197, + EmptyStatement = 198, + ExpressionStatement = 199, + IfStatement = 200, + DoStatement = 201, + WhileStatement = 202, + ForStatement = 203, + ForInStatement = 204, + ForOfStatement = 205, + ContinueStatement = 206, + BreakStatement = 207, + ReturnStatement = 208, + WithStatement = 209, + SwitchStatement = 210, + LabeledStatement = 211, + ThrowStatement = 212, + TryStatement = 213, + DebuggerStatement = 214, + VariableDeclaration = 215, + VariableDeclarationList = 216, + FunctionDeclaration = 217, + ClassDeclaration = 218, + InterfaceDeclaration = 219, + TypeAliasDeclaration = 220, + EnumDeclaration = 221, + ModuleDeclaration = 222, + ModuleBlock = 223, + CaseBlock = 224, + ImportEqualsDeclaration = 225, + ImportDeclaration = 226, + ImportClause = 227, + NamespaceImport = 228, + NamedImports = 229, + ImportSpecifier = 230, + ExportAssignment = 231, + ExportDeclaration = 232, + NamedExports = 233, + ExportSpecifier = 234, + MissingDeclaration = 235, + ExternalModuleReference = 236, + JsxElement = 237, + JsxSelfClosingElement = 238, + JsxOpeningElement = 239, + JsxText = 240, + JsxClosingElement = 241, + JsxAttribute = 242, + JsxSpreadAttribute = 243, + JsxExpression = 244, + CaseClause = 245, + DefaultClause = 246, + HeritageClause = 247, + CatchClause = 248, + PropertyAssignment = 249, + ShorthandPropertyAssignment = 250, + EnumMember = 251, + SourceFile = 252, + JSDocTypeExpression = 253, + JSDocAllType = 254, + JSDocUnknownType = 255, + JSDocArrayType = 256, + JSDocUnionType = 257, + JSDocTupleType = 258, + JSDocNullableType = 259, + JSDocNonNullableType = 260, + JSDocRecordType = 261, + JSDocRecordMember = 262, + JSDocTypeReference = 263, + JSDocOptionalType = 264, + JSDocFunctionType = 265, + JSDocVariadicType = 266, + JSDocConstructorType = 267, + JSDocThisType = 268, + JSDocComment = 269, + JSDocTag = 270, + JSDocParameterTag = 271, + JSDocReturnTag = 272, + JSDocTypeTag = 273, + JSDocTemplateTag = 274, + SyntaxList = 275, + Count = 276, FirstAssignment = 56, LastAssignment = 68, FirstReservedWord = 70, LastReservedWord = 105, FirstKeyword = 70, - LastKeyword = 134, + LastKeyword = 136, FirstFutureReservedWord = 106, LastFutureReservedWord = 114, - FirstTypeNode = 151, - LastTypeNode = 160, + FirstTypeNode = 152, + LastTypeNode = 164, FirstPunctuation = 15, LastPunctuation = 68, FirstToken = 0, - LastToken = 134, + LastToken = 136, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -328,41 +332,54 @@ declare namespace ts { LastTemplateToken = 14, FirstBinaryOperator = 25, LastBinaryOperator = 68, - FirstNode = 135, + FirstNode = 137, } enum NodeFlags { None = 0, - Export = 2, - Ambient = 4, - Public = 8, - Private = 16, - Protected = 32, - Static = 64, + Export = 1, + Ambient = 2, + Public = 4, + Private = 8, + Protected = 16, + Static = 32, + Readonly = 64, Abstract = 128, Async = 256, Default = 512, - MultiLine = 1024, - Synthetic = 2048, - DeclarationFile = 4096, - Let = 8192, - Const = 16384, - OctalLiteral = 32768, - Namespace = 65536, - ExportContext = 131072, - ContainsThis = 262144, - HasImplicitReturn = 524288, - HasExplicitReturn = 1048576, - Modifier = 1022, - AccessibilityModifier = 56, - BlockScoped = 24576, - ReachabilityCheckFlags = 1572864, + Let = 1024, + Const = 2048, + Namespace = 4096, + ExportContext = 8192, + ContainsThis = 16384, + HasImplicitReturn = 32768, + HasExplicitReturn = 65536, + GlobalAugmentation = 131072, + HasClassExtends = 262144, + HasDecorators = 524288, + HasParamDecorators = 1048576, + HasAsyncFunctions = 2097152, + DisallowInContext = 4194304, + YieldContext = 8388608, + DecoratorContext = 16777216, + AwaitContext = 33554432, + ThisNodeHasError = 67108864, + JavaScriptFile = 134217728, + ThisNodeOrAnySubNodesHasError = 268435456, + HasAggregatedChildData = 536870912, + Modifier = 959, + AccessibilityModifier = 28, + BlockScoped = 3072, + ReachabilityCheckFlags = 98304, + EmitHelperFlags = 3932160, + ContextFlags = 62914560, + TypeExcludesFlags = 41943040, } enum JsxFlags { None = 0, + /** An element from a named property of the JSX.IntrinsicElements interface */ IntrinsicNamedElement = 1, + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - ClassElement = 4, - UnknownElement = 8, IntrinsicElement = 3, } interface Node extends TextRange { @@ -375,9 +392,11 @@ declare namespace ts { interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface ModifiersArray extends NodeArray { + interface ModifiersArray extends NodeArray { flags: number; } + interface Modifier extends Node { + } interface Identifier extends PrimaryExpression { text: string; originalKeywordKind?: SyntaxKind; @@ -387,11 +406,15 @@ declare namespace ts { right: Identifier; } type EntityName = Identifier | QualifiedName; + type PropertyName = Identifier | LiteralExpression | ComputedPropertyName; type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; name?: DeclarationName; } + interface DeclarationStatement extends Declaration, Statement { + name?: Identifier; + } interface ComputedPropertyName extends Node { expression: Expression; } @@ -404,10 +427,15 @@ declare namespace ts { expression?: Expression; } interface SignatureDeclaration extends Declaration { + name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; type?: TypeNode; } + interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + } + interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + } interface VariableDeclaration extends Declaration { parent?: VariableDeclarationList; name: Identifier | BindingPattern; @@ -425,23 +453,30 @@ declare namespace ts { initializer?: Expression; } interface BindingElement extends Declaration { - propertyName?: Identifier; + propertyName?: PropertyName; dotDotDotToken?: Node; name: Identifier | BindingPattern; initializer?: Expression; } - interface PropertyDeclaration extends Declaration, ClassElement { - name: DeclarationName; + interface PropertySignature extends TypeElement { + name: PropertyName; questionToken?: Node; type?: TypeNode; initializer?: Expression; } + interface PropertyDeclaration extends ClassElement { + questionToken?: Node; + name: PropertyName; + type?: TypeNode; + initializer?: Expression; + } interface ObjectLiteralElement extends Declaration { _objectLiteralBrandBrand: any; + name?: PropertyName; } interface PropertyAssignment extends ObjectLiteralElement { _propertyAssignmentBrand: any; - name: DeclarationName; + name: PropertyName; questionToken?: Node; initializer: Expression; } @@ -452,16 +487,23 @@ declare namespace ts { objectAssignmentInitializer?: Expression; } interface VariableLikeDeclaration extends Declaration { - propertyName?: Identifier; + propertyName?: PropertyName; dotDotDotToken?: Node; name: DeclarationName; questionToken?: Node; type?: TypeNode; initializer?: Expression; } + interface PropertyLikeDeclaration extends Declaration { + name: PropertyName; + } interface BindingPattern extends Node { elements: NodeArray; } + interface ObjectBindingPattern extends BindingPattern { + } + interface ArrayBindingPattern extends BindingPattern { + } /** * Several node kinds share function-like features such as a signature, * a name, and a body. These nodes should extend FunctionLikeDeclaration. @@ -476,45 +518,61 @@ declare namespace ts { questionToken?: Node; body?: Block | Expression; } - interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { + interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { name?: Identifier; - body?: Block; + body?: FunctionBody; + } + interface MethodSignature extends SignatureDeclaration, TypeElement { + name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - body?: Block; + name: PropertyName; + body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { - body?: Block; + body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { _semicolonClassElementBrand: any; } interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { _accessorDeclarationBrand: any; - body: Block; + name: PropertyName; + body: FunctionBody; } - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { + interface GetAccessorDeclaration extends AccessorDeclaration { + } + interface SetAccessorDeclaration extends AccessorDeclaration { + } + interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { _indexSignatureDeclarationBrand: any; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface ThisTypeNode extends TypeNode { + _thisTypeNodeBrand: any; + } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { _functionOrConstructorTypeNodeBrand: any; } + interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + } + interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + } interface TypeReferenceNode extends TypeNode { typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { - parameterName: Identifier; + parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { - members: NodeArray; + members: NodeArray; } interface ArrayTypeNode extends TypeNode { elementType: TypeNode; @@ -532,13 +590,18 @@ declare namespace ts { interface ParenthesizedTypeNode extends TypeNode { type: TypeNode; } - interface StringLiteral extends LiteralExpression, TypeNode { + interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode { + _stringLiteralTypeBrand: any; + } + interface StringLiteral extends LiteralExpression { _stringLiteralBrand: any; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } + interface OmittedExpression extends Expression { + } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; } @@ -581,7 +644,7 @@ declare namespace ts { asteriskToken?: Node; expression?: Expression; } - interface BinaryExpression extends Expression { + interface BinaryExpression extends Expression, Declaration { left: Expression; operatorToken: Node; right: Expression; @@ -593,25 +656,34 @@ declare namespace ts { colonToken: Node; whenFalse: Expression; } + type FunctionBody = Block; + type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { name?: Identifier; - body: Block | Expression; + body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { equalsGreaterThanToken: Node; + body: ConciseBody; } - interface LiteralExpression extends PrimaryExpression { + interface LiteralLikeNode extends Node { text: string; isUnterminated?: boolean; hasExtendedUnicodeEscape?: boolean; } + interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { + _literalExpressionBrand: any; + } + interface TemplateLiteralFragment extends LiteralLikeNode { + _templateLiteralFragmentBrand: any; + } interface TemplateExpression extends PrimaryExpression { - head: LiteralExpression; + head: TemplateLiteralFragment; templateSpans: NodeArray; } interface TemplateSpan extends Node { expression: Expression; - literal: LiteralExpression; + literal: TemplateLiteralFragment; } interface ParenthesizedExpression extends PrimaryExpression { expression: Expression; @@ -625,7 +697,7 @@ declare namespace ts { interface ObjectLiteralExpression extends PrimaryExpression, Declaration { properties: NodeArray; } - interface PropertyAccessExpression extends MemberExpression { + interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; dotToken: Node; name: Identifier; @@ -634,7 +706,7 @@ declare namespace ts { expression: LeftHandSideExpression; argumentExpression?: Expression; } - interface CallExpression extends LeftHandSideExpression { + interface CallExpression extends LeftHandSideExpression, Declaration { expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; @@ -693,6 +765,14 @@ declare namespace ts { interface Statement extends Node { _statementBrand: any; } + interface EmptyStatement extends Statement { + } + interface DebuggerStatement extends Statement { + } + interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + name?: Identifier; + } + type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { statements: NodeArray; } @@ -729,9 +809,13 @@ declare namespace ts { initializer: VariableDeclarationList | Expression; expression: Expression; } - interface BreakOrContinueStatement extends Statement { + interface BreakStatement extends Statement { label?: Identifier; } + interface ContinueStatement extends Statement { + label?: Identifier; + } + type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { expression?: Expression; } @@ -747,7 +831,7 @@ declare namespace ts { clauses: NodeArray; } interface CaseClause extends Node { - expression?: Expression; + expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { @@ -776,24 +860,31 @@ declare namespace ts { heritageClauses?: NodeArray; members: NodeArray; } - interface ClassDeclaration extends ClassLikeDeclaration, Statement { + interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { } interface ClassElement extends Declaration { _classElementBrand: any; + name?: PropertyName; } - interface InterfaceDeclaration extends Declaration, Statement { + interface TypeElement extends Declaration { + _typeElementBrand: any; + name?: PropertyName; + questionToken?: Node; + } + interface InterfaceDeclaration extends DeclarationStatement { name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; - members: NodeArray; + members: NodeArray; } interface HeritageClause extends Node { token: SyntaxKind; types?: NodeArray; } - interface TypeAliasDeclaration extends Declaration, Statement { + interface TypeAliasDeclaration extends DeclarationStatement { name: Identifier; typeParameters?: NodeArray; type: TypeNode; @@ -802,18 +893,19 @@ declare namespace ts { name: DeclarationName; initializer?: Expression; } - interface EnumDeclaration extends Declaration, Statement { + interface EnumDeclaration extends DeclarationStatement { name: Identifier; members: NodeArray; } - interface ModuleDeclaration extends Declaration, Statement { + type ModuleBody = ModuleBlock | ModuleDeclaration; + interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; body: ModuleBlock | ModuleDeclaration; } interface ModuleBlock extends Node, Statement { statements: NodeArray; } - interface ImportEqualsDeclaration extends Declaration, Statement { + interface ImportEqualsDeclaration extends DeclarationStatement { name: Identifier; moduleReference: EntityName | ExternalModuleReference; } @@ -831,22 +923,27 @@ declare namespace ts { interface NamespaceImport extends Declaration { name: Identifier; } - interface ExportDeclaration extends Declaration, Statement { + interface ExportDeclaration extends DeclarationStatement { exportClause?: NamedExports; moduleSpecifier?: Expression; } - interface NamedImportsOrExports extends Node { - elements: NodeArray; + interface NamedImports extends Node { + elements: NodeArray; } - type NamedImports = NamedImportsOrExports; - type NamedExports = NamedImportsOrExports; - interface ImportOrExportSpecifier extends Declaration { + interface NamedExports extends Node { + elements: NodeArray; + } + type NamedImportsOrExports = NamedImports | NamedExports; + interface ImportSpecifier extends Declaration { propertyName?: Identifier; name: Identifier; } - type ImportSpecifier = ImportOrExportSpecifier; - type ExportSpecifier = ImportOrExportSpecifier; - interface ExportAssignment extends Declaration, Statement { + interface ExportSpecifier extends Declaration { + propertyName?: Identifier; + name: Identifier; + } + type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; + interface ExportAssignment extends DeclarationStatement { isExportEquals?: boolean; expression: Expression; } @@ -907,7 +1004,8 @@ declare namespace ts { interface JSDocThisType extends JSDocType { type: JSDocType; } - interface JSDocRecordMember extends PropertyDeclaration { + type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; + interface JSDocRecordMember extends PropertySignature { name: Identifier | LiteralExpression; type?: JSDocType; } @@ -933,19 +1031,21 @@ declare namespace ts { postParameterName?: Identifier; isBracketed: boolean; } + interface AmdDependency { + path: string; + name: string; + } interface SourceFile extends Declaration { statements: NodeArray; endOfFileToken: Node; fileName: string; path: Path; text: string; - amdDependencies: { - path: string; - name: string; - }[]; + amdDependencies: AmdDependency[]; moduleName: string; referencedFiles: FileReference[]; languageVariant: LanguageVariant; + isDeclarationFile: boolean; /** * lib.d.ts should have a reference comment like * @@ -1039,6 +1139,7 @@ declare namespace ts { } interface EmitResult { emitSkipped: boolean; + /** Contains declaration emit diagnostics */ diagnostics: Diagnostic[]; } interface TypeChecker { @@ -1052,7 +1153,9 @@ declare namespace ts { getReturnTypeOfSignature(signature: Signature): Type; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol; + getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; getShorthandAssignmentValueSymbol(location: Node): Symbol; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; getTypeAtLocation(node: Node): Type; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; @@ -1066,6 +1169,7 @@ declare namespace ts { isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; + isUnknownSymbol(symbol: Symbol): boolean; getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; getAliasedSymbol(symbol: Symbol): Symbol; @@ -1077,10 +1181,11 @@ declare namespace ts { interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; + buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1116,11 +1221,22 @@ declare namespace ts { WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, } - interface TypePredicate { - parameterName: string; - parameterIndex: number; + enum TypePredicateKind { + This = 0, + Identifier = 1, + } + interface TypePredicateBase { + kind: TypePredicateKind; type: Type; } + interface ThisTypePredicate extends TypePredicateBase { + _thisTypePredicateBrand: any; + } + interface IdentifierTypePredicate extends TypePredicateBase { + parameterName: string; + parameterIndex: number; + } + type TypePredicate = IdentifierTypePredicate | ThisTypePredicate; enum SymbolFlags { None = 0, FunctionScopedVariable = 1, @@ -1220,6 +1336,7 @@ declare namespace ts { ObjectLiteral = 524288, ESSymbol = 16777216, ThisType = 33554432, + ObjectLiteralPatternWithComputedProperties = 67108864, StringLike = 258, NumberLike = 132, ObjectType = 80896, @@ -1247,8 +1364,8 @@ declare namespace ts { declaredProperties: Symbol[]; declaredCallSignatures: Signature[]; declaredConstructSignatures: Signature[]; - declaredStringIndexType: Type; - declaredNumberIndexType: Type; + declaredStringIndexInfo: IndexInfo; + declaredNumberIndexInfo: IndexInfo; } interface TypeReference extends ObjectType { target: GenericType; @@ -1277,12 +1394,16 @@ declare namespace ts { declaration: SignatureDeclaration; typeParameters: TypeParameter[]; parameters: Symbol[]; - typePredicate?: TypePredicate; } enum IndexKind { String = 0, Number = 1, } + interface IndexInfo { + type: Type; + isReadonly: boolean; + declaration?: SignatureDeclaration; + } interface DiagnosticMessage { key: string; category: DiagnosticCategory; @@ -1318,6 +1439,9 @@ declare namespace ts { Classic = 1, NodeJs = 2, } + type RootPaths = string[]; + type PathSubstitutions = Map; + type TsConfigOnlyOptions = RootPaths | PathSubstitutions; interface CompilerOptions { allowNonTsExtensions?: boolean; charset?: string; @@ -1329,6 +1453,7 @@ declare namespace ts { inlineSourceMap?: boolean; inlineSources?: boolean; jsx?: JsxEmit; + reactNamespace?: string; listFiles?: boolean; locale?: string; mapRoot?: string; @@ -1364,7 +1489,14 @@ declare namespace ts { noImplicitReturns?: boolean; noFallthroughCasesInSwitch?: boolean; forceConsistentCasingInFileNames?: boolean; - [option: string]: string | number | boolean; + baseUrl?: string; + paths?: PathSubstitutions; + rootDirs?: RootPaths; + traceModuleResolution?: boolean; + allowSyntheticDefaultImports?: boolean; + allowJs?: boolean; + noImplicitUseStrict?: boolean; + [option: string]: string | number | boolean | TsConfigOnlyOptions; } enum ModuleKind { None = 0, @@ -1388,6 +1520,13 @@ declare namespace ts { line: number; character: number; } + enum ScriptKind { + Unknown = 0, + JS = 1, + JSX = 2, + TS = 3, + TSX = 4, + } enum ScriptTarget { ES3 = 0, ES5 = 1, @@ -1407,6 +1546,8 @@ declare namespace ts { interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string; + trace?(s: string): void; + directoryExists?(directoryName: string): boolean; } interface ResolvedModule { resolvedFileName: string; @@ -1437,6 +1578,8 @@ declare namespace ts { } } declare namespace ts { + type FileWatcherCallback = (path: string, removed?: boolean) => void; + type DirectoryWatcherCallback = (path: string) => void; interface System { args: string[]; newLine: string; @@ -1444,8 +1587,8 @@ declare namespace ts { write(s: string): void; readFile(path: string, encoding?: string): string; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: (path: string, removed?: boolean) => void): FileWatcher; - watchDirectory?(path: string, callback: (path: string) => void, recursive?: boolean): FileWatcher; + watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher; + watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; fileExists(path: string): boolean; directoryExists(path: string): boolean; @@ -1459,6 +1602,10 @@ declare namespace ts { interface FileWatcher { close(): void; } + interface DirectoryWatcher extends FileWatcher { + directoryPath: Path; + referenceCount: number; + } var sys: System; } declare namespace ts { @@ -1483,6 +1630,7 @@ declare namespace ts { scanJsxIdentifier(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; + scanJSDocToken(): SyntaxKind; scan(): SyntaxKind; setText(text: string, start?: number, length?: number): void; setOnError(onError: ErrorCallback): void; @@ -1490,6 +1638,7 @@ declare namespace ts { setLanguageVariant(variant: LanguageVariant): void; setTextPos(textPos: number): void; lookAhead(callback: () => T): T; + scanRange(start: number, length: number, callback: () => T): T; tryScan(callback: () => T): T; } function tokenToString(t: SyntaxKind): string; @@ -1535,20 +1684,20 @@ declare namespace ts { */ function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; + function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; } declare namespace ts { - function getNodeConstructor(kind: SyntaxKind): new (pos?: number, end?: number) => Node; function createNode(kind: SyntaxKind, pos?: number, end?: number): 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 createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { const version: string; - function findConfigFile(searchPath: string): string; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1581,15 +1730,15 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; - function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string): { + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string): ParsedCommandLine; + function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; } declare namespace ts { /** The version of the language service API */ - let servicesVersion: string; + const servicesVersion: string; interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; @@ -1658,7 +1807,7 @@ declare namespace ts { /** Releases all resources held by this script snapshot */ dispose?(): void; } - module ScriptSnapshot { + namespace ScriptSnapshot { function fromString(text: string): IScriptSnapshot; } interface PreProcessedFileInfo { @@ -1675,6 +1824,7 @@ declare namespace ts { getNewLine?(): string; getProjectVersion?(): string; getScriptFileNames(): string[]; + getScriptKind?(fileName: string): ScriptKind; getScriptVersion(fileName: string): string; getScriptSnapshot(fileName: string): IScriptSnapshot; getLocalizedDiagnosticMessages?(): any; @@ -1686,6 +1836,7 @@ declare namespace ts { error?(s: string): void; useCaseSensitiveFileNames?(): boolean; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + directoryExists?(directoryName: string): boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -1781,7 +1932,7 @@ declare namespace ts { fileName: string; highlightSpans: HighlightSpan[]; } - module HighlightSpanKind { + namespace HighlightSpanKind { const none: string; const definition: string; const reference: string; @@ -1823,6 +1974,7 @@ declare namespace ts { InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; [s: string]: boolean | number | string; @@ -2041,7 +2193,7 @@ declare namespace ts { * @parm version Current version of the file. Only used if the file was not found * in the registry and a new one was created. */ - acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; /** * Request an updated version of an already existing SourceFile with a given fileName * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile @@ -2054,7 +2206,7 @@ declare namespace ts { * @param scriptSnapshot Text of the file. * @param version Current version of the file. */ - updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; /** * Informs the DocumentRegistry that a file is not needed any longer. * @@ -2067,7 +2219,7 @@ declare namespace ts { releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; reportStats(): string; } - module ScriptElementKind { + namespace ScriptElementKind { const unknown: string; const warning: string; const keyword: string; @@ -2098,7 +2250,7 @@ declare namespace ts { const constElement: string; const letElement: string; } - module ScriptElementKindModifier { + namespace ScriptElementKindModifier { const none: string; const publicMemberModifier: string; const privateMemberModifier: string; @@ -2126,6 +2278,12 @@ declare namespace ts { static typeAliasName: string; static parameterName: string; static docCommentTagName: string; + static jsxOpenTagName: string; + static jsxCloseTagName: string; + static jsxSelfClosingTagName: string; + static jsxAttribute: string; + static jsxText: string; + static jsxAttributeStringLiteralValue: string; } enum ClassificationType { comment = 1, @@ -2146,6 +2304,12 @@ declare namespace ts { typeAliasName = 16, parameterName = 17, docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, } interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; @@ -2166,12 +2330,11 @@ declare namespace ts { } function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; 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; + function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; - function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; + function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; function createClassifier(): Classifier; /** diff --git a/lib/typescript.js b/lib/typescript.js index 8b0ef04f96e..8dafad54257 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -13,6 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +var __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 ts; (function (ts) { // token > SyntaxKind.Identifer => token is a keyword @@ -156,187 +161,191 @@ var ts; SyntaxKind[SyntaxKind["IsKeyword"] = 124] = "IsKeyword"; SyntaxKind[SyntaxKind["ModuleKeyword"] = 125] = "ModuleKeyword"; SyntaxKind[SyntaxKind["NamespaceKeyword"] = 126] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 127] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 128] = "NumberKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 129] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 130] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 131] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 132] = "TypeKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 133] = "FromKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 134] = "OfKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 127] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 128] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 129] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 130] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 131] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 132] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 133] = "TypeKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 134] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 135] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 136] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 135] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 136] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 137] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 138] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 137] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 138] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 139] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 139] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 140] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 141] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 140] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 141] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 142] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 143] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 144] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 145] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 146] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 147] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 148] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 149] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 142] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 143] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 144] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 145] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 146] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 147] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 148] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 149] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 150] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 151] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 150] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 151] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 152] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 153] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 154] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 155] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 156] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 157] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 158] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 159] = "IntersectionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 160] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 152] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 153] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 154] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 155] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 156] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 157] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 158] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 159] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 160] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 161] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 162] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 163] = "ThisType"; + SyntaxKind[SyntaxKind["StringLiteralType"] = 164] = "StringLiteralType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 161] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 162] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 163] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 165] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 166] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 167] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 164] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 165] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 166] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 167] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 168] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 169] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 170] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 171] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 172] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 173] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 174] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 175] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 176] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 177] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 178] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 179] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 180] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 181] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 182] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 183] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 184] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElementExpression"] = 185] = "SpreadElementExpression"; - SyntaxKind[SyntaxKind["ClassExpression"] = 186] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 187] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 188] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 189] = "AsExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 168] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 169] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 170] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 171] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 172] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 173] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 174] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 175] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 176] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 177] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 178] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 179] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 180] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 181] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 182] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 183] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 184] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 185] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 186] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 187] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 188] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElementExpression"] = 189] = "SpreadElementExpression"; + SyntaxKind[SyntaxKind["ClassExpression"] = 190] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 191] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 192] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 193] = "AsExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 190] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 191] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 194] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 195] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 192] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 193] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 194] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 195] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 196] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 197] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 198] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 199] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 200] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 201] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 202] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 203] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 204] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 205] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 206] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 207] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 208] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 209] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 210] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 211] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 212] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 213] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 214] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 215] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 216] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 217] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 218] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 219] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 220] = "CaseBlock"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 221] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 222] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 223] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 224] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 225] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 226] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 227] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 228] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 229] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 230] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 231] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 196] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 197] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 198] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 199] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 200] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 201] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 202] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 203] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 204] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 205] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 206] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 207] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 208] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 209] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 210] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 211] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 212] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 213] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 214] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 215] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 216] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 217] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 218] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 219] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 220] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 221] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 222] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 223] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 224] = "CaseBlock"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 225] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 226] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 227] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 228] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 229] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 230] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 231] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 232] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 233] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 234] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 235] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 232] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 236] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 233] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 234] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 235] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxText"] = 236] = "JsxText"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 237] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 238] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 239] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 240] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 237] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 238] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 239] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxText"] = 240] = "JsxText"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 241] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 242] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 243] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 244] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 241] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 242] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 243] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 244] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 245] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 246] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 247] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 248] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 245] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 246] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 249] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 250] = "ShorthandPropertyAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 247] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 251] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 248] = "SourceFile"; - // JSDoc nodes. - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 249] = "JSDocTypeExpression"; - // The * type. - SyntaxKind[SyntaxKind["JSDocAllType"] = 250] = "JSDocAllType"; - // The ? type. - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 251] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocArrayType"] = 252] = "JSDocArrayType"; - SyntaxKind[SyntaxKind["JSDocUnionType"] = 253] = "JSDocUnionType"; - SyntaxKind[SyntaxKind["JSDocTupleType"] = 254] = "JSDocTupleType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 255] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 256] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocRecordType"] = 257] = "JSDocRecordType"; - SyntaxKind[SyntaxKind["JSDocRecordMember"] = 258] = "JSDocRecordMember"; - SyntaxKind[SyntaxKind["JSDocTypeReference"] = 259] = "JSDocTypeReference"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 260] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 261] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 262] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocConstructorType"] = 263] = "JSDocConstructorType"; - SyntaxKind[SyntaxKind["JSDocThisType"] = 264] = "JSDocThisType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 265] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 266] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 267] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 268] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 269] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 270] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["SourceFile"] = 252] = "SourceFile"; + // JSDoc nodes + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 253] = "JSDocTypeExpression"; + // The * type + SyntaxKind[SyntaxKind["JSDocAllType"] = 254] = "JSDocAllType"; + // The ? type + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 255] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 256] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 257] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 258] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 259] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 260] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 261] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 262] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 263] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 264] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 265] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 266] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 267] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 268] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 269] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 270] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 271] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 272] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 273] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 274] = "JSDocTemplateTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 271] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 275] = "SyntaxList"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 272] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 276] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstReservedWord"] = 70] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 105] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 70] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 134] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 136] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 106] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 114] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 151] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 160] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 152] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 164] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 15] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 68] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 134] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 136] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -345,73 +354,58 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 14] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 25] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 68] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 135] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 137] = "FirstNode"; })(ts.SyntaxKind || (ts.SyntaxKind = {})); var SyntaxKind = ts.SyntaxKind; (function (NodeFlags) { NodeFlags[NodeFlags["None"] = 0] = "None"; - NodeFlags[NodeFlags["Export"] = 2] = "Export"; - NodeFlags[NodeFlags["Ambient"] = 4] = "Ambient"; - NodeFlags[NodeFlags["Public"] = 8] = "Public"; - NodeFlags[NodeFlags["Private"] = 16] = "Private"; - NodeFlags[NodeFlags["Protected"] = 32] = "Protected"; - NodeFlags[NodeFlags["Static"] = 64] = "Static"; + NodeFlags[NodeFlags["Export"] = 1] = "Export"; + NodeFlags[NodeFlags["Ambient"] = 2] = "Ambient"; + NodeFlags[NodeFlags["Public"] = 4] = "Public"; + NodeFlags[NodeFlags["Private"] = 8] = "Private"; + NodeFlags[NodeFlags["Protected"] = 16] = "Protected"; + NodeFlags[NodeFlags["Static"] = 32] = "Static"; + NodeFlags[NodeFlags["Readonly"] = 64] = "Readonly"; NodeFlags[NodeFlags["Abstract"] = 128] = "Abstract"; NodeFlags[NodeFlags["Async"] = 256] = "Async"; NodeFlags[NodeFlags["Default"] = 512] = "Default"; - NodeFlags[NodeFlags["MultiLine"] = 1024] = "MultiLine"; - NodeFlags[NodeFlags["Synthetic"] = 2048] = "Synthetic"; - NodeFlags[NodeFlags["DeclarationFile"] = 4096] = "DeclarationFile"; - NodeFlags[NodeFlags["Let"] = 8192] = "Let"; - NodeFlags[NodeFlags["Const"] = 16384] = "Const"; - NodeFlags[NodeFlags["OctalLiteral"] = 32768] = "OctalLiteral"; - NodeFlags[NodeFlags["Namespace"] = 65536] = "Namespace"; - NodeFlags[NodeFlags["ExportContext"] = 131072] = "ExportContext"; - NodeFlags[NodeFlags["ContainsThis"] = 262144] = "ContainsThis"; - NodeFlags[NodeFlags["HasImplicitReturn"] = 524288] = "HasImplicitReturn"; - NodeFlags[NodeFlags["HasExplicitReturn"] = 1048576] = "HasExplicitReturn"; - NodeFlags[NodeFlags["Modifier"] = 1022] = "Modifier"; - NodeFlags[NodeFlags["AccessibilityModifier"] = 56] = "AccessibilityModifier"; - NodeFlags[NodeFlags["BlockScoped"] = 24576] = "BlockScoped"; - NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 1572864] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["Let"] = 1024] = "Let"; + NodeFlags[NodeFlags["Const"] = 2048] = "Const"; + NodeFlags[NodeFlags["Namespace"] = 4096] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 8192] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 16384] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 32768] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 65536] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 131072] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasClassExtends"] = 262144] = "HasClassExtends"; + NodeFlags[NodeFlags["HasDecorators"] = 524288] = "HasDecorators"; + NodeFlags[NodeFlags["HasParamDecorators"] = 1048576] = "HasParamDecorators"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 2097152] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 4194304] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 8388608] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 16777216] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 33554432] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 67108864] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 134217728] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 268435456] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 536870912] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["Modifier"] = 959] = "Modifier"; + NodeFlags[NodeFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + NodeFlags[NodeFlags["BlockScoped"] = 3072] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 98304] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["EmitHelperFlags"] = 3932160] = "EmitHelperFlags"; + // Parsing context flags + NodeFlags[NodeFlags["ContextFlags"] = 62914560] = "ContextFlags"; + // Exclude these flags when parsing a Type + NodeFlags[NodeFlags["TypeExcludesFlags"] = 41943040] = "TypeExcludesFlags"; })(ts.NodeFlags || (ts.NodeFlags = {})); var NodeFlags = ts.NodeFlags; - /* @internal */ - (function (ParserContextFlags) { - ParserContextFlags[ParserContextFlags["None"] = 0] = "None"; - // If this node was parsed in a context where 'in-expressions' are not allowed. - ParserContextFlags[ParserContextFlags["DisallowIn"] = 1] = "DisallowIn"; - // If this node was parsed in the 'yield' context created when parsing a generator. - ParserContextFlags[ParserContextFlags["Yield"] = 2] = "Yield"; - // If this node was parsed as part of a decorator - ParserContextFlags[ParserContextFlags["Decorator"] = 4] = "Decorator"; - // If this node was parsed in the 'await' context created when parsing an async function. - ParserContextFlags[ParserContextFlags["Await"] = 8] = "Await"; - // If the parser encountered an error when parsing the code that created this node. Note - // the parser only sets this directly on the node it creates right after encountering the - // error. - ParserContextFlags[ParserContextFlags["ThisNodeHasError"] = 16] = "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"] = 32] = "JavaScriptFile"; - // Context flags set directly by the parser. - ParserContextFlags[ParserContextFlags["ParserGeneratedFlags"] = 31] = "ParserGeneratedFlags"; - // Exclude these flags when parsing a Type - ParserContextFlags[ParserContextFlags["TypeExcludesFlags"] = 10] = "TypeExcludesFlags"; - // 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"; - // Used to know if we've computed data from children and cached it in this node. - ParserContextFlags[ParserContextFlags["HasAggregatedChildData"] = 128] = "HasAggregatedChildData"; - })(ts.ParserContextFlags || (ts.ParserContextFlags = {})); - var ParserContextFlags = ts.ParserContextFlags; (function (JsxFlags) { JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; - JsxFlags[JsxFlags["ClassElement"] = 4] = "ClassElement"; - JsxFlags[JsxFlags["UnknownElement"] = 8] = "UnknownElement"; JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; })(ts.JsxFlags || (ts.JsxFlags = {})); var JsxFlags = ts.JsxFlags; @@ -426,7 +420,7 @@ var ts; function OperationCanceledException() { } return OperationCanceledException; - })(); + }()); ts.OperationCanceledException = OperationCanceledException; /** Return code used by getEmitOutput function to indicate status of the function */ (function (ExitStatus) { @@ -472,6 +466,11 @@ var ts; SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); var SymbolAccessibility = ts.SymbolAccessibility; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(ts.TypePredicateKind || (ts.TypePredicateKind = {})); + var TypePredicateKind = ts.TypePredicateKind; /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator * metadata */ /* @internal */ @@ -573,21 +572,20 @@ var ts; NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; - NodeCheckFlags[NodeCheckFlags["EmitExtends"] = 8] = "EmitExtends"; - NodeCheckFlags[NodeCheckFlags["EmitDecorate"] = 16] = "EmitDecorate"; - NodeCheckFlags[NodeCheckFlags["EmitParam"] = 32] = "EmitParam"; - NodeCheckFlags[NodeCheckFlags["EmitAwaiter"] = 64] = "EmitAwaiter"; - NodeCheckFlags[NodeCheckFlags["EmitGenerator"] = 128] = "EmitGenerator"; NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["LexicalArguments"] = 2048] = "LexicalArguments"; - NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 4096] = "CaptureArguments"; - // Values for enum members have been computed, and any errors have been reported for them. - NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 8192] = "EnumValuesComputed"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 16384] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; - NodeCheckFlags[NodeCheckFlags["LoopWithBlockScopedBindingCapturedInFunction"] = 65536] = "LoopWithBlockScopedBindingCapturedInFunction"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var NodeCheckFlags = ts.NodeCheckFlags; (function (TypeFlags) { @@ -622,6 +620,7 @@ var ts; TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol"; TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType"; + TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties"; /* @internal */ TypeFlags[TypeFlags["Intrinsic"] = 16777343] = "Intrinsic"; /* @internal */ @@ -647,6 +646,19 @@ var ts; IndexKind[IndexKind["Number"] = 1] = "Number"; })(ts.IndexKind || (ts.IndexKind = {})); var IndexKind = ts.IndexKind; + /* @internal */ + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + /// exports.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + })(ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + var SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; @@ -679,6 +691,14 @@ var ts; NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; })(ts.NewLineKind || (ts.NewLineKind = {})); var NewLineKind = ts.NewLineKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + })(ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptKind = ts.ScriptKind; (function (ScriptTarget) { ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; @@ -1067,9 +1087,11 @@ var ts; var count = array.length; if (count > 0) { var pos = 0; - var result = arguments.length <= 2 ? array[pos++] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos++; while (pos < count) { - result = f(result, array[pos++]); + result = f(result, array[pos]); + pos++; } return result; } @@ -1081,9 +1103,11 @@ var ts; if (array) { var pos = array.length - 1; if (pos >= 0) { - var result = arguments.length <= 2 ? array[pos--] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos--; while (pos >= 0) { - result = f(result, array[pos--]); + result = f(result, array[pos]); + pos--; } return result; } @@ -1176,6 +1200,32 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + /** + * Reduce the properties of a map. + * + * @param map The map to reduce + * @param callback An aggregation function that is called for each entry in the map + * @param initial The initial value for the reduction. + */ + function reduceProperties(map, callback, initial) { + var result = initial; + if (map) { + for (var key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } + } + return result; + } + ts.reduceProperties = reduceProperties; + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; function memoize(callback) { var value; return function () { @@ -1220,6 +1270,15 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; + /* internal */ + function formatMessage(dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; function createCompilerDiagnostic(message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 1) { @@ -1422,7 +1481,7 @@ var ts; } ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; function getNormalizedPathComponentsOfUrl(url) { - // Get root length of http://www.website.com/folder1/foler2/ + // Get root length of http://www.website.com/folder1/folder2/ // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; @@ -1447,7 +1506,7 @@ var ts; var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); if (indexOfNextSlash !== -1) { // Found the "/" after the website.com so the root is length of http://www.website.com/ - // and get components afetr the root normally like any other folder components + // and get components after the root normally like any other folder components rootLength = indexOfNextSlash + 1; return normalizedPathComponents(url, rootLength); } @@ -1476,7 +1535,8 @@ var ts; directoryComponents.length--; } // Find the component that differs - for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { + var joinStartIndex; + for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { break; } @@ -1501,7 +1561,7 @@ var ts; } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; function getBaseFileName(path) { - if (!path) { + if (path === undefined) { return undefined; } var i = path.lastIndexOf(ts.directorySeparator); @@ -1529,19 +1589,19 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedExtensions = [".ts", ".tsx", ".d.ts"]; - /** - * List of extensions that will be used to look for external modules. - * This list is kept separate from supportedExtensions to for cases when we'll allow to include .js files in compilation, - * but still would like to load only TypeScript files as modules - */ - ts.moduleFileExtensions = ts.supportedExtensions; - function isSupportedSourceFileName(fileName) { + ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedJavascriptExtensions = [".js", ".jsx"]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options) { + return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + ts.getSupportedExtensions = getSupportedExtensions; + function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; } - for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; + for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -1560,22 +1620,6 @@ var ts; return path; } ts.removeFileExtension = removeFileExtension; - var backslashOrDoubleQuote = /[\"\\]/g; - var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { - "\0": "\\0", - "\t": "\\t", - "\v": "\\v", - "\f": "\\f", - "\b": "\\b", - "\r": "\\r", - "\n": "\\n", - "\\": "\\\\", - "\"": "\\\"", - "\u2028": "\\u2028", - "\u2029": "\\u2029", - "\u0085": "\\u0085" // nextLine - }; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -1586,17 +1630,16 @@ var ts; } function Signature(checker) { } + function Node(kind, pos, end) { + this.kind = kind; + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; + } ts.objectAllocator = { - getNodeConstructor: function (kind) { - function Node(pos, end) { - this.pos = pos; - this.end = end; - this.flags = 0 /* None */; - this.parent = undefined; - } - Node.prototype = { kind: kind }; - return Node; - }, + getNodeConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } @@ -1627,7 +1670,7 @@ var ts; } Debug.assert = assert; function fail(message) { - Debug.assert(false, message); + Debug.assert(/*expression*/ false, message); } Debug.fail = fail; })(Debug = ts.Debug || (ts.Debug = {})); @@ -1642,6 +1685,12 @@ var ts; return copiedList; } ts.copyListRemovingItem = copyListRemovingItem; + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; })(ts || (ts = {})); /// var ts; @@ -1788,10 +1837,9 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); - var _tty = require("tty"); // average async stat takes about 30 microseconds // set chunk size to do 30 files in < 1 millisecond - function createWatchedFileSet(interval, chunkSize) { + function createPollingWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } if (chunkSize === void 0) { chunkSize = 30; } var watchedFiles = []; @@ -1805,13 +1853,13 @@ var ts; if (!watchedFile) { return; } - _fs.stat(watchedFile.fileName, function (err, stats) { + _fs.stat(watchedFile.filePath, function (err, stats) { if (err) { - watchedFile.callback(watchedFile.fileName); + watchedFile.callback(watchedFile.filePath); } else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) { - watchedFile.mtime = getModifiedTime(watchedFile.fileName); - watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0); + watchedFile.mtime = getModifiedTime(watchedFile.filePath); + watchedFile.callback(watchedFile.filePath, watchedFile.mtime.getTime() === 0); } }); } @@ -1837,11 +1885,11 @@ var ts; nextFileToCheck = nextToCheck; }, interval); } - function addFile(fileName, callback) { + function addFile(filePath, callback) { var file = { - fileName: fileName, + filePath: filePath, callback: callback, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(filePath) }; watchedFiles.push(file); if (watchedFiles.length === 1) { @@ -1860,10 +1908,79 @@ var ts; removeFile: removeFile }; } + function createWatchedFileSet() { + var dirWatchers = ts.createFileMap(); + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createFileMap(); + return { addFile: addFile, removeFile: removeFile }; + function reduceDirWatcherRefCountForFile(filePath) { + var dirPath = ts.getDirectoryPath(filePath); + if (dirWatchers.contains(dirPath)) { + var watcher = dirWatchers.get(dirPath); + watcher.referenceCount -= 1; + if (watcher.referenceCount <= 0) { + watcher.close(); + dirWatchers.remove(dirPath); + } + } + } + function addDirWatcher(dirPath) { + if (dirWatchers.contains(dirPath)) { + var watcher_1 = dirWatchers.get(dirPath); + watcher_1.referenceCount += 1; + return; + } + var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher.referenceCount = 1; + dirWatchers.set(dirPath, watcher); + return; + } + function addFileWatcherCallback(filePath, callback) { + if (fileWatcherCallbacks.contains(filePath)) { + fileWatcherCallbacks.get(filePath).push(callback); + } + else { + fileWatcherCallbacks.set(filePath, [callback]); + } + } + function addFile(filePath, callback) { + addFileWatcherCallback(filePath, callback); + addDirWatcher(ts.getDirectoryPath(filePath)); + return { filePath: filePath, callback: callback }; + } + function removeFile(watchedFile) { + removeFileWatcherCallback(watchedFile.filePath, watchedFile.callback); + reduceDirWatcherRefCountForFile(watchedFile.filePath); + } + function removeFileWatcherCallback(filePath, callback) { + if (fileWatcherCallbacks.contains(filePath)) { + var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks.get(filePath)); + if (newCallbacks.length === 0) { + fileWatcherCallbacks.remove(filePath); + } + else { + fileWatcherCallbacks.set(filePath, newCallbacks); + } + } + } + function fileEventHandler(eventName, relativeFileName, baseDirPath) { + // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" + var filePath = typeof relativeFileName !== "string" + ? undefined + : ts.toPath(relativeFileName, baseDirPath, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)); + // Some applications save a working file via rename operations + if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks.contains(filePath)) { + for (var _i = 0, _a = fileWatcherCallbacks.get(filePath); _i < _a.length; _i++) { + var fileCallback = _a[_i]; + fileCallback(filePath); + } + } + } + } // REVIEW: for now this implementation uses polling. // The advantage of polling is that it works reliably // on all os and with network mounted files. - // For 90 referenced files, the average time to detect + // For 90 referenced files, the average time to detect // changes is 2*msInterval (by default 5 seconds). // The overhead of this is .04 percent (1/2500) with // average pause of < 1 millisecond (and max @@ -1873,6 +1990,7 @@ var ts; // changes for large reference sets? If so, do we want // to increase the chunk size or decrease the interval // time dynamically to match the large reference set? + var pollingWatchedFileSet = createPollingWatchedFileSet(); var watchedFileSet = createWatchedFileSet(); function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; @@ -1881,7 +1999,7 @@ var ts; // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; function readFile(fileName, encoding) { - if (!_fs.existsSync(fileName)) { + if (!fileExists(fileName)) { return undefined; } var buffer = _fs.readFileSync(fileName); @@ -1913,10 +2031,42 @@ var ts; if (writeByteOrderMark) { data = "\uFEFF" + data; } - _fs.writeFileSync(fileName, data, "utf8"); + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } } function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path.toLowerCase() : path; + return useCaseSensitiveFileNames ? path : path.toLowerCase(); + } + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + function fileSystemEntryExists(path, entryKind) { + try { + var stat = _fs.statSync(path); + switch (entryKind) { + case 0 /* File */: return stat.isFile(); + case 1 /* Directory */: return stat.isDirectory(); + } + } + catch (e) { + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0 /* File */); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1 /* Directory */); } function readDirectory(path, extension, exclude) { var result = []; @@ -1956,24 +2106,28 @@ var ts; }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { - // Node 4.0 stablized the `fs.watch` function on Windows which avoids polling + watchFile: function (filePath, callback) { + // Node 4.0 stabilized the `fs.watch` function on Windows which avoids polling // and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649 // and https://github.com/Microsoft/TypeScript/issues/4643), therefore // if the current node.js version is newer than 4, use `fs.watch` instead. - if (isNode4OrLater()) { - // Note: in node the callback of fs.watch is given only the relative file name as a parameter - return _fs.watch(fileName, function (eventName, relativeFileName) { return callback(fileName); }); - } - var watchedFile = watchedFileSet.addFile(fileName, callback); + var watchSet = isNode4OrLater() ? watchedFileSet : pollingWatchedFileSet; + var watchedFile = watchSet.addFile(filePath, callback); return { - close: function () { return watchedFileSet.removeFile(watchedFile); } + close: function () { return watchSet.removeFile(watchedFile); } }; }, watchDirectory: function (path, callback, recursive) { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) - return _fs.watch(path, { persistent: true, recursive: !!recursive }, function (eventName, relativeFileName) { + var options; + if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + return _fs.watch(path, options, function (eventName, relativeFileName) { // In watchDirectory we only care about adding and removing files (when event name is // "rename"); changes made within files are handled by corresponding fileWatchers (when // event name is "change") @@ -1987,12 +2141,8 @@ var ts; resolvePath: function (path) { return _path.resolve(path); }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); - }, + fileExists: fileExists, + directoryExists: directoryExists, createDirectory: function (directoryName) { if (!this.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); @@ -2016,6 +2166,33 @@ var ts; } }; } + function getChakraSystem() { + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, encoding) { + // encoding is automatically handled by the implementation in ChakraHost + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = "\uFEFF" + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + readDirectory: ChakraHost.readDirectory, + exit: ChakraHost.quit + }; + } if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { return getWScriptSystem(); } @@ -2024,6 +2201,9 @@ var ts; // process.browser check excludes webpack and browserify return getNodeSystem(); } + else if (typeof ChakraHost !== "undefined") { + return getChakraSystem(); + } else { return undefined; // Unsupported host } @@ -2052,6 +2232,7 @@ var ts; An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_a_type_annotation_1021", message: "An index signature must have a type annotation." }, An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_must_have_a_type_annotation_1022", message: "An index signature parameter must have a type annotation." }, An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_type_must_be_string_or_number_1023", message: "An index signature parameter type must be 'string' or 'number'." }, + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: { code: 1024, category: ts.DiagnosticCategory.Error, key: "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", message: "'readonly' modifier can only appear on a property declaration or index signature." }, Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility_modifier_already_seen_1028", message: "Accessibility modifier already seen." }, _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{0}' modifier already seen." }, @@ -2065,7 +2246,7 @@ var ts; _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_a_class_declaration_1041", message: "'{0}' modifier cannot be used with a class declaration." }, _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_here_1042", message: "'{0}' modifier cannot be used here." }, _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_data_property_1043", message: "'{0}' modifier cannot appear on a data property." }, - _0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_element_1044", message: "'{0}' modifier cannot appear on a module element." }, + _0_modifier_cannot_appear_on_a_module_or_namespace_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", message: "'{0}' modifier cannot appear on a module or namespace element." }, A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", message: "A '{0}' modifier cannot be used with an interface declaration." }, A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", message: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_be_optional_1047", message: "A rest parameter cannot be optional." }, @@ -2084,8 +2265,11 @@ var ts; Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." }, _0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "{0} is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." }, + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." }, Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", message: "Unexpected token. A constructor, method, accessor, or property was expected." }, + _0_modifier_cannot_appear_on_a_type_member: { code: 1070, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_type_member_1070", message: "'{0}' modifier cannot appear on a type member." }, + _0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." }, A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." }, Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." }, Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher." }, @@ -2141,10 +2325,9 @@ var ts; String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, - Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: ts.DiagnosticCategory.Error, key: "Modifiers_not_permitted_on_index_signature_members_1145", message: "Modifiers not permitted on index signature members." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_1148", message: "Cannot compile modules unless the '--module' flag is provided." }, + Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting__1148", message: "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -2204,7 +2387,7 @@ var ts; Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_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_Speci_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning." }, + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_6_or_higher_1220", message: "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_1221", message: "Generators are not allowed in an ambient context." }, An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An_overload_signature_cannot_be_declared_as_a_generator_1222", message: "An overload signature cannot be declared as a generator." }, @@ -2227,10 +2410,14 @@ var ts; Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", message: "Unable to resolve signature of parameter decorator when called as an expression." }, Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", message: "Unable to resolve signature of property decorator when called as an expression." }, Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", message: "Unable to resolve signature of method decorator when called as an expression." }, - abstract_modifier_can_only_appear_on_a_class_or_method_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_or_method_declaration_1242", message: "'abstract' modifier can only appear on a class or method declaration." }, + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", message: "'abstract' modifier can only appear on a class, method, or property declaration." }, _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, + An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, + A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, + A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, @@ -2244,11 +2431,12 @@ var ts; Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list_2313", message: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." }, + Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, @@ -2258,6 +2446,7 @@ var ts; Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, + Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, @@ -2314,7 +2503,7 @@ var ts; get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", message: "Specialized overload signature is not assignable to any non-specialized signature." }, - Overload_signatures_must_all_be_exported_or_not_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_not_exported_2383", message: "Overload signatures must all be exported or not exported." }, + Overload_signatures_must_all_be_exported_or_non_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_non_exported_2383", message: "Overload signatures must all be exported or non-exported." }, Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", message: "Overload signatures must all be ambient or non-ambient." }, Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_public_private_or_protected_2385", message: "Overload signatures must all be public, private or protected." }, Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_optional_or_required_2386", message: "Overload signatures must all be optional or required." }, @@ -2328,6 +2517,7 @@ var ts; Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, @@ -2346,7 +2536,6 @@ var ts; Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'" }, Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." }, Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0: { code: 2419, category: ts.DiagnosticCategory.Error, key: "Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0_2419", message: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." }, Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." }, A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_implement_another_class_or_interface_2422", message: "A class may only implement another class or interface." }, Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, @@ -2354,7 +2543,7 @@ var ts; Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'" }, - All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_interface_must_have_identical_type_parameters_2428", message: "All declarations of an interface must have identical type parameters." }, + All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." }, Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'" }, In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, @@ -2374,8 +2563,8 @@ var ts; Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_2449", message: "The operand of an increment or decrement operator cannot be a constant." }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_2450", message: "Left-hand side of assignment expression cannot be a constant." }, + The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property_2449", message: "The operand of an increment or decrement operator cannot be a constant or a read-only property." }, + Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property_2450", message: "Left-hand side of assignment expression cannot be a constant or a read-only property." }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, @@ -2408,8 +2597,8 @@ var ts; Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" }, - The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant_2485", message: "The left-hand side of a 'for...of' statement cannot be a previously defined constant." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant_2486", message: "The left-hand side of a 'for...in' statement cannot be a previously defined constant." }, + The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property_2485", message: "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property." }, + The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property_2486", message: "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property." }, Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_of_statement_2487", message: "Invalid left-hand side in 'for...of' statement." }, Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, @@ -2435,12 +2624,13 @@ var ts; Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", message: "Base constructor return type '{0}' is not a class or interface type." }, Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base_constructors_must_all_have_the_same_return_type_2510", message: "Base constructors must all have the same return type." }, Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot_create_an_instance_of_the_abstract_class_0_2511", message: "Cannot create an instance of the abstract class '{0}'." }, - Overload_signatures_must_all_be_abstract_or_not_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_not_abstract_2512", message: "Overload signatures must all be abstract or not abstract." }, + Overload_signatures_must_all_be_abstract_or_non_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", message: "Overload signatures must all be abstract or non-abstract." }, Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", message: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes_containing_abstract_methods_must_be_marked_abstract_2514", message: "Classes containing abstract methods must be marked abstract." }, Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, @@ -2450,7 +2640,9 @@ var ts; A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_must_be_an_object_type_2600", message: "JSX element attributes type '{0}' must be an object type." }, + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, + Property_0_is_incompatible_with_index_signature: { code: 2530, category: ts.DiagnosticCategory.Error, key: "Property_0_is_incompatible_with_index_signature_2530", message: "Property '{0}' is incompatible with index signature." }, + JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'" }, @@ -2466,6 +2658,25 @@ var ts; Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element" }, + Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'" }, + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, + Cannot_re_export_name_that_is_not_defined_in_the_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_name_that_is_not_defined_in_the_module_2661", message: "Cannot re-export name that is not defined in the module." }, + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, + Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope_2665", message: "Module augmentation cannot introduce new names in the top level scope." }, + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: { code: 2672, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", message: "Cannot assign a '{0}' constructor type to a '{1}' constructor type." }, + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: { code: 2673, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", message: "Constructor of class '{0}' is private and only accessible within the class declaration." }, + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: { code: 2674, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", message: "Constructor of class '{0}' is protected and only accessible within the class declaration." }, + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: { code: 2675, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", message: "Cannot extend a class '{0}'. Class constructor is marked as private." }, + Accessors_must_both_be_abstract_or_non_abstract: { code: 2676, category: ts.DiagnosticCategory.Error, key: "Accessors_must_both_be_abstract_or_non_abstract_2676", message: "Accessors must both be abstract or non-abstract." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2550,6 +2761,14 @@ var ts; Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, + Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'" }, + The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'" }, + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." }, + Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, + Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character" }, + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character" }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -2560,6 +2779,7 @@ var ts; Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -2582,7 +2802,7 @@ var ts; Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." }, - Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015_6046", message: "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', or 'es2015'." }, + Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none_6046", message: "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'none'." }, Argument_for_target_option_must_be_ES3_ES5_or_ES2015: { code: 6047, category: ts.DiagnosticCategory.Error, key: "Argument_for_target_option_must_be_ES3_ES5_or_ES2015_6047", message: "Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'." }, Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form or -. For example '{0}' or '{1}'." }, Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." }, @@ -2599,6 +2819,7 @@ var ts; NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "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_6062", message: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Argument_for_moduleResolution_option_must_be_node_or_classic: { code: 6063, category: ts.DiagnosticCategory.Error, key: "Argument_for_moduleResolution_option_must_be_node_or_classic_6063", message: "Argument for '--moduleResolution' option must be 'node' or 'classic'." }, + Option_0_can_only_be_specified_in_tsconfig_json_file: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", message: "Option '{0}' can only be specified in 'tsconfig.json' file." }, Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, @@ -2614,6 +2835,37 @@ var ts; Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, + Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, + Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." }, + Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit_6084", message: "Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit" }, + Enable_tracing_of_the_module_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_module_resolution_process_6085", message: "Enable tracing of the module resolution process." }, + Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" }, + Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." }, + Module_resolution_kind_is_not_specified_using_0: { code: 6088, category: ts.DiagnosticCategory.Message, key: "Module_resolution_kind_is_not_specified_using_0_6088", message: "Module resolution kind is not specified, using '{0}'." }, + Module_name_0_was_successfully_resolved_to_1: { code: 6089, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_successfully_resolved_to_1_6089", message: "======== Module name '{0}' was successfully resolved to '{1}'. ========" }, + Module_name_0_was_not_resolved: { code: 6090, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_not_resolved_6090", message: "======== Module name '{0}' was not resolved. ========" }, + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: { code: 6091, category: ts.DiagnosticCategory.Message, key: "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", message: "'paths' option is specified, looking for a pattern to match module name '{0}'." }, + Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." }, + Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." }, + Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." }, + Loading_module_as_file_Slash_folder_candidate_module_location_0: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_6095", message: "Loading module as file / folder, candidate module location '{0}'." }, + File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." }, + File_0_exist_use_it_as_a_module_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_module_resolution_result_6097", message: "File '{0}' exist - use it as a module resolution result." }, + Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." }, + Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, + package_json_does_not_have_typings_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_typings_field_6100", message: "'package.json' does not have 'typings' field." }, + package_json_has_typings_field_0_that_references_1: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_typings_field_0_that_references_1_6101", message: "'package.json' has 'typings' field '{0}' that references '{1}'." }, + Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, + Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, + Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." }, + Expected_type_of_typings_field_in_package_json_to_be_string_got_0: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_typings_field_in_package_json_to_be_string_got_0_6105", message: "Expected type of 'typings' field in 'package.json' to be 'string', got '{0}'." }, + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'" }, + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'" }, + Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'" }, + Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'" }, + Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'" }, + Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed" }, + Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2621,6 +2873,7 @@ var ts; _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", message: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, @@ -2651,7 +2904,6 @@ var ts; 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_8014", message: "'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_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, - 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_8017", message: "'decorators' can only be used in a .ts file." }, 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_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, @@ -2661,7 +2913,9 @@ var ts; Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'" }, An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." } + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, + JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." } }; })(ts || (ts = {})); /// @@ -2697,7 +2951,7 @@ var ts; "false": 84 /* FalseKeyword */, "finally": 85 /* FinallyKeyword */, "for": 86 /* ForKeyword */, - "from": 133 /* FromKeyword */, + "from": 134 /* FromKeyword */, "function": 87 /* FunctionKeyword */, "get": 123 /* GetKeyword */, "if": 88 /* IfKeyword */, @@ -2712,24 +2966,26 @@ var ts; "namespace": 126 /* NamespaceKeyword */, "new": 92 /* NewKeyword */, "null": 93 /* NullKeyword */, - "number": 128 /* NumberKeyword */, + "number": 129 /* NumberKeyword */, "package": 109 /* PackageKeyword */, "private": 110 /* PrivateKeyword */, "protected": 111 /* ProtectedKeyword */, "public": 112 /* PublicKeyword */, - "require": 127 /* RequireKeyword */, + "readonly": 127 /* ReadonlyKeyword */, + "require": 128 /* RequireKeyword */, + "global": 135 /* GlobalKeyword */, "return": 94 /* ReturnKeyword */, - "set": 129 /* SetKeyword */, + "set": 130 /* SetKeyword */, "static": 113 /* StaticKeyword */, - "string": 130 /* StringKeyword */, + "string": 131 /* StringKeyword */, "super": 95 /* SuperKeyword */, "switch": 96 /* SwitchKeyword */, - "symbol": 131 /* SymbolKeyword */, + "symbol": 132 /* SymbolKeyword */, "this": 97 /* ThisKeyword */, "throw": 98 /* ThrowKeyword */, "true": 99 /* TrueKeyword */, "try": 100 /* TryKeyword */, - "type": 132 /* TypeKeyword */, + "type": 133 /* TypeKeyword */, "typeof": 101 /* TypeOfKeyword */, "var": 102 /* VarKeyword */, "void": 103 /* VoidKeyword */, @@ -2738,7 +2994,7 @@ var ts; "yield": 114 /* YieldKeyword */, "async": 118 /* AsyncKeyword */, "await": 119 /* AwaitKeyword */, - "of": 134 /* OfKeyword */, + "of": 136 /* OfKeyword */, "{": 15 /* OpenBraceToken */, "}": 16 /* CloseBraceToken */, "(": 17 /* OpenParenToken */, @@ -2901,7 +3157,8 @@ var ts; var pos = 0; var lineStart = 0; while (pos < text.length) { - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 13 /* carriageReturn */: if (text.charCodeAt(pos) === 10 /* lineFeed */) { @@ -3035,6 +3292,11 @@ var ts; ts.couldStartTrivia = couldStartTrivia; /* @internal */ function skipTrivia(text, pos, stopAfterLineBreak) { + // Using ! with a greater than test is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + if (!(pos >= 0)) { + return pos; + } // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -3104,7 +3366,7 @@ var ts; } ts.skipTrivia = skipTrivia; // All conflict markers consist of the same character repeated seven times. If it is - // a <<<<<<< or >>>>>>> marker then it is also followd by a space. + // a <<<<<<< or >>>>>>> marker then it is also followed by a space. var mergeConflictMarkerLength = "<<<<<<<".length; function isConflictMarkerTrivia(text, pos) { ts.Debug.assert(pos >= 0); @@ -3136,7 +3398,7 @@ var ts; } else { ts.Debug.assert(ch === 61 /* equals */); - // Consume everything from the start of the mid-conlict marker to the start of the next + // Consume everything from the start of the mid-conflict marker to the start of the next // end-conflict marker. while (pos < len) { var ch_1 = text.charCodeAt(pos); @@ -3173,7 +3435,7 @@ var ts; function getCommentRanges(text, pos, trailing) { var result; var collecting = trailing || pos === 0; - while (true) { + while (pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13 /* carriageReturn */: @@ -3242,6 +3504,7 @@ var ts; } return result; } + return result; } function getLeadingCommentRanges(text, pos) { return getCommentRanges(text, pos, /*trailing*/ false); @@ -3270,6 +3533,19 @@ var ts; ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; + /* @internal */ + function isIdentifier(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1, n = name.length; i < n; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifier = isIdentifier; // Creates a scanner over a (possibly unspecified) range of a piece of text. function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } @@ -3305,6 +3581,7 @@ var ts; scanJsxIdentifier: scanJsxIdentifier, reScanJsxToken: reScanJsxToken, scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, scan: scan, setText: setText, setScriptTarget: setScriptTarget, @@ -3312,7 +3589,8 @@ var ts; setOnError: setOnError, setTextPos: setTextPos, tryScan: tryScan, - lookAhead: lookAhead + lookAhead: lookAhead, + scanRange: scanRange }; function error(message, length) { if (onError) { @@ -3343,7 +3621,7 @@ var ts; error(ts.Diagnostics.Digit_expected); } } - return +(text.substring(start, end)); + return "" + +(text.substring(start, end)); } function scanOctalDigits() { var start = pos; @@ -3392,7 +3670,8 @@ var ts; return value; } function scanString() { - var quote = text.charCodeAt(pos++); + var quote = text.charCodeAt(pos); + pos++; var result = ""; var start = pos; while (true) { @@ -3488,7 +3767,8 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); return ""; } - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 48 /* _0 */: return "\0"; @@ -3715,7 +3995,8 @@ var ts; } return pos += 2, token = 31 /* ExclamationEqualsToken */; } - return pos++, token = 49 /* ExclamationToken */; + pos++; + return token = 49 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); @@ -3726,7 +4007,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 62 /* PercentEqualsToken */; } - return pos++, token = 40 /* PercentToken */; + pos++; + return token = 40 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { return pos += 2, token = 51 /* AmpersandAmpersandToken */; @@ -3734,11 +4016,14 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 66 /* AmpersandEqualsToken */; } - return pos++, token = 46 /* AmpersandToken */; + pos++; + return token = 46 /* AmpersandToken */; case 40 /* openParen */: - return pos++, token = 17 /* OpenParenToken */; + pos++; + return token = 17 /* OpenParenToken */; case 41 /* closeParen */: - return pos++, token = 18 /* CloseParenToken */; + pos++; + return token = 18 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 59 /* AsteriskEqualsToken */; @@ -3749,7 +4034,8 @@ var ts; } return pos += 2, token = 38 /* AsteriskAsteriskToken */; } - return pos++, token = 37 /* AsteriskToken */; + pos++; + return token = 37 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { return pos += 2, token = 41 /* PlusPlusToken */; @@ -3757,9 +4043,11 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 57 /* PlusEqualsToken */; } - return pos++, token = 35 /* PlusToken */; + pos++; + return token = 35 /* PlusToken */; case 44 /* comma */: - return pos++, token = 24 /* CommaToken */; + pos++; + return token = 24 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { return pos += 2, token = 42 /* MinusMinusToken */; @@ -3767,16 +4055,18 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 58 /* MinusEqualsToken */; } - return pos++, token = 36 /* MinusToken */; + pos++; + return token = 36 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = "" + scanNumber(); + tokenValue = scanNumber(); return token = 8 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { return pos += 3, token = 22 /* DotDotDotToken */; } - return pos++, token = 21 /* DotToken */; + pos++; + return token = 21 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -3824,7 +4114,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 61 /* SlashEqualsToken */; } - return pos++, token = 39 /* SlashToken */; + pos++; + return token = 39 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; @@ -3873,12 +4164,14 @@ var ts; case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - tokenValue = "" + scanNumber(); + tokenValue = scanNumber(); return token = 8 /* NumericLiteral */; case 58 /* colon */: - return pos++, token = 54 /* ColonToken */; + pos++; + return token = 54 /* ColonToken */; case 59 /* semicolon */: - return pos++, token = 23 /* SemicolonToken */; + pos++; + return token = 23 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3903,7 +4196,8 @@ var ts; text.charCodeAt(pos + 2) !== 42 /* asterisk */) { return pos += 2, token = 26 /* LessThanSlashToken */; } - return pos++, token = 25 /* LessThanToken */; + pos++; + return token = 25 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3923,7 +4217,8 @@ var ts; if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { return pos += 2, token = 34 /* EqualsGreaterThanToken */; } - return pos++, token = 56 /* EqualsToken */; + pos++; + return token = 56 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3934,20 +4229,26 @@ var ts; return token = 7 /* ConflictMarkerTrivia */; } } - return pos++, token = 27 /* GreaterThanToken */; + pos++; + return token = 27 /* GreaterThanToken */; case 63 /* question */: - return pos++, token = 53 /* QuestionToken */; + pos++; + return token = 53 /* QuestionToken */; case 91 /* openBracket */: - return pos++, token = 19 /* OpenBracketToken */; + pos++; + return token = 19 /* OpenBracketToken */; case 93 /* closeBracket */: - return pos++, token = 20 /* CloseBracketToken */; + pos++; + return token = 20 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 68 /* CaretEqualsToken */; } - return pos++, token = 48 /* CaretToken */; + pos++; + return token = 48 /* CaretToken */; case 123 /* openBrace */: - return pos++, token = 15 /* OpenBraceToken */; + pos++; + return token = 15 /* OpenBraceToken */; case 124 /* bar */: if (text.charCodeAt(pos + 1) === 124 /* bar */) { return pos += 2, token = 52 /* BarBarToken */; @@ -3955,13 +4256,17 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 67 /* BarEqualsToken */; } - return pos++, token = 47 /* BarToken */; + pos++; + return token = 47 /* BarToken */; case 125 /* closeBrace */: - return pos++, token = 16 /* CloseBraceToken */; + pos++; + return token = 16 /* CloseBraceToken */; case 126 /* tilde */: - return pos++, token = 50 /* TildeToken */; + pos++; + return token = 50 /* TildeToken */; case 64 /* at */: - return pos++, token = 55 /* AtToken */; + pos++; + return token = 55 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -3970,7 +4275,8 @@ var ts; return token = getIdentifierToken(); } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0 /* Unknown */; + pos++; + return token = 0 /* Unknown */; default: if (isIdentifierStart(ch, languageVersion)) { pos++; @@ -3992,7 +4298,8 @@ var ts; continue; } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0 /* Unknown */; + pos++; + return token = 0 /* Unknown */; } } } @@ -4008,10 +4315,12 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 64 /* GreaterThanGreaterThanEqualsToken */; } - return pos++, token = 44 /* GreaterThanGreaterThanToken */; + pos++; + return token = 44 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { - return pos++, token = 29 /* GreaterThanEqualsToken */; + pos++; + return token = 29 /* GreaterThanEqualsToken */; } } return token; @@ -4103,7 +4412,7 @@ var ts; break; } } - return token = 236 /* JsxText */; + return token = 240 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -4123,6 +4432,55 @@ var ts; } return token; } + function scanJSDocToken() { + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + startPos = pos; + // Eat leading whitespace + var ch = text.charCodeAt(pos); + while (pos < end) { + ch = text.charCodeAt(pos); + if (isWhiteSpace(ch)) { + pos++; + } + else { + break; + } + } + tokenPos = pos; + switch (ch) { + case 64 /* at */: + return pos += 1, token = 55 /* AtToken */; + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + return pos += 1, token = 4 /* NewLineTrivia */; + case 42 /* asterisk */: + return pos += 1, token = 37 /* AsteriskToken */; + case 123 /* openBrace */: + return pos += 1, token = 15 /* OpenBraceToken */; + case 125 /* closeBrace */: + return pos += 1, token = 16 /* CloseBraceToken */; + case 91 /* openBracket */: + return pos += 1, token = 19 /* OpenBracketToken */; + case 93 /* closeBracket */: + return pos += 1, token = 20 /* CloseBracketToken */; + case 61 /* equals */: + return pos += 1, token = 56 /* EqualsToken */; + case 44 /* comma */: + return pos += 1, token = 24 /* CommaToken */; + } + if (isIdentifierStart(ch, 2 /* Latest */)) { + pos++; + while (isIdentifierPart(text.charCodeAt(pos), 2 /* Latest */) && pos < end) { + pos++; + } + return token = 69 /* Identifier */; + } + else { + return pos += 1, token = 0 /* Unknown */; + } + } function speculationHelper(callback, isLookahead) { var savePos = pos; var saveStartPos = startPos; @@ -4143,11 +4501,34 @@ var ts; } return result; } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var savePrecedingLineBreak = precedingLineBreak; + var saveTokenValue = tokenValue; + var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + var saveTokenIsUnterminated = tokenIsUnterminated; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + precedingLineBreak = savePrecedingLineBreak; + tokenValue = saveTokenValue; + hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; + tokenIsUnterminated = saveTokenIsUnterminated; + return result; + } function lookAhead(callback) { - return speculationHelper(callback, /*isLookahead:*/ true); + return speculationHelper(callback, /*isLookahead*/ true); } function tryScan(callback) { - return speculationHelper(callback, /*isLookahead:*/ false); + return speculationHelper(callback, /*isLookahead*/ false); } function setText(newText, start, length) { text = newText || ""; @@ -4177,1321 +4558,6 @@ var ts; } ts.createScanner = createScanner; })(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - ts.bindTime = 0; - (function (ModuleInstanceState) { - ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; - ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; - ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; - })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); - var ModuleInstanceState = ts.ModuleInstanceState; - var Reachability; - (function (Reachability) { - Reachability[Reachability["Unintialized"] = 1] = "Unintialized"; - Reachability[Reachability["Reachable"] = 2] = "Reachable"; - Reachability[Reachability["Unreachable"] = 4] = "Unreachable"; - Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable"; - })(Reachability || (Reachability = {})); - function or(state1, state2) { - return (state1 | state2) & 2 /* Reachable */ - ? 2 /* Reachable */ - : (state1 & state2) & 8 /* ReportedUnreachable */ - ? 8 /* ReportedUnreachable */ - : 4 /* Unreachable */; - } - function getModuleInstanceState(node) { - // A module is uninstantiated if it contains only - // 1. interface declarations, type alias declarations - if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 216 /* TypeAliasDeclaration */) { - return 0 /* NonInstantiated */; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2 /* ConstEnumOnly */; - } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) { - return 0 /* NonInstantiated */; - } - else if (node.kind === 219 /* ModuleBlock */) { - var state = 0 /* NonInstantiated */; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0 /* NonInstantiated */: - // child is non-instantiated - continue searching - return false; - case 2 /* ConstEnumOnly */: - // child is const enum only - record state and continue searching - state = 2 /* ConstEnumOnly */; - return false; - case 1 /* Instantiated */: - // child is instantiated - record state and stop - state = 1 /* Instantiated */; - return true; - } - }); - return state; - } - else if (node.kind === 218 /* ModuleDeclaration */) { - return getModuleInstanceState(node.body); - } - else { - return 1 /* Instantiated */; - } - } - ts.getModuleInstanceState = getModuleInstanceState; - var ContainerFlags; - (function (ContainerFlags) { - // The current node is not a container, and no container manipulation should happen before - // recursing into it. - ContainerFlags[ContainerFlags["None"] = 0] = "None"; - // The current node is a container. It should be set as the current container (and block- - // container) before recursing into it. The current node does not have locals. Examples: - // - // Classes, ObjectLiterals, TypeLiterals, Interfaces... - ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; - // The current node is a block-scoped-container. It should be set as the current block- - // container before recursing into it. Examples: - // - // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... - ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; - 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 = {})); - var binder = createBinder(); - function bindSourceFile(file, options) { - var start = new Date().getTime(); - binder(file, options); - ts.bindTime += new Date().getTime() - start; - } - ts.bindSourceFile = bindSourceFile; - function createBinder() { - var file; - var options; - var parent; - var container; - var blockScopeContainer; - var lastContainer; - var seenThisKeyword; - // state used by reachability checks - var hasExplicitReturn; - var currentReachabilityState; - var labelStack; - var labelIndexMap; - var implicitLabels; - // 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; - var symbolCount = 0; - var Symbol; - var classifiableNames; - function bindSourceFile(f, opts) { - file = f; - options = opts; - inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; - Symbol = ts.objectAllocator.getSymbolConstructor(); - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - hasExplicitReturn = false; - labelStack = undefined; - labelIndexMap = undefined; - implicitLabels = undefined; - } - return bindSourceFile; - function createSymbol(flags, name) { - symbolCount++; - return new Symbol(flags, name); - } - function addDeclarationToSymbol(symbol, node, symbolFlags) { - symbol.flags |= symbolFlags; - node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = []; - } - symbol.declarations.push(node); - if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { - symbol.exports = {}; - } - 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 === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { - return "\"" + node.name.text + "\""; - } - if (node.name.kind === 136 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); - } - return node.name.text; - } - switch (node.kind) { - case 144 /* Constructor */: - return "__constructor"; - case 152 /* FunctionType */: - case 147 /* CallSignature */: - return "__call"; - case 153 /* ConstructorType */: - case 148 /* ConstructSignature */: - return "__new"; - case 149 /* IndexSignature */: - return "__index"; - case 228 /* ExportDeclaration */: - return "__export"; - case 227 /* ExportAssignment */: - return node.isExportEquals ? "export=" : "default"; - case 213 /* FunctionDeclaration */: - case 214 /* ClassDeclaration */: - return node.flags & 512 /* Default */ ? "default" : undefined; - } - } - function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); - } - /** - * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. - * @param symbolTable - The symbol table which node will be added to. - * @param parent - node's parent declaration. - * @param node - The declaration to be added to the symbol table - * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) - * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. - */ - function declareSymbol(symbolTable, parent, node, includes, excludes) { - ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 512 /* Default */; - // The exported symbol for an export default function/class node is always named "default" - var name = isDefaultExport && parent ? "default" : getDeclarationName(node); - var symbol; - if (name !== undefined) { - // Check and see if the symbol table already has a symbol with this name. If not, - // create a new symbol with this name and add it to the table. Note that we don't - // give the new symbol any flags *yet*. This ensures that it will not conflict - // with the 'excludes' flags we pass in. - // - // If we do get an existing symbol, see if it conflicts with the new symbol we're - // creating. For example, a 'var' symbol and a 'class' symbol will conflict within - // the same symbol table. If we have a conflict, report the issue on each - // declaration we have for this symbol, and then create a new symbol for this - // declaration. - // - // 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; - } - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - var message = symbol.flags & 2 /* BlockScopedVariable */ - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512 /* Default */) { - message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - }); - ts.forEach(symbol.declarations, function (declaration) { - 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 /* None */, name); - } - } - else { - symbol = createSymbol(0 /* None */, "__missing"); - } - addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; - return symbol; - } - function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 2 /* Export */; - if (symbolFlags & 8388608 /* Alias */) { - if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - else { - // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue, - // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set - // on it. There are 2 main reasons: - // - // 1. We treat locals and exports of the same name as mutually exclusive within a container. - // That means the binder will issue a Duplicate Identifier error if you mix locals and exports - // with the same name in the same container. - // TODO: Make this a more specific error and decouple it from the exclusion logic. - // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, - // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way - // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. - if (hasExportModifier || container.flags & 131072 /* ExportContext */) { - 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, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - 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) { - // 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; - // 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); - } - else if (containerFlags & 2 /* IsBlockScopedContainer */) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - var savedReachabilityState; - var savedLabelStack; - var savedLabels; - var savedImplicitLabels; - var savedHasExplicitReturn; - var kind = node.kind; - var flags = node.flags; - // reset all reachability check related flags on node (for incremental scenarios) - flags &= ~1572864 /* ReachabilityCheckFlags */; - if (kind === 215 /* InterfaceDeclaration */) { - seenThisKeyword = false; - } - var saveState = kind === 248 /* SourceFile */ || kind === 219 /* ModuleBlock */ || ts.isFunctionLikeKind(kind); - if (saveState) { - savedReachabilityState = currentReachabilityState; - savedLabelStack = labelStack; - savedLabels = labelIndexMap; - savedImplicitLabels = implicitLabels; - savedHasExplicitReturn = hasExplicitReturn; - currentReachabilityState = 2 /* Reachable */; - hasExplicitReturn = false; - labelStack = labelIndexMap = implicitLabels = undefined; - } - bindReachableStatement(node); - if (currentReachabilityState === 2 /* Reachable */ && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { - flags |= 524288 /* HasImplicitReturn */; - if (hasExplicitReturn) { - flags |= 1048576 /* HasExplicitReturn */; - } - } - if (kind === 215 /* InterfaceDeclaration */) { - flags = seenThisKeyword ? flags | 262144 /* ContainsThis */ : flags & ~262144 /* ContainsThis */; - } - node.flags = flags; - if (saveState) { - hasExplicitReturn = savedHasExplicitReturn; - currentReachabilityState = savedReachabilityState; - labelStack = savedLabelStack; - labelIndexMap = savedLabels; - implicitLabels = savedImplicitLabels; - } - container = saveContainer; - parent = saveParent; - blockScopeContainer = savedBlockScopeContainer; - } - /** - * Returns true if node and its subnodes were successfully traversed. - * Returning false means that node was not examined and caller needs to dive into the node himself. - */ - function bindReachableStatement(node) { - if (checkUnreachable(node)) { - ts.forEachChild(node, bind); - return; - } - switch (node.kind) { - case 198 /* WhileStatement */: - bindWhileStatement(node); - break; - case 197 /* DoStatement */: - bindDoStatement(node); - break; - case 199 /* ForStatement */: - bindForStatement(node); - break; - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - bindForInOrForOfStatement(node); - break; - case 196 /* IfStatement */: - bindIfStatement(node); - break; - case 204 /* ReturnStatement */: - case 208 /* ThrowStatement */: - bindReturnOrThrow(node); - break; - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: - bindBreakOrContinueStatement(node); - break; - case 209 /* TryStatement */: - bindTryStatement(node); - break; - case 206 /* SwitchStatement */: - bindSwitchStatement(node); - break; - case 220 /* CaseBlock */: - bindCaseBlock(node); - break; - case 207 /* LabeledStatement */: - bindLabeledStatement(node); - break; - default: - ts.forEachChild(node, bind); - break; - } - } - function bindWhileStatement(n) { - var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; - var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; - // bind expressions (don't affect reachability) - bind(n.expression); - currentReachabilityState = preWhileState; - var postWhileLabel = pushImplicitLabel(); - bind(n.statement); - popImplicitLabel(postWhileLabel, postWhileState); - } - function bindDoStatement(n) { - var preDoState = currentReachabilityState; - var postDoLabel = pushImplicitLabel(); - bind(n.statement); - var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState; - popImplicitLabel(postDoLabel, postDoState); - // bind expressions (don't affect reachability) - bind(n.expression); - } - function bindForStatement(n) { - var preForState = currentReachabilityState; - var postForLabel = pushImplicitLabel(); - // bind expressions (don't affect reachability) - bind(n.initializer); - bind(n.condition); - bind(n.incrementor); - bind(n.statement); - // for statement is considered infinite when it condition is either omitted or is true keyword - // - for(..;;..) - // - for(..;true;..) - var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */); - var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState; - popImplicitLabel(postForLabel, postForState); - } - function bindForInOrForOfStatement(n) { - var preStatementState = currentReachabilityState; - var postStatementLabel = pushImplicitLabel(); - // bind expressions (don't affect reachability) - bind(n.initializer); - bind(n.expression); - bind(n.statement); - popImplicitLabel(postStatementLabel, preStatementState); - } - function bindIfStatement(n) { - // denotes reachability state when entering 'thenStatement' part of the if statement: - // i.e. if condition is false then thenStatement is unreachable - var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; - // denotes reachability state when entering 'elseStatement': - // i.e. if condition is true then elseStatement is unreachable - var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; - currentReachabilityState = ifTrueState; - // bind expression (don't affect reachability) - bind(n.expression); - bind(n.thenStatement); - if (n.elseStatement) { - var preElseState = currentReachabilityState; - currentReachabilityState = ifFalseState; - bind(n.elseStatement); - currentReachabilityState = or(currentReachabilityState, preElseState); - } - else { - currentReachabilityState = or(currentReachabilityState, ifFalseState); - } - } - function bindReturnOrThrow(n) { - // bind expression (don't affect reachability) - bind(n.expression); - if (n.kind === 204 /* ReturnStatement */) { - hasExplicitReturn = true; - } - currentReachabilityState = 4 /* Unreachable */; - } - function bindBreakOrContinueStatement(n) { - // call bind on label (don't affect reachability) - bind(n.label); - // for continue case touch label so it will be marked a used - var isValidJump = jumpToLabel(n.label, n.kind === 203 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); - if (isValidJump) { - currentReachabilityState = 4 /* Unreachable */; - } - } - function bindTryStatement(n) { - // catch\finally blocks has the same reachability as try block - var preTryState = currentReachabilityState; - bind(n.tryBlock); - var postTryState = currentReachabilityState; - currentReachabilityState = preTryState; - bind(n.catchClause); - var postCatchState = currentReachabilityState; - currentReachabilityState = preTryState; - bind(n.finallyBlock); - // post catch/finally state is reachable if - // - post try state is reachable - control flow can fall out of try block - // - post catch state is reachable - control flow can fall out of catch block - currentReachabilityState = or(postTryState, postCatchState); - } - function bindSwitchStatement(n) { - var preSwitchState = currentReachabilityState; - var postSwitchLabel = pushImplicitLabel(); - // bind expression (don't affect reachability) - bind(n.expression); - bind(n.caseBlock); - var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242 /* DefaultClause */; }); - // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case - var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState; - popImplicitLabel(postSwitchLabel, postSwitchState); - } - function bindCaseBlock(n) { - var startState = currentReachabilityState; - for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { - var clause = _a[_i]; - currentReachabilityState = startState; - bind(clause); - if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } - } - } - function bindLabeledStatement(n) { - // call bind on label (don't affect reachability) - bind(n.label); - var ok = pushNamedLabel(n.label); - bind(n.statement); - if (ok) { - popNamedLabel(n.label, currentReachabilityState); - } - } - function getContainerFlags(node) { - switch (node.kind) { - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 155 /* TypeLiteral */: - case 165 /* ObjectLiteralExpression */: - return 1 /* IsContainer */; - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 213 /* FunctionDeclaration */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 218 /* ModuleDeclaration */: - case 248 /* SourceFile */: - case 216 /* TypeAliasDeclaration */: - return 5 /* IsContainerWithLocals */; - case 244 /* CatchClause */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 220 /* CaseBlock */: - return 2 /* IsBlockScopedContainer */; - case 192 /* 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 */; - } - return 0 /* None */; - } - function addToContainerChain(next) { - if (lastContainer) { - lastContainer.nextContainer = next; - } - lastContainer = next; - } - function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - // Just call this directly so that the return type of this function stays "void". - 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 218 /* ModuleDeclaration */: - return declareModuleMember(node, symbolFlags, symbolExcludes); - case 248 /* SourceFile */: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: - return declareClassMember(node, symbolFlags, symbolExcludes); - case 217 /* EnumDeclaration */: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 155 /* TypeLiteral */: - case 165 /* ObjectLiteralExpression */: - case 215 /* 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 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 216 /* 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 & 64 /* 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 hasExportDeclarations(node) { - var body = node.kind === 248 /* SourceFile */ ? node : node.body; - if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var stat = _a[_i]; - if (stat.kind === 228 /* ExportDeclaration */ || stat.kind === 227 /* ExportAssignment */) { - return true; - } - } - } - return false; - } - function setExportContextFlag(node) { - // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular - // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 131072 /* ExportContext */; - } - else { - node.flags &= ~131072 /* ExportContext */; - } - } - function bindModuleDeclaration(node) { - setExportContextFlag(node); - if (node.name.kind === 9 /* StringLiteral */) { - declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); - } - else { - var state = getModuleInstanceState(node); - if (state === 0 /* NonInstantiated */) { - declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */); - } - else { - declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); - if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { - // if module was already merged with some function, class or non-const enum - // treat is a non-const-enum-only - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; - if (node.symbol.constEnumOnlyModule === undefined) { - // non-merged case - use the current state - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - // merged case: module is const enum only if all its pieces are non-instantiated or const enum - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } - } - } - } - function bindFunctionOrConstructorType(node) { - // For a given function symbol "<...>(...) => T" we want to generate a symbol identical - // to the one we would get for: { <...>(...): T } - // - // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable - // from an actual type literal symbol you would have gotten had you used the long form. - var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072 /* Signature */); - var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); - var _a; - } - 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 !== 69 /* 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 === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* 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 bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - addDeclarationToSymbol(symbol, node, symbolFlags); - } - function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { - switch (blockScopeContainer.kind) { - case 218 /* ModuleDeclaration */: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case 248 /* SourceFile */: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - // fall through. - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); - } - // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized - // check for reserved words used as identifiers in strict mode code. - function checkStrictModeIdentifier(node) { - if (inStrictMode && - node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 114 /* 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.getContainingClass(node)) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - function checkStrictModeBinaryExpression(node) { - if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) - checkStrictModeEvalOrArguments(node, node.left); - } - } - function checkStrictModeCatchClause(node) { - // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the - // Catch production is eval or arguments - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - function checkStrictModeDeleteExpression(node) { - // Grammar checking - if (inStrictMode && node.expression.kind === 69 /* 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 === 69 /* Identifier */ && - (node.text === "eval" || node.text === "arguments"); - } - function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 69 /* 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.getContainingClass(node)) { - return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; - } - function checkStrictModeFunctionName(node) { - if (inStrictMode) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) - checkStrictModeEvalOrArguments(node, node.name); - } - } - function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.flags & 32768 /* 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 === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - function checkStrictModeWithStatement(node) { - // Grammar checking for withStatement - if (inStrictMode) { - errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - function getDestructuringParameterName(node) { - return "__" + ts.indexOf(node.parent.parameters, node); - } - function bind(node) { - if (!node) { - return; - } - node.parent = parent; - var 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 248 /* SourceFile */: - case 219 /* ModuleBlock */: - updateStrictModeStatementList(node.statements); - return; - case 192 /* Block */: - if (ts.isFunctionLike(node.parent)) { - updateStrictModeStatementList(node.statements); - } - return; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - // All classes are automatically in strict mode in ES6. - inStrictMode = true; - return; - } - } - function updateStrictModeStatementList(statements) { - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; - if (!ts.isPrologueDirective(statement)) { - return; - } - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - /// Should be called only on prologue directives (isPrologueDirective(node) should be true) - function isUseStrictPrologueDirective(node) { - var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); - // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the - // string to contain unicode escapes (as per ES5). - return nodeText === "\"use strict\"" || nodeText === "'use strict'"; - } - function bindWorker(node) { - switch (node.kind) { - case 69 /* Identifier */: - return checkStrictModeIdentifier(node); - case 181 /* BinaryExpression */: - return checkStrictModeBinaryExpression(node); - case 244 /* CatchClause */: - return checkStrictModeCatchClause(node); - case 175 /* DeleteExpression */: - return checkStrictModeDeleteExpression(node); - case 8 /* NumericLiteral */: - return checkStrictModeNumericLiteral(node); - case 180 /* PostfixUnaryExpression */: - return checkStrictModePostfixUnaryExpression(node); - case 179 /* PrefixUnaryExpression */: - return checkStrictModePrefixUnaryExpression(node); - case 205 /* WithStatement */: - return checkStrictModeWithStatement(node); - case 97 /* ThisKeyword */: - seenThisKeyword = true; - return; - case 137 /* TypeParameter */: - return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); - case 138 /* Parameter */: - return bindParameter(node); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: - return bindVariableDeclarationOrBindingElement(node); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); - case 245 /* PropertyAssignment */: - case 246 /* ShorthandPropertyAssignment */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); - case 247 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - // If this is an ObjectLiteralExpression method, then it sits in the same space - // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes - // so that it will conflict with any other object literal members with the same - // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); - case 213 /* FunctionDeclaration */: - checkStrictModeFunctionName(node); - return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); - case 144 /* Constructor */: - return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 145 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); - case 146 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - return bindFunctionOrConstructorType(node); - case 155 /* TypeLiteral */: - return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); - case 165 /* ObjectLiteralExpression */: - return bindObjectLiteralExpression(node); - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.text : "__function"; - return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: - return bindClassLikeDeclaration(node); - case 215 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); - case 216 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); - case 217 /* EnumDeclaration */: - return bindEnumDeclaration(node); - case 218 /* ModuleDeclaration */: - return bindModuleDeclaration(node); - case 221 /* ImportEqualsDeclaration */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: - return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - case 223 /* ImportClause */: - return bindImportClause(node); - case 228 /* ExportDeclaration */: - return bindExportDeclaration(node); - case 227 /* ExportAssignment */: - return bindExportAssignment(node); - case 248 /* 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 === 69 /* 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 === 214 /* ClassDeclaration */) { - bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); - } - else { - var bindingName = node.name ? node.name.text : "__class"; - bindAnonymousDeclaration(node, 32 /* Class */, bindingName); - // Add name of class expression into the map for semantic classifier - if (node.name) { - classifiableNames[node.name.text] = node.name.text; - } - } - var symbol = node.symbol; - // TypeScript 1.0 spec (April 2014): 8.4 - // Every class automatically contains a static property member named 'prototype', the - // type of which is an instantiation of the class type with type Any supplied as a type - // argument for each type parameter. It is an error to explicitly declare a static - // property member with the name 'prototype'. - // - // Note: we check for this here because this class may be merging into a module. The - // module might have an exported variable called 'prototype'. We can't allow that as - // that would clash with the built-in 'prototype' for the class. - var prototypeSymbol = createSymbol(4 /* Property */ | 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)); - } - else { - 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 & 56 /* AccessibilityModifier */ && - node.parent.kind === 144 /* Constructor */ && - ts.isClassLike(node.parent.parent)) { - var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); - } - } - function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed") - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - // reachability checks - function pushNamedLabel(name) { - initializeReachabilityStateIfNecessary(); - if (ts.hasProperty(labelIndexMap, name.text)) { - return false; - } - labelIndexMap[name.text] = labelStack.push(1 /* Unintialized */) - 1; - return true; - } - function pushImplicitLabel() { - initializeReachabilityStateIfNecessary(); - var index = labelStack.push(1 /* Unintialized */) - 1; - implicitLabels.push(index); - return index; - } - function popNamedLabel(label, outerState) { - var index = labelIndexMap[label.text]; - ts.Debug.assert(index !== undefined); - ts.Debug.assert(labelStack.length == index + 1); - labelIndexMap[label.text] = undefined; - setCurrentStateAtLabel(labelStack.pop(), outerState, label); - } - function popImplicitLabel(implicitLabelIndex, outerState) { - if (labelStack.length !== implicitLabelIndex + 1) { - ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); - } - var i = implicitLabels.pop(); - if (implicitLabelIndex !== i) { - ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); - } - setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined); - } - function setCurrentStateAtLabel(innerMergedState, outerState, label) { - if (innerMergedState === 1 /* Unintialized */) { - if (label && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); - } - currentReachabilityState = outerState; - } - else { - currentReachabilityState = or(innerMergedState, outerState); - } - } - function jumpToLabel(label, outerState) { - initializeReachabilityStateIfNecessary(); - var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); - if (index === undefined) { - // reference to unknown label or - // break/continue used outside of loops - return false; - } - var stateAtLabel = labelStack[index]; - labelStack[index] = stateAtLabel === 1 /* Unintialized */ ? outerState : or(stateAtLabel, outerState); - return true; - } - function checkUnreachable(node) { - switch (currentReachabilityState) { - case 4 /* Unreachable */: - var reportError = - // report error on all statements - ts.isStatement(node) || - // report error on class declarations - node.kind === 214 /* ClassDeclaration */ || - // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 218 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 217 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); - if (reportError) { - currentReachabilityState = 8 /* ReportedUnreachable */; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 193 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); - } - } - case 8 /* ReportedUnreachable */: - return true; - default: - return false; - } - function shouldReportErrorOnModuleDeclaration(node) { - var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); - } - } - function initializeReachabilityStateIfNecessary() { - if (labelIndexMap) { - return; - } - currentReachabilityState = 2 /* Reachable */; - labelIndexMap = {}; - labelStack = []; - implicitLabels = []; - } - } -})(ts || (ts = {})); -/// /// /* @internal */ var ts; @@ -5513,10 +4579,10 @@ var ts; var stringWriters = []; function getSingleLineStringWriter() { if (stringWriters.length === 0) { - var str = ""; - var writeText = function (text) { return str += text; }; + var str_1 = ""; + var writeText = function (text) { return str_1 += text; }; return { - string: function () { return str; }, + string: function () { return str_1; }, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -5526,10 +4592,10 @@ var ts; writeSymbol: writeText, // Completely ignore indentation for string writers. And map newlines to // a single space. - writeLine: function () { return str += " "; }, + writeLine: function () { return str_1 += " "; }, increaseIndent: function () { }, decreaseIndent: function () { }, - clear: function () { return str = ""; }, + clear: function () { return str_1 = ""; }, trackSymbol: function () { }, reportInaccessibleThisError: function () { } }; @@ -5553,7 +4619,7 @@ var ts; if (array1.length !== array2.length) { return false; } - for (var i = 0; i < array1.length; ++i) { + for (var i = 0; i < array1.length; i++) { var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; if (!equals) { return false; @@ -5580,33 +4646,45 @@ 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.flags & 268435456 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.parserContextFlags & 128 /* HasAggregatedChildData */)) { + if (!(node.flags & 536870912 /* 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. - var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & 16 /* ThisNodeHasError */) !== 0) || + var thisNodeOrAnySubNodesHasError = ((node.flags & 67108864 /* ThisNodeHasError */) !== 0) || ts.forEachChild(node, containsParseError); // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { - node.parserContextFlags |= 64 /* ThisNodeOrAnySubNodesHasError */; + node.flags |= 268435456 /* ThisNodeOrAnySubNodesHasError */; } - // Also mark that we've propogated the child information to this node. This way we can + // Also mark that we've propagated 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.flags |= 536870912 /* HasAggregatedChildData */; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 248 /* SourceFile */) { + while (node && node.kind !== 252 /* SourceFile */) { node = node.parent; } return node; } ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 196 /* Block */: + case 224 /* CaseBlock */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; function getStartPositionOfLine(line, sourceFile) { ts.Debug.assert(line >= 0); return ts.getLineStarts(sourceFile)[line]; @@ -5700,10 +4778,42 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 24576 /* BlockScoped */) !== 0 || + return (getCombinedNodeFlags(declaration) & 3072 /* BlockScoped */) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isAmbientModule(node) { + return node && node.kind === 222 /* ModuleDeclaration */ && + (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isBlockScopedContainerTopLevel(node) { + return node.kind === 252 /* SourceFile */ || + node.kind === 222 /* ModuleDeclaration */ || + isFunctionLike(node) || + isFunctionBlock(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 131072 /* GlobalAugmentation */); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + // external module augmentation is a ambient module declaration that is either: + // - defined in the top level scope and source file is an external module + // - defined inside ambient module declaration located in the top level scope and source file not an external module + if (!node || !isAmbientModule(node)) { + return false; + } + switch (node.parent.kind) { + case 252 /* SourceFile */: + return isExternalModule(node.parent); + case 223 /* ModuleBlock */: + return isAmbientModule(node.parent.parent) && !isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -5713,15 +4823,15 @@ var ts; return current; } switch (current.kind) { - case 248 /* SourceFile */: - case 220 /* CaseBlock */: - case 244 /* CatchClause */: - case 218 /* ModuleDeclaration */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 252 /* SourceFile */: + case 224 /* CaseBlock */: + case 248 /* CatchClause */: + case 222 /* ModuleDeclaration */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: return current; - case 192 /* Block */: + case 196 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block if (!isFunctionLike(current.parent)) { @@ -5734,9 +4844,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 211 /* VariableDeclaration */ && + declaration.kind === 215 /* VariableDeclaration */ && declaration.parent && - declaration.parent.kind === 244 /* CatchClause */; + declaration.parent.kind === 248 /* CatchClause */; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; // Return display name of an identifier @@ -5775,7 +4885,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 248 /* SourceFile */: + case 252 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -5784,16 +4894,20 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 219 /* InterfaceDeclaration */: + case 222 /* ModuleDeclaration */: + case 221 /* EnumDeclaration */: + case 251 /* EnumMember */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 220 /* TypeAliasDeclaration */: errorNode = node.name; break; } @@ -5812,16 +4926,20 @@ var ts; return file.externalModuleIndicator !== undefined; } ts.isExternalModule = isExternalModule; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; function isDeclarationFile(file) { - return (file.flags & 4096 /* DeclarationFile */) !== 0; + return file.isDeclarationFile; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 217 /* EnumDeclaration */ && isConst(node); + return node.kind === 221 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 163 /* BindingElement */ || isBindingPattern(node))) { + while (node && (node.kind === 167 /* BindingElement */ || isBindingPattern(node))) { node = node.parent; } return node; @@ -5836,85 +4954,94 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 211 /* VariableDeclaration */) { + if (node.kind === 215 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 212 /* VariableDeclarationList */) { + if (node && node.kind === 216 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 193 /* VariableStatement */) { + if (node && node.kind === 197 /* VariableStatement */) { flags |= node.flags; } return flags; } ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 16384 /* Const */); + return !!(getCombinedNodeFlags(node) & 2048 /* Const */); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 8192 /* Let */); + return !!(getCombinedNodeFlags(node) & 1024 /* Let */); } ts.isLet = isLet; + function isSuperCallExpression(n) { + return n.kind === 172 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; + } + ts.isSuperCallExpression = isSuperCallExpression; function isPrologueDirective(node) { - return node.kind === 195 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 199 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getLeadingCommentRangesOfNodeFromText(node, text) { + return ts.getLeadingCommentRanges(text, node.pos); + } + ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; function getJsDocComments(node, sourceFileOfNode) { - var commentRanges = (node.kind === 138 /* Parameter */ || node.kind === 137 /* TypeParameter */) ? - ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) : - getLeadingCommentRangesOfNode(node, sourceFileOfNode); + return getJsDocCommentsFromText(node, sourceFileOfNode.text); + } + ts.getJsDocComments = getJsDocComments; + function getJsDocCommentsFromText(node, text) { + var commentRanges = (node.kind === 140 /* Parameter */ || node.kind === 139 /* TypeParameter */) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + getLeadingCommentRangesOfNodeFromText(node, text); return ts.filter(commentRanges, isJsDocComment); function isJsDocComment(comment) { // True if the comment starts with '/**' but not if it is '/**/' - return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - sourceFileOfNode.text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && - sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== 47 /* slash */; + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 3) !== 47 /* slash */; } } - ts.getJsDocComments = getJsDocComments; + ts.getJsDocCommentsFromText = getJsDocCommentsFromText; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isTypeNode(node) { - if (151 /* FirstTypeNode */ <= node.kind && node.kind <= 160 /* LastTypeNode */) { + if (152 /* FirstTypeNode */ <= node.kind && node.kind <= 164 /* LastTypeNode */) { return true; } switch (node.kind) { case 117 /* AnyKeyword */: - case 128 /* NumberKeyword */: - case 130 /* StringKeyword */: + case 129 /* NumberKeyword */: + case 131 /* StringKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: return true; case 103 /* VoidKeyword */: - return node.parent.kind !== 177 /* VoidExpression */; - case 9 /* StringLiteral */: - // Specialized signatures can have string literals as their parameters' type names - return node.parent.kind === 138 /* Parameter */; - case 188 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 181 /* VoidExpression */; + case 192 /* 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 69 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 137 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 170 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); - case 135 /* QualifiedName */: - case 166 /* PropertyAccessExpression */: + ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 137 /* QualifiedName */ || node.kind === 170 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + case 137 /* QualifiedName */: + case 170 /* PropertyAccessExpression */: case 97 /* ThisKeyword */: var parent_1 = node.parent; - if (parent_1.kind === 154 /* TypeQuery */) { + if (parent_1.kind === 156 /* TypeQuery */) { return false; } // Do not recursively call isTypeNode on the parent. In the example: @@ -5923,38 +5050,38 @@ var ts; // // Calling isTypeNode would consider the qualified name A.B a type node. Only C or // A.B.C is a type node. - if (151 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 160 /* LastTypeNode */) { + if (152 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 164 /* LastTypeNode */) { return true; } switch (parent_1.kind) { - case 188 /* ExpressionWithTypeArguments */: + case 192 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); - case 137 /* TypeParameter */: + case 139 /* TypeParameter */: return node === parent_1.constraint; - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 138 /* Parameter */: - case 211 /* VariableDeclaration */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 140 /* Parameter */: + case 215 /* VariableDeclaration */: return node === parent_1.type; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 144 /* Constructor */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 146 /* Constructor */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: return node === parent_1.type; - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: return node === parent_1.type; - case 171 /* TypeAssertionExpression */: + case 175 /* TypeAssertionExpression */: return node === parent_1.type; - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 170 /* TaggedTemplateExpression */: + case 174 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -5968,23 +5095,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 204 /* ReturnStatement */: + case 208 /* ReturnStatement */: return visitor(node); - case 220 /* CaseBlock */: - case 192 /* Block */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: + case 224 /* CaseBlock */: + case 196 /* Block */: + case 200 /* IfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 209 /* WithStatement */: + case 210 /* SwitchStatement */: + case 245 /* CaseClause */: + case 246 /* DefaultClause */: + case 211 /* LabeledStatement */: + case 213 /* TryStatement */: + case 248 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -5994,18 +5121,18 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 184 /* YieldExpression */: + case 188 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 221 /* EnumDeclaration */: + case 219 /* InterfaceDeclaration */: + case 222 /* ModuleDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: // 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. @@ -6013,7 +5140,7 @@ var ts; default: if (isFunctionLike(node)) { var name_5 = node.name; - if (name_5 && name_5.kind === 136 /* ComputedPropertyName */) { + if (name_5 && name_5.kind === 138 /* 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_5.expression); @@ -6032,14 +5159,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 163 /* BindingElement */: - case 247 /* EnumMember */: - case 138 /* Parameter */: - case 245 /* PropertyAssignment */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 246 /* ShorthandPropertyAssignment */: - case 211 /* VariableDeclaration */: + case 167 /* BindingElement */: + case 251 /* EnumMember */: + case 140 /* Parameter */: + case 249 /* PropertyAssignment */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 250 /* ShorthandPropertyAssignment */: + case 215 /* VariableDeclaration */: return true; } } @@ -6047,11 +5174,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - return node && (node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */); + return node && (node.kind === 147 /* GetAccessor */ || node.kind === 148 /* SetAccessor */); } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */); + return node && (node.kind === 218 /* ClassDeclaration */ || node.kind === 190 /* ClassExpression */); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -6060,32 +5187,32 @@ var ts; ts.isFunctionLike = isFunctionLike; function isFunctionLikeKind(kind) { switch (kind) { - case 144 /* Constructor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 146 /* Constructor */: + case 177 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: + case 178 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: return true; } } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: return true; } return false; @@ -6093,26 +5220,34 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: return true; - case 207 /* LabeledStatement */: + case 211 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 192 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 196 /* Block */ && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 143 /* MethodDeclaration */ && node.parent.kind === 165 /* ObjectLiteralExpression */; + return node && node.kind === 145 /* MethodDeclaration */ && node.parent.kind === 169 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0 /* This */; + } + ts.isThisTypePredicate = isThisTypePredicate; function getContainingFunction(node) { while (true) { node = node.parent; @@ -6138,7 +5273,7 @@ var ts; return undefined; } switch (node.kind) { - case 136 /* ComputedPropertyName */: + case 138 /* 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 @@ -6153,9 +5288,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 139 /* Decorator */: + case 141 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 138 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 140 /* 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; @@ -6166,55 +5301,66 @@ var ts; node = node.parent; } break; - case 174 /* ArrowFunction */: + case 178 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // Fall through - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 218 /* ModuleDeclaration */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 217 /* EnumDeclaration */: - case 248 /* SourceFile */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 222 /* ModuleDeclaration */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + case 221 /* EnumDeclaration */: + case 252 /* SourceFile */: return node; } } } ts.getThisContainer = getThisContainer; - function getSuperContainer(node, includeFunctions) { + /** + * Given an super call\property node returns a closest node where either + * - super call\property is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - node is arrow function (so caller might need to call getSuperContainer in case it needs to climb higher) + * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ + function getSuperContainer(node, stopOnFunctions) { while (true) { node = node.parent; - if (!node) + if (!node) { return node; + } switch (node.kind) { - case 136 /* 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 (isClassLike(node.parent.parent)) { - return node; - } - // If this is a computed property, then the parent should not - // make it a super container. The parent might be a property - // in an object literal, like a method or accessor. But in order for - // such a parent to be a super container, the reference must be in - // the *body* of the container. + case 138 /* ComputedPropertyName */: node = node.parent; break; - case 139 /* Decorator */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + return node; + case 141 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 138 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 140 /* 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; @@ -6225,33 +5371,28 @@ var ts; node = node.parent; } break; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - if (!includeFunctions) { - continue; - } - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - return node; } } } ts.getSuperContainer = getSuperContainer; + /** + * Determines whether a node is a property or element access expression for super. + */ + function isSuperPropertyOrElementAccess(node) { + return (node.kind === 170 /* PropertyAccessExpression */ + || node.kind === 171 /* ElementAccessExpression */) + && node.expression.kind === 95 /* SuperKeyword */; + } + ts.isSuperPropertyOrElementAccess = isSuperPropertyOrElementAccess; function getEntityNameFromTypeNode(node) { if (node) { switch (node.kind) { - case 151 /* TypeReference */: + case 153 /* TypeReference */: return node.typeName; - case 188 /* ExpressionWithTypeArguments */: + case 192 /* ExpressionWithTypeArguments */: return node.expression; case 69 /* Identifier */: - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: return node; } } @@ -6259,7 +5400,7 @@ var ts; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 174 /* TaggedTemplateExpression */) { return node.tag; } // Will either be a CallExpression, NewExpression, or Decorator. @@ -6268,73 +5409,40 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: // classes are valid targets return true; - case 141 /* PropertyDeclaration */: + case 143 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return node.parent.kind === 214 /* ClassDeclaration */; - case 138 /* 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 === 214 /* ClassDeclaration */; - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 143 /* MethodDeclaration */: + return node.parent.kind === 218 /* ClassDeclaration */; + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 145 /* 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 === 214 /* ClassDeclaration */; + return node.body !== undefined + && node.parent.kind === 218 /* ClassDeclaration */; + case 140 /* 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 !== undefined + && (node.parent.kind === 146 /* Constructor */ + || node.parent.kind === 145 /* MethodDeclaration */ + || node.parent.kind === 148 /* SetAccessor */) + && node.parent.parent.kind === 218 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { - switch (node.kind) { - case 214 /* ClassDeclaration */: - if (node.decorators) { - return true; - } - return false; - case 141 /* PropertyDeclaration */: - case 138 /* Parameter */: - if (node.decorators) { - return true; - } - return false; - case 145 /* GetAccessor */: - if (node.body && node.decorators) { - return true; - } - return false; - case 143 /* MethodDeclaration */: - case 146 /* SetAccessor */: - if (node.body && node.decorators) { - return true; - } - return false; - } - return false; + return node.decorators !== undefined + && nodeCanBeDecorated(node); } ts.nodeIsDecorated = nodeIsDecorated; - function childIsDecorated(node) { - switch (node.kind) { - case 214 /* ClassDeclaration */: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 143 /* MethodDeclaration */: - case 146 /* SetAccessor */: - return ts.forEach(node.parameters, nodeIsDecorated); - } - return false; - } - ts.childIsDecorated = childIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); - } - ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function isPropertyAccessExpression(node) { - return node.kind === 166 /* PropertyAccessExpression */; + return node.kind === 170 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 167 /* ElementAccessExpression */; + return node.kind === 171 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isExpression(node) { @@ -6344,42 +5452,42 @@ var ts; case 99 /* TrueKeyword */: case 84 /* FalseKeyword */: case 10 /* RegularExpressionLiteral */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 170 /* TaggedTemplateExpression */: - case 189 /* AsExpression */: - case 171 /* TypeAssertionExpression */: - case 172 /* ParenthesizedExpression */: - case 173 /* FunctionExpression */: - case 186 /* ClassExpression */: - case 174 /* ArrowFunction */: - case 177 /* VoidExpression */: - case 175 /* DeleteExpression */: - case 176 /* TypeOfExpression */: - case 179 /* PrefixUnaryExpression */: - case 180 /* PostfixUnaryExpression */: - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 183 /* TemplateExpression */: + case 168 /* ArrayLiteralExpression */: + case 169 /* ObjectLiteralExpression */: + case 170 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 174 /* TaggedTemplateExpression */: + case 193 /* AsExpression */: + case 175 /* TypeAssertionExpression */: + case 176 /* ParenthesizedExpression */: + case 177 /* FunctionExpression */: + case 190 /* ClassExpression */: + case 178 /* ArrowFunction */: + case 181 /* VoidExpression */: + case 179 /* DeleteExpression */: + case 180 /* TypeOfExpression */: + case 183 /* PrefixUnaryExpression */: + case 184 /* PostfixUnaryExpression */: + case 185 /* BinaryExpression */: + case 186 /* ConditionalExpression */: + case 189 /* SpreadElementExpression */: + case 187 /* TemplateExpression */: case 11 /* NoSubstitutionTemplateLiteral */: - case 187 /* OmittedExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 184 /* YieldExpression */: - case 178 /* AwaitExpression */: + case 191 /* OmittedExpression */: + case 237 /* JsxElement */: + case 238 /* JsxSelfClosingElement */: + case 188 /* YieldExpression */: + case 182 /* AwaitExpression */: return true; - case 135 /* QualifiedName */: - while (node.parent.kind === 135 /* QualifiedName */) { + case 137 /* QualifiedName */: + while (node.parent.kind === 137 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 154 /* TypeQuery */; + return node.parent.kind === 156 /* TypeQuery */; case 69 /* Identifier */: - if (node.parent.kind === 154 /* TypeQuery */) { + if (node.parent.kind === 156 /* TypeQuery */) { return true; } // fall through @@ -6388,47 +5496,47 @@ var ts; case 97 /* ThisKeyword */: var parent_2 = node.parent; switch (parent_2.kind) { - case 211 /* VariableDeclaration */: - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 247 /* EnumMember */: - case 245 /* PropertyAssignment */: - case 163 /* BindingElement */: + case 215 /* VariableDeclaration */: + case 140 /* Parameter */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 251 /* EnumMember */: + case 249 /* PropertyAssignment */: + case 167 /* BindingElement */: return parent_2.initializer === node; - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 204 /* ReturnStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 208 /* ThrowStatement */: - case 206 /* SwitchStatement */: + case 199 /* ExpressionStatement */: + case 200 /* IfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: + case 208 /* ReturnStatement */: + case 209 /* WithStatement */: + case 210 /* SwitchStatement */: + case 245 /* CaseClause */: + case 212 /* ThrowStatement */: + case 210 /* SwitchStatement */: return parent_2.expression === node; - case 199 /* ForStatement */: + case 203 /* ForStatement */: var forStatement = parent_2; - return (forStatement.initializer === node && forStatement.initializer.kind !== 212 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 216 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: var forInStatement = parent_2; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 212 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 216 /* VariableDeclarationList */) || forInStatement.expression === node; - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 175 /* TypeAssertionExpression */: + case 193 /* AsExpression */: return node === parent_2.expression; - case 190 /* TemplateSpan */: + case 194 /* TemplateSpan */: return node === parent_2.expression; - case 136 /* ComputedPropertyName */: + case 138 /* ComputedPropertyName */: return node === parent_2.expression; - case 139 /* Decorator */: - case 240 /* JsxExpression */: - case 239 /* JsxSpreadAttribute */: + case 141 /* Decorator */: + case 244 /* JsxExpression */: + case 243 /* JsxSpreadAttribute */: return true; - case 188 /* ExpressionWithTypeArguments */: + case 192 /* ExpressionWithTypeArguments */: return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: if (isExpression(parent_2)) { @@ -6452,7 +5560,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */; + return node.kind === 225 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 236 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -6461,34 +5569,94 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 232 /* ExternalModuleReference */; + return node.kind === 225 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 236 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJavaScript(file) { + return isInJavaScriptFile(file); + } + ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isInJavaScriptFile(node) { + return node && !!(node.flags & 134217728 /* JavaScriptFile */); + } + ts.isInJavaScriptFile = isInJavaScriptFile; + /** + * Returns true if the node is a CallExpression to the identifier 'require' with + * exactly one argument. + * This function does not test if the node is in a JavaScript file or not. + */ + function isRequireCall(expression, checkArgumentIsStringLiteral) { + // of the form 'require("name")' + var isRequire = expression.kind === 172 /* CallExpression */ && + expression.expression.kind === 69 /* Identifier */ && + expression.expression.text === "require" && + expression.arguments.length === 1; + return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9 /* StringLiteral */); + } + ts.isRequireCall = isRequireCall; + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getSpecialPropertyAssignmentKind(expression) { + if (expression.kind !== 185 /* BinaryExpression */) { + return 0 /* None */; + } + var expr = expression; + if (expr.operatorToken.kind !== 56 /* EqualsToken */ || expr.left.kind !== 170 /* PropertyAccessExpression */) { + return 0 /* None */; + } + var lhs = expr.left; + if (lhs.expression.kind === 69 /* Identifier */) { + var lhsId = lhs.expression; + if (lhsId.text === "exports") { + // exports.name = expr + return 1 /* ExportsProperty */; + } + else if (lhsId.text === "module" && lhs.name.text === "exports") { + // module.exports = expr + return 2 /* ModuleExports */; + } + } + else if (lhs.expression.kind === 97 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } + else if (lhs.expression.kind === 170 /* PropertyAccessExpression */) { + // chained dot, e.g. x.y.z = expr; this var is the 'x.y' part + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 69 /* Identifier */ && innerPropertyAccess.name.text === "prototype") { + return 3 /* PrototypeProperty */; + } + } + return 0 /* None */; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 222 /* ImportDeclaration */) { + if (node.kind === 226 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 225 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 232 /* ExternalModuleReference */) { + if (reference.kind === 236 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 228 /* ExportDeclaration */) { + if (node.kind === 232 /* ExportDeclaration */) { return node.moduleSpecifier; } + if (node.kind === 222 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { + return node.name; + } } ts.getExternalModuleName = getExternalModuleName; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 138 /* Parameter */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 246 /* ShorthandPropertyAssignment */: - case 245 /* PropertyAssignment */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 140 /* Parameter */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 250 /* ShorthandPropertyAssignment */: + case 249 /* PropertyAssignment */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -6496,31 +5664,70 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 261 /* JSDocFunctionType */ && + return node.kind === 265 /* JSDocFunctionType */ && node.parameters.length > 0 && - node.parameters[0].type.kind === 263 /* JSDocConstructorType */; + node.parameters[0].type.kind === 267 /* JSDocConstructorType */; } 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 getJSDocTag(node, kind, checkParentVariableStatement) { + if (!node) { + return undefined; + } + var jsDocComment = getJSDocComment(node, checkParentVariableStatement); + if (!jsDocComment) { + return undefined; + } + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === kind) { + return tag; } } } + function getJSDocComment(node, checkParentVariableStatement) { + if (node.jsDocComment) { + return node.jsDocComment; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + if (checkParentVariableStatement) { + var isInitializerOfVariableDeclarationInStatement = node.parent.kind === 215 /* VariableDeclaration */ && + node.parent.initializer === node && + node.parent.parent.parent.kind === 197 /* VariableStatement */; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined; + if (variableStatementNode) { + return variableStatementNode.jsDocComment; + } + // Also recognize when the node is the RHS of an assignment expression + var parent_3 = node.parent; + var isSourceOfAssignmentExpressionStatement = parent_3 && parent_3.parent && + parent_3.kind === 185 /* BinaryExpression */ && + parent_3.operatorToken.kind === 56 /* EqualsToken */ && + parent_3.parent.kind === 199 /* ExpressionStatement */; + if (isSourceOfAssignmentExpressionStatement) { + return parent_3.parent.jsDocComment; + } + var isPropertyAssignmentExpression = parent_3 && parent_3.kind === 249 /* PropertyAssignment */; + if (isPropertyAssignmentExpression) { + return parent_3.jsDocComment; + } + } + return undefined; + } function getJSDocTypeTag(node) { - return getJSDocTag(node, 269 /* JSDocTypeTag */); + return getJSDocTag(node, 273 /* JSDocTypeTag */, /*checkParentVariableStatement*/ false); } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 268 /* JSDocReturnTag */); + return getJSDocTag(node, 272 /* JSDocReturnTag */, /*checkParentVariableStatement*/ true); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 270 /* JSDocTemplateTag */); + return getJSDocTag(node, 274 /* JSDocTemplateTag */, /*checkParentVariableStatement*/ false); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getCorrespondingJSDocParameterTag(parameter) { @@ -6528,19 +5735,21 @@ var ts; // 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 === 267 /* JSDocParameterTag */) { - var parameterTag = t; + var jsDocComment = getJSDocComment(parameter.parent, /*checkParentVariableStatement*/ true); + if (jsDocComment) { + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === 271 /* JSDocParameterTag */) { + var parameterTag = tag; var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; if (name_6.text === parameterName) { - return t; + return parameterTag; } } - }); + } } } + return undefined; } ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; function hasRestParameter(s) { @@ -6549,13 +5758,13 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { if (node) { - if (node.parserContextFlags & 32 /* JavaScriptFile */) { - if (node.type && node.type.kind === 262 /* JSDocVariadicType */) { + if (node.flags & 134217728 /* JavaScriptFile */) { + if (node.type && node.type.kind === 266 /* JSDocVariadicType */) { return true; } var paramTag = getCorrespondingJSDocParameterTag(node); if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 262 /* JSDocVariadicType */; + return paramTag.typeExpression.type.kind === 266 /* JSDocVariadicType */; } } return node.dotDotDotToken !== undefined; @@ -6576,7 +5785,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 162 /* ArrayBindingPattern */ || node.kind === 161 /* ObjectBindingPattern */); + return !!node && (node.kind === 166 /* ArrayBindingPattern */ || node.kind === 165 /* ObjectBindingPattern */); } ts.isBindingPattern = isBindingPattern; function isNodeDescendentOf(node, ancestor) { @@ -6590,7 +5799,7 @@ var ts; ts.isNodeDescendentOf = isNodeDescendentOf; function isInAmbientContext(node) { while (node) { - if (node.flags & (4 /* Ambient */ | 4096 /* DeclarationFile */)) { + if (node.flags & 2 /* Ambient */ || (node.kind === 252 /* SourceFile */ && node.isDeclarationFile)) { return true; } node = node.parent; @@ -6600,34 +5809,34 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 174 /* ArrowFunction */: - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 144 /* Constructor */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 230 /* ExportSpecifier */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 145 /* GetAccessor */: - case 223 /* ImportClause */: - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 215 /* InterfaceDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 218 /* ModuleDeclaration */: - case 224 /* NamespaceImport */: - case 138 /* Parameter */: - case 245 /* PropertyAssignment */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 146 /* SetAccessor */: - case 246 /* ShorthandPropertyAssignment */: - case 216 /* TypeAliasDeclaration */: - case 137 /* TypeParameter */: - case 211 /* VariableDeclaration */: + case 178 /* ArrowFunction */: + case 167 /* BindingElement */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 146 /* Constructor */: + case 221 /* EnumDeclaration */: + case 251 /* EnumMember */: + case 234 /* ExportSpecifier */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 147 /* GetAccessor */: + case 227 /* ImportClause */: + case 225 /* ImportEqualsDeclaration */: + case 230 /* ImportSpecifier */: + case 219 /* InterfaceDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 222 /* ModuleDeclaration */: + case 228 /* NamespaceImport */: + case 140 /* Parameter */: + case 249 /* PropertyAssignment */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 148 /* SetAccessor */: + case 250 /* ShorthandPropertyAssignment */: + case 220 /* TypeAliasDeclaration */: + case 139 /* TypeParameter */: + case 215 /* VariableDeclaration */: return true; } return false; @@ -6635,25 +5844,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: - case 210 /* DebuggerStatement */: - case 197 /* DoStatement */: - case 195 /* ExpressionStatement */: - case 194 /* EmptyStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 196 /* IfStatement */: - case 207 /* LabeledStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 193 /* VariableStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 227 /* ExportAssignment */: + case 207 /* BreakStatement */: + case 206 /* ContinueStatement */: + case 214 /* DebuggerStatement */: + case 201 /* DoStatement */: + case 199 /* ExpressionStatement */: + case 198 /* EmptyStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 203 /* ForStatement */: + case 200 /* IfStatement */: + case 211 /* LabeledStatement */: + case 208 /* ReturnStatement */: + case 210 /* SwitchStatement */: + case 212 /* ThrowStatement */: + case 213 /* TryStatement */: + case 197 /* VariableStatement */: + case 202 /* WhileStatement */: + case 209 /* WithStatement */: + case 231 /* ExportAssignment */: return true; default: return false; @@ -6662,13 +5871,13 @@ var ts; ts.isStatement = isStatement; function isClassElement(n) { switch (n.kind) { - case 144 /* Constructor */: - case 141 /* PropertyDeclaration */: - case 143 /* MethodDeclaration */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 142 /* MethodSignature */: - case 149 /* IndexSignature */: + case 146 /* Constructor */: + case 143 /* PropertyDeclaration */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 144 /* MethodSignature */: + case 151 /* IndexSignature */: return true; default: return false; @@ -6681,7 +5890,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 226 /* ImportSpecifier */ || parent.kind === 230 /* ExportSpecifier */) { + if (parent.kind === 230 /* ImportSpecifier */ || parent.kind === 234 /* ExportSpecifier */) { if (parent.propertyName) { return true; } @@ -6696,31 +5905,31 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 247 /* EnumMember */: - case 245 /* PropertyAssignment */: - case 166 /* PropertyAccessExpression */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 251 /* EnumMember */: + case 249 /* PropertyAssignment */: + case 170 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: // Name on right hand side of dot in a type query if (parent.right === node) { - while (parent.kind === 135 /* QualifiedName */) { + while (parent.kind === 137 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 154 /* TypeQuery */; + return parent.kind === 156 /* TypeQuery */; } return false; - case 163 /* BindingElement */: - case 226 /* ImportSpecifier */: + case 167 /* BindingElement */: + case 230 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 230 /* ExportSpecifier */: + case 234 /* ExportSpecifier */: // Any name in an export specifier return true; } @@ -6736,12 +5945,12 @@ var ts; // export = ... // export default ... function isAliasSymbolDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ || - node.kind === 223 /* ImportClause */ && !!node.name || - node.kind === 224 /* NamespaceImport */ || - node.kind === 226 /* ImportSpecifier */ || - node.kind === 230 /* ExportSpecifier */ || - node.kind === 227 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; + return node.kind === 225 /* ImportEqualsDeclaration */ || + node.kind === 227 /* ImportClause */ && !!node.name || + node.kind === 228 /* NamespaceImport */ || + node.kind === 230 /* ImportSpecifier */ || + node.kind === 234 /* ExportSpecifier */ || + node.kind === 231 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -6791,8 +6000,8 @@ var ts; function getFileReferenceFromReferencePath(comment, commentRange) { var simpleReferenceRegEx = /^\/\/\/\s*/gim; - if (simpleReferenceRegEx.exec(comment)) { - if (isNoDefaultLibRegEx.exec(comment)) { + if (simpleReferenceRegEx.test(comment)) { + if (isNoDefaultLibRegEx.test(comment)) { return { isNoDefaultLib: true }; @@ -6823,7 +6032,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 70 /* FirstKeyword */ <= token && token <= 134 /* LastKeyword */; + return 70 /* FirstKeyword */ <= token && token <= 136 /* LastKeyword */; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -6834,6 +6043,10 @@ var ts; return isFunctionLike(node) && (node.flags & 256 /* Async */) !== 0 && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; + function isStringOrNumericLiteral(kind) { + return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */; + } + ts.isStringOrNumericLiteral = isStringOrNumericLiteral; /** * A declaration has a dynamic name if both of the following are true: * 1. The declaration has a computed property name @@ -6842,11 +6055,15 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - return declaration.name && - declaration.name.kind === 136 /* ComputedPropertyName */ && - !isWellKnownSymbolSyntactically(declaration.name.expression); + return declaration.name && isDynamicName(declaration.name); } ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 138 /* ComputedPropertyName */ && + !isStringOrNumericLiteral(name.expression.kind) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; /** * Checks if the expression is of the form: * Symbol.name @@ -6860,7 +6077,7 @@ var ts; if (name.kind === 69 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { return name.text; } - if (name.kind === 136 /* ComputedPropertyName */) { + if (name.kind === 138 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -6881,7 +6098,7 @@ var ts; return node.kind === 69 /* Identifier */ && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; - function isModifier(token) { + function isModifierKind(token) { switch (token) { case 115 /* AbstractKeyword */: case 118 /* AsyncKeyword */: @@ -6892,44 +6109,79 @@ var ts; case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: + case 127 /* ReadonlyKeyword */: case 113 /* StaticKeyword */: return true; } return false; } - ts.isModifier = isModifier; + ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 138 /* Parameter */; + return root.kind === 140 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 163 /* BindingElement */) { + while (node.kind === 167 /* BindingElement */) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 218 /* ModuleDeclaration */ || n.kind === 248 /* SourceFile */; + return isFunctionLike(n) || n.kind === 222 /* ModuleDeclaration */ || n.kind === 252 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneEntityName(node) { - if (node.kind === 69 /* Identifier */) { - var clone_1 = createSynthesizedNode(69 /* Identifier */); - clone_1.text = node.text; - return clone_1; + /** + * Creates a shallow, memberwise clone of a node. The "kind", "pos", "end", "flags", and "parent" + * properties are excluded by default, and can be provided via the "location", "flags", and + * "parent" parameters. + * @param node The node to clone. + * @param location An optional TextRange to use to supply the new position. + * @param flags The NodeFlags to use for the cloned node. + * @param parent The parent for the new node. + */ + function cloneNode(node, location, flags, parent) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + var clone = location !== undefined + ? ts.createNode(node.kind, location.pos, location.end) + : createSynthesizedNode(node.kind); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; } - else { - var clone_2 = createSynthesizedNode(135 /* QualifiedName */); - clone_2.left = cloneEntityName(node.left); - clone_2.left.parent = clone_2; - clone_2.right = cloneEntityName(node.right); - clone_2.right.parent = clone_2; - return clone_2; + if (flags !== undefined) { + clone.flags = flags; } + if (parent !== undefined) { + clone.parent = parent; + } + return clone; + } + ts.cloneNode = cloneNode; + /** + * Creates a deep clone of an EntityName, with new parent pointers. + * @param node The EntityName to clone. + * @param parent The parent for the cloned node. + */ + function cloneEntityName(node, parent) { + var clone = cloneNode(node, node, node.flags, parent); + if (isQualifiedName(clone)) { + var left = clone.left, right = clone.right; + clone.left = cloneEntityName(left, clone); + clone.right = cloneNode(right, right, right.flags, parent); + } + return clone; } ts.cloneEntityName = cloneEntityName; + function isQualifiedName(node) { + return node.kind === 137 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { return node.pos === -1; } @@ -7087,11 +6339,11 @@ var ts; } ts.getIndentSize = getIndentSize; function createTextWriter(newLine) { - var output = ""; - var indent = 0; - var lineStart = true; - var lineCount = 0; - var linePos = 0; + var output; + var indent; + var lineStart; + var lineCount; + var linePos; function write(s) { if (s && s.length) { if (lineStart) { @@ -7101,6 +6353,13 @@ var ts; output += s; } } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } function rawWrite(s) { if (s !== undefined) { if (lineStart) { @@ -7127,25 +6386,38 @@ var ts; lineStart = true; } } - function writeTextOfNode(sourceFile, node) { - write(getSourceTextOfNodeFromSourceFile(sourceFile, node)); + function writeTextOfNode(text, node) { + write(getTextOfNodeFromSourceText(text, node)); } + reset(); return { write: write, rawWrite: rawWrite, writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, - increaseIndent: function () { return indent++; }, - decreaseIndent: function () { return indent--; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, getLine: function () { return lineCount + 1; }, getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, - getText: function () { return output; } + getText: function () { return output; }, + reset: reset }; } ts.createTextWriter = createTextWriter; + /** + * Resolves a local path to a path which is absolute to the base of the emit + */ + function getExternalModuleNameFromPath(host, fileName) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.removeFileExtension(relativePath); + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; function getOwnEmitOutputFilePath(sourceFile, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; @@ -7158,6 +6430,78 @@ var ts; return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { + var options = host.getCompilerOptions(); + // Emit on each source file + if (options.outFile || options.out) { + onBundledEmit(host); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + if (!isDeclarationFile(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + var extension = ".js"; + if (options.jsx === 1 /* Preserve */) { + if (isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + extension = ".jsx"; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + extension = ".jsx"; + } + } + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined + }; + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + } + function onBundledEmit(host) { + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + (!isExternalModule(sourceFile) || + (getEmitModuleKind(options) && isExternalModule(sourceFile))); }); // module that can emit - note falsy value from getEmitModuleKind means the module kind that shouldn't be emitted + if (bundledSources.length) { + var jsFilePath = options.outFile || options.out; + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options) + }; + action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + } + } + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getDeclarationEmitFilePath(jsFilePath, options) { + return options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + } + } + ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); @@ -7166,7 +6510,7 @@ var ts; ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }); } ts.writeFile = writeFile; @@ -7174,9 +6518,13 @@ var ts; return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 144 /* Constructor */ && nodeIsPresent(member.body)) { + if (member.kind === 146 /* Constructor */ && nodeIsPresent(member.body)) { return member; } }); @@ -7186,18 +6534,6 @@ var ts; return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; - function shouldEmitToOwnFile(sourceFile, compilerOptions) { - if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) { - // 1. in-browser single file compilation scenario - // 2. non .js file - return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); - } - return false; - } - return false; - } - ts.shouldEmitToOwnFile = shouldEmitToOwnFile; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -7205,10 +6541,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 145 /* GetAccessor */) { + if (accessor.kind === 147 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 146 /* SetAccessor */) { + else if (accessor.kind === 148 /* SetAccessor */) { setAccessor = accessor; } else { @@ -7217,8 +6553,8 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) - && (member.flags & 64 /* Static */) === (accessor.flags & 64 /* Static */)) { + if ((member.kind === 147 /* GetAccessor */ || member.kind === 148 /* SetAccessor */) + && (member.flags & 32 /* Static */) === (accessor.flags & 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -7228,10 +6564,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 145 /* GetAccessor */ && !getAccessor) { + if (member.kind === 147 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 146 /* SetAccessor */ && !setAccessor) { + if (member.kind === 148 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -7246,22 +6582,22 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) { + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { // If the leading comments start on different line than the start of node, write new line if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && - getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) { + getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { writer.writeLine(); } } ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; - function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) { + function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) { var emitLeadingSpace = !trailingSeparator; ts.forEach(comments, function (comment) { if (emitLeadingSpace) { writer.write(" "); emitLeadingSpace = false; } - writeComment(currentSourceFile, writer, comment, newLine); + writeComment(text, lineMap, writer, comment, newLine); if (comment.hasTrailingNewLine) { writer.writeLine(); } @@ -7279,7 +6615,7 @@ var ts; * Detached comment is a comment at the top of file or function body that is separated from * the next statement by space. */ - function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) { + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { var leadingComments; var currentDetachedCommentInfo; if (removeComments) { @@ -7289,21 +6625,21 @@ var ts; // // var x = 10; if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment); + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); } } else { // removeComments is false, just get detached as normal and bypass the process to filter comment - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + leadingComments = ts.getLeadingCommentRanges(text, node.pos); } if (leadingComments) { var detachedComments = []; - var lastComment; + var lastComment = void 0; for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { var comment = leadingComments_1[_i]; if (lastComment) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); if (commentLine >= lastCommentLine + 2) { // There was a blank line between the last comment and this comment. This // comment is not part of the copyright comments. Return what we have so @@ -7318,36 +6654,36 @@ var ts; // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); - var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } } return currentDetachedCommentInfo; function isPinnedComment(comment) { - return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; } } ts.emitDetachedComments = emitDetachedComments; - function writeCommentRange(currentSourceFile, writer, comment, newLine) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { - var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos); - var lineCount = ts.getLineStarts(currentSourceFile).length; - var firstCommentLineIndent; + function writeCommentRange(text, lineMap, writer, comment, newLine) { + if (text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { var nextLineStart = (currentLine + 1) === lineCount - ? currentSourceFile.text.length + 1 - : getStartPositionOfLine(currentLine + 1, currentSourceFile); + ? text.length + 1 + : lineMap[currentLine + 1]; if (pos !== comment.pos) { // If we are not emitting first line, we need to write the spaces to adjust the alignment if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos); + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos); } // These are number of spaces writer is going to write at current indent var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); @@ -7365,7 +6701,7 @@ var ts; // More right indented comment */ --4 = 8 - 4 + 11 // class c { } // } - var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); if (spacesToEmit > 0) { var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); @@ -7383,57 +6719,58 @@ var ts; } } // Write the comment line text - writeTrimmedCurrentLine(pos, nextLineStart); + writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart); pos = nextLineStart; } } else { // Single line comment of style //.... - writer.write(currentSourceFile.text.substring(comment.pos, comment.end)); - } - function writeTrimmedCurrentLine(pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); - var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ""); - if (currentLineText) { - // trimmed forward and ending spaces text - writer.write(currentLineText); - if (end !== comment.end) { - writer.writeLine(); - } - } - else { - // Empty string - make sure we write empty line - writer.writeLiteral(newLine); - } - } - function calculateIndent(pos, end) { - var currentLineIndent = 0; - for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) { - if (currentSourceFile.text.charCodeAt(pos) === 9 /* tab */) { - // Tabs = TabSize = indent size and go to next tabStop - currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); - } - else { - // Single space - currentLineIndent++; - } - } - return currentLineIndent; + writer.write(text.substring(comment.pos, comment.end)); } } ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) { + var end = Math.min(comment.end, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + // trimmed forward and ending spaces text + writer.write(currentLineText); + if (end !== comment.end) { + writer.writeLine(); + } + } + else { + // Empty string - make sure we write empty line + writer.writeLiteral(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpace(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9 /* tab */) { + // Tabs = TabSize = indent size and go to next tabStop + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + // Single space + currentLineIndent++; + } + } + return currentLineIndent; + } function modifierToFlag(token) { switch (token) { - case 113 /* StaticKeyword */: return 64 /* Static */; - case 112 /* PublicKeyword */: return 8 /* Public */; - case 111 /* ProtectedKeyword */: return 32 /* Protected */; - case 110 /* PrivateKeyword */: return 16 /* Private */; + case 113 /* StaticKeyword */: return 32 /* Static */; + case 112 /* PublicKeyword */: return 4 /* Public */; + case 111 /* ProtectedKeyword */: return 16 /* Protected */; + case 110 /* PrivateKeyword */: return 8 /* Private */; case 115 /* AbstractKeyword */: return 128 /* Abstract */; - case 82 /* ExportKeyword */: return 2 /* Export */; - case 122 /* DeclareKeyword */: return 4 /* Ambient */; - case 74 /* ConstKeyword */: return 16384 /* Const */; + case 82 /* ExportKeyword */: return 1 /* Export */; + case 122 /* DeclareKeyword */: return 2 /* Ambient */; + case 74 /* ConstKeyword */: return 2048 /* Const */; case 77 /* DefaultKeyword */: return 512 /* Default */; case 118 /* AsyncKeyword */: return 256 /* Async */; + case 127 /* ReadonlyKeyword */: return 64 /* Readonly */; } return 0; } @@ -7441,24 +6778,24 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 169 /* NewExpression */: - case 168 /* CallExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 170 /* TaggedTemplateExpression */: - case 164 /* ArrayLiteralExpression */: - case 172 /* ParenthesizedExpression */: - case 165 /* ObjectLiteralExpression */: - case 186 /* ClassExpression */: - case 173 /* FunctionExpression */: + case 170 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: + case 173 /* NewExpression */: + case 172 /* CallExpression */: + case 237 /* JsxElement */: + case 238 /* JsxSelfClosingElement */: + case 174 /* TaggedTemplateExpression */: + case 168 /* ArrayLiteralExpression */: + case 176 /* ParenthesizedExpression */: + case 169 /* ObjectLiteralExpression */: + case 190 /* ClassExpression */: + case 177 /* FunctionExpression */: case 69 /* Identifier */: case 10 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 11 /* NoSubstitutionTemplateLiteral */: - case 183 /* TemplateExpression */: + case 187 /* TemplateExpression */: case 84 /* FalseKeyword */: case 93 /* NullKeyword */: case 97 /* ThisKeyword */: @@ -7475,7 +6812,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 188 /* ExpressionWithTypeArguments */ && + return node.kind === 192 /* ExpressionWithTypeArguments */ && node.parent.token === 83 /* ExtendsKeyword */ && isClassLike(node.parent.parent); } @@ -7498,16 +6835,16 @@ var ts; } } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 137 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 170 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 165 /* ObjectLiteralExpression */) { + if (kind === 169 /* ObjectLiteralExpression */) { return expression.properties.length === 0; } - if (kind === 164 /* ArrayLiteralExpression */) { + if (kind === 168 /* ArrayLiteralExpression */) { return expression.elements.length === 0; } return false; @@ -7517,14 +6854,10 @@ var ts; return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function isJavaScript(fileName) { - return ts.fileExtensionIs(fileName, ".js"); + function hasJavaScriptFileExtension(fileName) { + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.isJavaScript = isJavaScript; - function isTsx(fileName) { - return ts.fileExtensionIs(fileName, ".tsx"); - } - ts.isTsx = isTsx; + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; /** * 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. @@ -7559,6 +6892,47 @@ var ts; } return output; } + /** + * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph + * as the fallback implementation does not check for circular references by default. + */ + ts.stringify = typeof JSON !== "undefined" && JSON.stringify + ? JSON.stringify + : stringifyFallback; + /** + * Serialize an object graph into a JSON string. + */ + function stringifyFallback(value) { + // JSON.stringify returns `undefined` here, instead of the string "undefined". + return value === undefined ? undefined : stringifyValue(value); + } + function stringifyValue(value) { + return typeof value === "string" ? "\"" + escapeString(value) + "\"" + : typeof value === "number" ? isFinite(value) ? String(value) : "null" + : typeof value === "boolean" ? value ? "true" : "false" + : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) + : "null"; + } + function cycleCheck(cb, value) { + ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); + value.__cycle = true; + var result = cb(value); + delete value.__cycle; + return result; + } + function stringifyArray(value) { + return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; + } + function stringifyElement(memo, value) { + return (memo ? memo + "," : memo) + stringifyValue(value); + } + function stringifyObject(value) { + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + } + function stringifyProperty(memo, value, key) { + return value === undefined || typeof value === "function" || key === "__cycle" ? memo + : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); + } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** * Converts a string to a base-64 encoded ASCII string. @@ -7584,7 +6958,7 @@ var ts; else if (i + 2 >= length) { byte4 = 64; } - // Write to the ouput + // Write to the output result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); i += 3; } @@ -7770,9 +7144,9 @@ var ts; // . | \ // ----------------------------------------------------------------------*-------------------------------- // - // (Note the dots represent the newly inferrred start. + // (Note the dots represent the newly inferred start. // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the - // absolute positions at the asterixes, and the relative change between the dollar signs. Basically, we see + // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that // means: // @@ -7795,8 +7169,8 @@ var ts; // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started // that's the same as if we started at char 80 instead of 60. // - // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter - // than pusing the first edit forward to match the second, we'll push the second edit forward to match the + // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather + // than pushing the first edit forward to match the second, we'll push the second edit forward to match the // first. // // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange @@ -7825,28 +7199,34 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 137 /* TypeParameter */) { + if (d && d.kind === 139 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 215 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 219 /* InterfaceDeclaration */) { return current; } } } } ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return node.flags & 28 /* AccessibilityModifier */ && node.parent.kind === 146 /* Constructor */ && ts.isClassLike(node.parent.parent); + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; })(ts || (ts = {})); -/// /// +/// var ts; (function (ts) { - var nodeConstructors = new Array(272 /* Count */); /* @internal */ ts.parseTime = 0; - function getNodeConstructor(kind) { - return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); - } - ts.getNodeConstructor = getNodeConstructor; + var NodeConstructor; + var SourceFileConstructor; function createNode(kind, pos, end) { - return new (getNodeConstructor(kind))(pos, end); + if (kind === 252 /* SourceFile */) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } } ts.createNode = createNode; function visitNode(cbNode, node) { @@ -7884,26 +7264,26 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 137 /* TypeParameter */: + case 139 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 246 /* ShorthandPropertyAssignment */: + case 250 /* ShorthandPropertyAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 140 /* Parameter */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 249 /* PropertyAssignment */: + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -7912,24 +7292,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 177 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: + case 178 /* ArrowFunction */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -7940,302 +7320,319 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 151 /* TypeReference */: + case 153 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 150 /* TypePredicate */: + case 152 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 154 /* TypeQuery */: + case 156 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 155 /* TypeLiteral */: + case 157 /* TypeLiteral */: return visitNodes(cbNodes, node.members); - case 156 /* ArrayType */: + case 158 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 157 /* TupleType */: + case 159 /* TupleType */: return visitNodes(cbNodes, node.elementTypes); - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 160 /* UnionType */: + case 161 /* IntersectionType */: return visitNodes(cbNodes, node.types); - case 160 /* ParenthesizedType */: + case 162 /* ParenthesizedType */: return visitNode(cbNode, node.type); - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: + case 165 /* ObjectBindingPattern */: + case 166 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return visitNodes(cbNodes, node.elements); - case 165 /* ObjectLiteralExpression */: + case 169 /* ObjectLiteralExpression */: return visitNodes(cbNodes, node.properties); - case 166 /* PropertyAccessExpression */: + case 170 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 167 /* ElementAccessExpression */: + case 171 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 170 /* TaggedTemplateExpression */: + case 174 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 171 /* TypeAssertionExpression */: + case 175 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 175 /* DeleteExpression */: + case 179 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 176 /* TypeOfExpression */: + case 180 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 177 /* VoidExpression */: + case 181 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 184 /* YieldExpression */: + case 188 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 178 /* AwaitExpression */: + case 182 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 180 /* PostfixUnaryExpression */: + case 184 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 189 /* AsExpression */: + case 193 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 185 /* SpreadElementExpression */: + case 189 /* SpreadElementExpression */: return visitNode(cbNode, node.expression); - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 196 /* Block */: + case 223 /* ModuleBlock */: return visitNodes(cbNodes, node.statements); - case 248 /* SourceFile */: + case 252 /* SourceFile */: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 212 /* VariableDeclarationList */: + case 216 /* VariableDeclarationList */: return visitNodes(cbNodes, node.declarations); - case 195 /* ExpressionStatement */: + case 199 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 196 /* IfStatement */: + case 200 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 197 /* DoStatement */: + case 201 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 198 /* WhileStatement */: + case 202 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 199 /* ForStatement */: + case 203 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 200 /* ForInStatement */: + case 204 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 201 /* ForOfStatement */: + case 205 /* ForOfStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 206 /* ContinueStatement */: + case 207 /* BreakStatement */: return visitNode(cbNode, node.label); - case 204 /* ReturnStatement */: + case 208 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 205 /* WithStatement */: + case 209 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 206 /* SwitchStatement */: + case 210 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 220 /* CaseBlock */: + case 224 /* CaseBlock */: return visitNodes(cbNodes, node.clauses); - case 241 /* CaseClause */: + case 245 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 242 /* DefaultClause */: + case 246 /* DefaultClause */: return visitNodes(cbNodes, node.statements); - case 207 /* LabeledStatement */: + case 211 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 208 /* ThrowStatement */: + case 212 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 209 /* TryStatement */: + case 213 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 244 /* CatchClause */: + case 248 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 139 /* Decorator */: + case 141 /* Decorator */: return visitNode(cbNode, node.expression); - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 218 /* ClassDeclaration */: + case 190 /* 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 215 /* InterfaceDeclaration */: + case 219 /* 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 216 /* TypeAliasDeclaration */: + case 220 /* TypeAliasDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.members); - case 247 /* EnumMember */: + case 251 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 223 /* ImportClause */: + case 227 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 224 /* NamespaceImport */: + case 228 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 225 /* NamedImports */: - case 229 /* NamedExports */: + case 229 /* NamedImports */: + case 233 /* NamedExports */: return visitNodes(cbNodes, node.elements); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 230 /* ImportSpecifier */: + case 234 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 183 /* TemplateExpression */: + case 187 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 190 /* TemplateSpan */: + case 194 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 136 /* ComputedPropertyName */: + case 138 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 243 /* HeritageClause */: + case 247 /* HeritageClause */: return visitNodes(cbNodes, node.types); - case 188 /* ExpressionWithTypeArguments */: + case 192 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 232 /* ExternalModuleReference */: + case 236 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 231 /* MissingDeclaration */: + case 235 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); - case 233 /* JsxElement */: + case 237 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 234 /* JsxSelfClosingElement */: - case 235 /* JsxOpeningElement */: + case 238 /* JsxSelfClosingElement */: + case 239 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 238 /* JsxAttribute */: + case 242 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 239 /* JsxSpreadAttribute */: + case 243 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 240 /* JsxExpression */: + case 244 /* JsxExpression */: return visitNode(cbNode, node.expression); - case 237 /* JsxClosingElement */: + case 241 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 249 /* JSDocTypeExpression */: + case 253 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 253 /* JSDocUnionType */: + case 257 /* JSDocUnionType */: return visitNodes(cbNodes, node.types); - case 254 /* JSDocTupleType */: + case 258 /* JSDocTupleType */: return visitNodes(cbNodes, node.types); - case 252 /* JSDocArrayType */: + case 256 /* JSDocArrayType */: return visitNode(cbNode, node.elementType); - case 256 /* JSDocNonNullableType */: + case 260 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 255 /* JSDocNullableType */: + case 259 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 257 /* JSDocRecordType */: + case 261 /* JSDocRecordType */: return visitNodes(cbNodes, node.members); - case 259 /* JSDocTypeReference */: + case 263 /* JSDocTypeReference */: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); - case 260 /* JSDocOptionalType */: + case 264 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 261 /* JSDocFunctionType */: + case 265 /* JSDocFunctionType */: return visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 262 /* JSDocVariadicType */: + case 266 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 263 /* JSDocConstructorType */: + case 267 /* JSDocConstructorType */: return visitNode(cbNode, node.type); - case 264 /* JSDocThisType */: + case 268 /* JSDocThisType */: return visitNode(cbNode, node.type); - case 258 /* JSDocRecordMember */: + case 262 /* JSDocRecordMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 265 /* JSDocComment */: + case 269 /* JSDocComment */: return visitNodes(cbNodes, node.tags); - case 267 /* JSDocParameterTag */: + case 271 /* JSDocParameterTag */: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 268 /* JSDocReturnTag */: + case 272 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 269 /* JSDocTypeTag */: + case 273 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 270 /* JSDocTemplateTag */: + case 274 /* JSDocTemplateTag */: return visitNodes(cbNodes, node.typeParameters); } } ts.forEachChild = forEachChild; - function createSourceFile(fileName, sourceText, languageVersion, setParentNodes) { + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } var start = new Date().getTime(); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); ts.parseTime += new Date().getTime() - start; return result; } ts.createSourceFile = createSourceFile; + /* @internal */ + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js": + return 1 /* JS */; + case ".jsx": + return 2 /* JSX */; + case ".ts": + return 3 /* TS */; + case ".tsx": + return 4 /* TSX */; + default: + return 3 /* TS */; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter // indicates what changed between the 'text' that this SourceFile has and the 'newText'. // The SourceFile will be created with the compiler attempting to reuse as many nodes from @@ -8268,7 +7665,10 @@ var ts; // Share a single scanner across all calls to parse a source file. This helps speed things // up by avoiding the cost of creating/compiling scanners over and over again. var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); - var disallowInAndDecoratorContext = 1 /* DisallowIn */ | 4 /* Decorator */; + var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */; + // capture constructors in 'initializeState' to avoid null checks + var NodeConstructor; + var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; @@ -8353,14 +7753,26 @@ var ts; // Note: any errors at the end of the file that do not precede a regular node, should get // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) { - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); - var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes, scriptKind) { + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then attempt + // to get the ScriptKind from the file name. + scriptKind = scriptKind ? scriptKind : getScriptKindFromFileName(fileName); + initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); return result; } Parser.parseSourceFile = parseSourceFile; - function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) { + function getLanguageVariant(scriptKind) { + // .tsx and .jsx files are treated as jsx language variant. + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ ? 1 /* JSX */ : 0 /* Standard */; + } + function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; @@ -8368,27 +7780,28 @@ var ts; identifiers = {}; identifierCount = 0; nodeCount = 0; - contextFlags = ts.isJavaScript(fileName) ? 32 /* JavaScriptFile */ : 0 /* None */; + contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 134217728 /* JavaScriptFile */ : 0 /* None */; parseErrorBeforeNextFinishedNode = false; // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(ts.isTsx(fileName) ? 1 /* JSX */ : 0 /* Standard */); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); } function clearState() { // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. scanner.setText(""); scanner.setOnError(undefined); - // Clear any data. We don't want to accidently hold onto it for too long. + // Clear any data. We don't want to accidentally hold onto it for too long. parseDiagnostics = undefined; sourceFile = undefined; identifiers = undefined; syntaxCursor = undefined; sourceText = undefined; } - function parseSourceFileWorker(fileName, languageVersion, setParentNodes) { - sourceFile = createSourceFile(fileName, languageVersion); + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + sourceFile.flags = contextFlags; // Prime the scanner. token = nextToken(); processReferenceComments(sourceFile); @@ -8403,40 +7816,22 @@ var ts; if (setParentNodes) { fixupParentReferences(sourceFile); } - // 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 193 /* VariableStatement */: - case 213 /* FunctionDeclaration */: - case 138 /* Parameter */: - addJSDocComment(node); - } - forEachChild(node, visit); - } - } function addJSDocComment(node) { - var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); - if (comments) { - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var comment = comments_1[_i]; - var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDocComment) { - node.jsDocComment = jsDocComment; + if (contextFlags & 134217728 /* JavaScriptFile */) { + var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); + if (comments) { + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (jsDocComment) { + node.jsDocComment = jsDocComment; + } } } } + return node; } function fixupParentReferences(sourceFile) { // normally parent references are set during binding. However, for clients that only need @@ -8460,16 +7855,18 @@ var ts; } } Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion) { - var sourceFile = createNode(248 /* SourceFile */, /*pos*/ 0); - sourceFile.pos = 0; - sourceFile.end = sourceText.length; + function createSourceFile(fileName, languageVersion, scriptKind) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(252 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 /* DeclarationFile */ : 0; - sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */; + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.scriptKind = scriptKind; return sourceFile; } function setContextFlag(val, flag) { @@ -8481,16 +7878,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 1 /* DisallowIn */); + setContextFlag(val, 4194304 /* DisallowInContext */); } function setYieldContext(val) { - setContextFlag(val, 2 /* Yield */); + setContextFlag(val, 8388608 /* YieldContext */); } function setDecoratorContext(val) { - setContextFlag(val, 4 /* Decorator */); + setContextFlag(val, 16777216 /* DecoratorContext */); } function setAwaitContext(val) { - setContextFlag(val, 8 /* Await */); + setContextFlag(val, 33554432 /* AwaitContext */); } function doOutsideOfContext(context, func) { // contextFlagsToClear will contain only the context flags that are @@ -8502,10 +7899,10 @@ var ts; var contextFlagsToClear = context & contextFlags; if (contextFlagsToClear) { // clear the requested context flags - setContextFlag(false, contextFlagsToClear); + setContextFlag(/*val*/ false, contextFlagsToClear); var result = func(); // restore the context flags we just cleared - setContextFlag(true, contextFlagsToClear); + setContextFlag(/*val*/ true, contextFlagsToClear); return result; } // no need to do anything special as we are not in any of the requested contexts @@ -8521,56 +7918,50 @@ var ts; var contextFlagsToSet = context & ~contextFlags; if (contextFlagsToSet) { // set the requested context flags - setContextFlag(true, contextFlagsToSet); + setContextFlag(/*val*/ true, contextFlagsToSet); var result = func(); // reset the context flags we just set - setContextFlag(false, contextFlagsToSet); + setContextFlag(/*val*/ false, contextFlagsToSet); return result; } // no need to do anything special as we are already in all of the requested contexts return func(); } function allowInAnd(func) { - return doOutsideOfContext(1 /* DisallowIn */, func); + return doOutsideOfContext(4194304 /* DisallowInContext */, func); } function disallowInAnd(func) { - return doInsideOfContext(1 /* DisallowIn */, func); + return doInsideOfContext(4194304 /* DisallowInContext */, func); } function doInYieldContext(func) { - return doInsideOfContext(2 /* Yield */, func); - } - function doOutsideOfYieldContext(func) { - return doOutsideOfContext(2 /* Yield */, func); + return doInsideOfContext(8388608 /* YieldContext */, func); } function doInDecoratorContext(func) { - return doInsideOfContext(4 /* Decorator */, func); + return doInsideOfContext(16777216 /* DecoratorContext */, func); } function doInAwaitContext(func) { - return doInsideOfContext(8 /* Await */, func); + return doInsideOfContext(33554432 /* AwaitContext */, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(8 /* Await */, func); + return doOutsideOfContext(33554432 /* AwaitContext */, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(2 /* Yield */ | 8 /* Await */, func); - } - function doOutsideOfYieldAndAwaitContext(func) { - return doOutsideOfContext(2 /* Yield */ | 8 /* Await */, func); + return doInsideOfContext(8388608 /* YieldContext */ | 33554432 /* AwaitContext */, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(2 /* Yield */); + return inContext(8388608 /* YieldContext */); } function inDisallowInContext() { - return inContext(1 /* DisallowIn */); + return inContext(4194304 /* DisallowInContext */); } function inDecoratorContext() { - return inContext(4 /* Decorator */); + return inContext(16777216 /* DecoratorContext */); } function inAwaitContext() { - return inContext(8 /* Await */); + return inContext(33554432 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -8600,9 +7991,6 @@ var ts; function nextToken() { return token = scanner.scan(); } - function getTokenPos(pos) { - return ts.skipTrivia(sourceText, pos); - } function reScanGreaterToken() { return token = scanner.reScanGreaterToken(); } @@ -8645,16 +8033,18 @@ var ts; } return result; } - // Invokes the provided callback then unconditionally restores the parser to the state it - // was in immediately prior to invoking the callback. The result of invoking the callback - // is returned from this function. + /** Invokes the provided callback then unconditionally restores the parser to the state it + * was in immediately prior to invoking the callback. The result of invoking the callback + * is returned from this function. + */ function lookAhead(callback) { return speculationHelper(callback, /*isLookAhead*/ true); } - // Invokes the provided callback. If the callback returns something falsy, then it restores - // the parser to the state it was in immediately prior to invoking the callback. If the - // callback returns something truthy, then the parser state is not rolled back. The result - // of invoking the callback is returned from this function. + /** Invokes the provided callback. If the callback returns something falsy, then it restores + * the parser to the state it was in immediately prior to invoking the callback. If the + * callback returns something truthy, then the parser state is not rolled back. The result + * of invoking the callback is returned from this function. + */ function tryParse(callback) { return speculationHelper(callback, /*isLookAhead*/ false); } @@ -8734,24 +8124,25 @@ var ts; return parseExpected(23 /* SemicolonToken */); } } + // note: this function creates only node function createNode(kind, pos) { nodeCount++; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return new (nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)))(pos, pos); + return new NodeConstructor(kind, pos, pos); } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; if (contextFlags) { - node.parserContextFlags = contextFlags; + node.flags |= contextFlags; } // Keep track on the node if we encountered an error while parsing it. If we did, then // we cannot reuse the node incrementally. Once we've marked this node, clear out the // flag so that we don't mark any subsequent nodes. if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.parserContextFlags |= 16 /* ThisNodeHasError */; + node.flags |= 67108864 /* ThisNodeHasError */; } return node; } @@ -8808,10 +8199,10 @@ var ts; return parseIdentifierName(); } function parsePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ true); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); } function parseSimplePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ false); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); } function isSimplePropertyName() { return token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token); @@ -8820,7 +8211,7 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(136 /* ComputedPropertyName */); + var node = createNode(138 /* ComputedPropertyName */); parseExpected(19 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker @@ -8832,6 +8223,13 @@ var ts; function parseContextualModifier(t) { return token === t && tryParse(nextTokenCanFollowModifier); } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } function nextTokenCanFollowModifier() { if (token === 74 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. @@ -8851,14 +8249,10 @@ var ts; nextToken(); return canFollowModifier(); } - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); + return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifier(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { return token === 19 /* OpenBracketToken */ @@ -8890,7 +8284,7 @@ var ts; case 2 /* SwitchClauses */: return token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; case 4 /* TypeMembers */: - return isStartOfTypeMember(); + return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: // We allow semicolons as class elements (as specified by ES6) as long as we're // not in error recovery. If we're in error recovery, we don't want an errant @@ -8904,7 +8298,7 @@ var ts; case 12 /* ObjectLiteralMembers */: return token === 19 /* OpenBracketToken */ || token === 37 /* AsteriskToken */ || isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return isLiteralPropertyName(); + return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. @@ -9064,7 +8458,7 @@ var ts; function isInSomeParsingContext() { for (var kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & (1 << kind)) { - if (isListElement(kind, /* inErrorRecovery */ true) || isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; } } @@ -9078,7 +8472,7 @@ var ts; var result = []; result.pos = getNodePos(); while (!isListTerminator(kind)) { - if (isListElement(kind, /* inErrorRecovery */ false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); result.push(element); continue; @@ -9130,20 +8524,20 @@ var ts; // We can only reuse a node if it was parsed under the same strict mode that we're // currently in. i.e. if we originally parsed a node in non-strict mode, but then // the user added 'using strict' at the top of the file, then we can't use that node - // again as the presense of strict mode may cause us to parse the tokens in the file - // differetly. + // again as the presence of strict mode may cause us to parse the tokens in the file + // differently. // // Note: we *can* reuse tokens when the strict mode changes. That's because tokens // are unaffected by strict mode. It's just the parser will decide what to do with it // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.parserContextFlags & 31 /* ParserGeneratedFlags */; + var nodeContextFlags = node.flags & 62914560 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } // Ok, we have a node that looks like it could be reused. Now verify that it is valid - // in the currest list parsing context that we're currently at. + // in the current list parsing context that we're currently at. if (!canReuseNode(node, parsingContext)) { return undefined; } @@ -9218,14 +8612,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 144 /* Constructor */: - case 149 /* IndexSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 141 /* PropertyDeclaration */: - case 191 /* SemicolonClassElement */: + case 146 /* Constructor */: + case 151 /* IndexSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 143 /* PropertyDeclaration */: + case 195 /* SemicolonClassElement */: return true; - case 143 /* MethodDeclaration */: + case 145 /* 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. @@ -9240,8 +8634,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 245 /* CaseClause */: + case 246 /* DefaultClause */: return true; } } @@ -9250,58 +8644,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 193 /* VariableStatement */: - case 192 /* Block */: - case 196 /* IfStatement */: - case 195 /* ExpressionStatement */: - case 208 /* ThrowStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 194 /* EmptyStatement */: - case 209 /* TryStatement */: - case 207 /* LabeledStatement */: - case 197 /* DoStatement */: - case 210 /* DebuggerStatement */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: - case 227 /* ExportAssignment */: - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 217 /* FunctionDeclaration */: + case 197 /* VariableStatement */: + case 196 /* Block */: + case 200 /* IfStatement */: + case 199 /* ExpressionStatement */: + case 212 /* ThrowStatement */: + case 208 /* ReturnStatement */: + case 210 /* SwitchStatement */: + case 207 /* BreakStatement */: + case 206 /* ContinueStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 203 /* ForStatement */: + case 202 /* WhileStatement */: + case 209 /* WithStatement */: + case 198 /* EmptyStatement */: + case 213 /* TryStatement */: + case 211 /* LabeledStatement */: + case 201 /* DoStatement */: + case 214 /* DebuggerStatement */: + case 226 /* ImportDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 232 /* ExportDeclaration */: + case 231 /* ExportAssignment */: + case 222 /* ModuleDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 220 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 247 /* EnumMember */; + return node.kind === 251 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 148 /* ConstructSignature */: - case 142 /* MethodSignature */: - case 149 /* IndexSignature */: - case 140 /* PropertySignature */: - case 147 /* CallSignature */: + case 150 /* ConstructSignature */: + case 144 /* MethodSignature */: + case 151 /* IndexSignature */: + case 142 /* PropertySignature */: + case 149 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 211 /* VariableDeclaration */) { + if (node.kind !== 215 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -9322,7 +8716,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 138 /* Parameter */) { + if (node.kind !== 140 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -9370,14 +8764,14 @@ var ts; } ; // Parses a comma-delimited list of elements - function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimeter) { + function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { - if (isListElement(kind, /* inErrorRecovery */ false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(24 /* CommaToken */)) { @@ -9395,7 +8789,7 @@ var ts; // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. - if (considerSemicolonAsDelimeter && token === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -9439,7 +8833,7 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); while (parseOptional(21 /* DotToken */)) { - var node = createNode(135 /* QualifiedName */, entity.pos); + var node = createNode(137 /* QualifiedName */, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -9472,14 +8866,14 @@ var ts; // Report that we need an identifier. However, report it right after the dot, // and not on the next token. This is because the next token might actually // be an identifier and the error would be quite confusing. - return createMissingNode(69 /* Identifier */, /*reportAtCurrentToken*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(183 /* TemplateExpression */); - template.head = parseLiteralNode(); + var template = createNode(187 /* TemplateExpression */); + template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = []; templateSpans.pos = getNodePos(); @@ -9491,12 +8885,12 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(190 /* TemplateSpan */); + var span = createNode(194 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token === 16 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseLiteralNode(); + literal = parseTemplateLiteralFragment(); } else { literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); @@ -9504,8 +8898,17 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(164 /* StringLiteralType */, /*internName*/ true); + } function parseLiteralNode(internName) { - var node = createNode(token); + return parseLiteralLikeNode(token, internName); + } + function parseTemplateLiteralFragment() { + return parseLiteralLikeNode(token, /*internName*/ false); + } + function parseLiteralLikeNode(kind, internName) { + var node = createNode(kind); var text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -9526,35 +8929,40 @@ var ts; if (node.kind === 8 /* NumericLiteral */ && sourceText.charCodeAt(tokenPos) === 48 /* _0 */ && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - node.flags |= 32768 /* OctalLiteral */; + node.isOctalLiteral = true; } return node; } // TYPES - function parseTypeReferenceOrTypePredicate() { + function parseTypeReference() { var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); - if (typeName.kind === 69 /* Identifier */ && token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var node_1 = createNode(150 /* TypePredicate */, typeName.pos); - node_1.parameterName = typeName; - node_1.type = parseType(); - return finishNode(node_1); - } - var node = createNode(151 /* TypeReference */, typeName.pos); + var node = createNode(153 /* TypeReference */, typeName.pos); node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } return finishNode(node); } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(152 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(163 /* ThisType */); + nextToken(); + return finishNode(node); + } function parseTypeQuery() { - var node = createNode(154 /* TypeQuery */); + var node = createNode(156 /* TypeQuery */); parseExpected(101 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(137 /* TypeParameter */); + var node = createNode(139 /* TypeParameter */); node.name = parseIdentifier(); if (parseOptional(83 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -9584,14 +8992,12 @@ var ts; } function parseParameterType() { if (parseOptional(54 /* ColonToken */)) { - return token === 9 /* StringLiteral */ - ? parseLiteralNode(/*internName*/ true) - : parseType(); + return parseType(); } return undefined; } function isStartOfParameter() { - return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifier(token) || token === 55 /* AtToken */; + return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */; } function setModifiers(node, modifiers) { if (modifiers) { @@ -9600,14 +9006,14 @@ var ts; } } function parseParameter() { - var node = createNode(138 /* Parameter */); + var node = createNode(140 /* Parameter */); node.decorators = parseDecorators(); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifier(token)) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { // in cases like // 'use strict' // function foo(static) @@ -9629,7 +9035,7 @@ var ts; // contexts. In addition, parameter initializers are semantically disallowed in // overload signatures. So parameter initializers are transitively disallowed in // ambient contexts. - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseBindingElementInitializer(inParameter) { return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); @@ -9643,10 +9049,10 @@ var ts; signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); if (returnTokenRequired) { parseExpected(returnToken); - signature.type = parseType(); + signature.type = parseTypeOrTypePredicate(); } else if (parseOptional(returnToken)) { - signature.type = parseType(); + signature.type = parseTypeOrTypePredicate(); } } function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { @@ -9694,7 +9100,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 148 /* ConstructSignature */) { + if (kind === 150 /* ConstructSignature */) { parseExpected(92 /* NewKeyword */); } fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); @@ -9728,7 +9134,7 @@ var ts; if (token === 22 /* DotDotDotToken */ || token === 20 /* CloseBracketToken */) { return true; } - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -9758,7 +9164,7 @@ var ts; return token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 20 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(149 /* IndexSignature */, fullStart); + var node = createNode(151 /* IndexSignature */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); @@ -9766,109 +9172,87 @@ var ts; parseTypeMemberSemicolon(); return finishNode(node); } - function parsePropertyOrMethodSignature() { - var fullStart = scanner.getStartPos(); + function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53 /* QuestionToken */); if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { - var method = createNode(142 /* MethodSignature */, fullStart); + var method = createNode(144 /* MethodSignature */, fullStart); + setModifiers(method, modifiers); method.name = name; method.questionToken = questionToken; - // Method signatues don't exist in expression contexts. So they have neither + // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); parseTypeMemberSemicolon(); return finishNode(method); } else { - var property = createNode(140 /* PropertySignature */, fullStart); + var property = createNode(142 /* PropertySignature */, fullStart); + setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); + if (token === 56 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + property.initializer = parseNonParameterInitializer(); + } parseTypeMemberSemicolon(); return finishNode(property); } } - function isStartOfTypeMember() { - switch (token) { - case 17 /* OpenParenToken */: - case 25 /* LessThanToken */: - case 19 /* OpenBracketToken */: - return true; - default: - if (ts.isModifier(token)) { - var result = lookAhead(isStartOfIndexSignatureDeclaration); - if (result) { - return result; - } - } - return isLiteralPropertyName() && lookAhead(isTypeMemberWithLiteralPropertyName); + function isTypeMemberStart() { + var idToken; + // Return true if we have the start of a signature member + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + return true; } - } - function isStartOfIndexSignatureDeclaration() { - while (ts.isModifier(token)) { + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier + while (ts.isModifierKind(token)) { + idToken = token; nextToken(); } - return isIndexSignature(); - } - function isTypeMemberWithLiteralPropertyName() { - nextToken(); - return token === 17 /* OpenParenToken */ || - token === 25 /* LessThanToken */ || - token === 53 /* QuestionToken */ || - token === 54 /* ColonToken */ || - canParseSemicolon(); + // Index signatures and computed property names are type members + if (token === 19 /* OpenBracketToken */) { + return true; + } + // Try to get the first property-like token following all modifiers + if (isLiteralPropertyName()) { + idToken = token; + nextToken(); + } + // If we were able to get any potential identifier, check that it is + // the start of a member declaration + if (idToken) { + return token === 17 /* OpenParenToken */ || + token === 25 /* LessThanToken */ || + token === 53 /* QuestionToken */ || + token === 54 /* ColonToken */ || + canParseSemicolon(); + } + return false; } function parseTypeMember() { - switch (token) { - case 17 /* OpenParenToken */: - case 25 /* LessThanToken */: - return parseSignatureMember(147 /* CallSignature */); - case 19 /* OpenBracketToken */: - // Indexer or computed property - return isIndexSignature() - ? parseIndexSignatureDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined) - : parsePropertyOrMethodSignature(); - case 92 /* NewKeyword */: - if (lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(148 /* ConstructSignature */); - } - // fall through. - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - return parsePropertyOrMethodSignature(); - default: - // Index declaration as allowed as a type member. But as per the grammar, - // they also allow modifiers. So we have to check for an index declaration - // that might be following modifiers. This ensures that things work properly - // when incrementally parsing as the parser will produce the Index declaration - // if it has the same text regardless of whether it is inside a class or an - // object type. - if (ts.isModifier(token)) { - var result = tryParse(parseIndexSignatureWithModifiers); - if (result) { - return result; - } - } - if (ts.tokenIsIdentifierOrKeyword(token)) { - return parsePropertyOrMethodSignature(); - } + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + return parseSignatureMember(149 /* CallSignature */); } - } - function parseIndexSignatureWithModifiers() { - var fullStart = scanner.getStartPos(); - var decorators = parseDecorators(); + if (token === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { + return parseSignatureMember(150 /* ConstructSignature */); + } + var fullStart = getNodePos(); var modifiers = parseModifiers(); - return isIndexSignature() - ? parseIndexSignatureDeclaration(fullStart, decorators, modifiers) - : undefined; + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, /*decorators*/ undefined, modifiers); + } + return parsePropertyOrMethodSignature(fullStart, modifiers); } function isStartOfConstructSignature() { nextToken(); return token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */; } function parseTypeLiteral() { - var node = createNode(155 /* TypeLiteral */); + var node = createNode(157 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -9884,12 +9268,12 @@ var ts; return members; } function parseTupleType() { - var node = createNode(157 /* TupleType */); + var node = createNode(159 /* TupleType */); node.elementTypes = parseBracketedList(19 /* TupleElementTypes */, parseType, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(160 /* ParenthesizedType */); + var node = createNode(162 /* ParenthesizedType */); parseExpected(17 /* OpenParenToken */); node.type = parseType(); parseExpected(18 /* CloseParenToken */); @@ -9897,7 +9281,7 @@ var ts; } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 153 /* ConstructorType */) { + if (kind === 155 /* ConstructorType */) { parseExpected(92 /* NewKeyword */); } fillSignature(34 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); @@ -9910,16 +9294,26 @@ var ts; function parseNonArrayType() { switch (token) { case 117 /* AnyKeyword */: - case 130 /* StringKeyword */: - case 128 /* NumberKeyword */: + case 131 /* StringKeyword */: + case 129 /* NumberKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReferenceOrTypePredicate(); + return node || parseTypeReference(); + case 9 /* StringLiteral */: + return parseStringLiteralTypeNode(); case 103 /* VoidKeyword */: - case 97 /* ThisKeyword */: return parseTokenNode(); + case 97 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } case 101 /* TypeOfKeyword */: return parseTypeQuery(); case 15 /* OpenBraceToken */: @@ -9929,16 +9323,16 @@ var ts; case 17 /* OpenParenToken */: return parseParenthesizedType(); default: - return parseTypeReferenceOrTypePredicate(); + return parseTypeReference(); } } function isStartOfType() { switch (token) { case 117 /* AnyKeyword */: - case 130 /* StringKeyword */: - case 128 /* NumberKeyword */: + case 131 /* StringKeyword */: + case 129 /* NumberKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: case 103 /* VoidKeyword */: case 97 /* ThisKeyword */: case 101 /* TypeOfKeyword */: @@ -9946,6 +9340,7 @@ var ts; case 19 /* OpenBracketToken */: case 25 /* LessThanToken */: case 92 /* NewKeyword */: + case 9 /* StringLiteral */: return true; case 17 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, @@ -9963,7 +9358,7 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(19 /* OpenBracketToken */)) { parseExpected(20 /* CloseBracketToken */); - var node = createNode(156 /* ArrayType */, type.pos); + var node = createNode(158 /* ArrayType */, type.pos); node.elementType = type; type = finishNode(node); } @@ -9985,10 +9380,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(159 /* IntersectionType */, parseArrayTypeOrHigher, 46 /* AmpersandToken */); + return parseUnionOrIntersectionType(161 /* IntersectionType */, parseArrayTypeOrHigher, 46 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(158 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); + return parseUnionOrIntersectionType(160 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); } function isStartOfFunctionType() { if (token === 25 /* LessThanToken */) { @@ -9996,6 +9391,23 @@ var ts; } return token === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } + function skipParameterStart() { + if (ts.isModifierKind(token)) { + // Skip modifiers + parseModifiers(); + } + if (isIdentifier()) { + nextToken(); + return true; + } + if (token === 19 /* OpenBracketToken */ || token === 15 /* OpenBraceToken */) { + // Return true if we can parse an array or object binding pattern with no errors + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } function isUnambiguouslyStartOfFunctionType() { nextToken(); if (token === 18 /* CloseParenToken */ || token === 22 /* DotDotDotToken */) { @@ -10003,39 +9415,58 @@ var ts; // ( ... return true; } - if (isIdentifier() || ts.isModifier(token)) { - nextToken(); + if (skipParameterStart()) { + // We successfully skipped modifiers (if any) and an identifier or binding pattern, + // now see if we have something that indicates a parameter declaration if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || - token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */ || - isIdentifier() || ts.isModifier(token)) { - // ( id : - // ( id , - // ( id ? - // ( id = - // ( modifier id + token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */) { + // ( xxx : + // ( xxx , + // ( xxx ? + // ( xxx = return true; } if (token === 18 /* CloseParenToken */) { nextToken(); if (token === 34 /* EqualsGreaterThanToken */) { - // ( id ) => + // ( xxx ) => return true; } } } return false; } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(152 /* TypePredicate */, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } function parseType() { // The rules about 'yield' only apply to actual code/expression contexts. They don't // apply to 'type' contexts. So we disable these parameters here before moving on. - return doOutsideOfContext(10 /* TypeExcludesFlags */, parseTypeWorker); + return doOutsideOfContext(41943040 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(152 /* FunctionType */); + return parseFunctionOrConstructorType(154 /* FunctionType */); } if (token === 92 /* NewKeyword */) { - return parseFunctionOrConstructorType(153 /* ConstructorType */); + return parseFunctionOrConstructorType(155 /* ConstructorType */); } return parseUnionTypeOrHigher(); } @@ -10108,9 +9539,6 @@ var ts; token !== 55 /* AtToken */ && isStartOfExpression(); } - function allowInAndParseExpression() { - return allowInAnd(parseExpression); - } function parseExpression() { // Expression[in]: // AssignmentExpression[in] @@ -10118,7 +9546,7 @@ var ts; // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; @@ -10126,7 +9554,7 @@ var ts; expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } return expr; } @@ -10203,7 +9631,7 @@ var ts; } function isYieldExpression() { if (token === 114 /* YieldKeyword */) { - // If we have a 'yield' keyword, and htis is a context where yield expressions are + // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { return true; @@ -10221,7 +9649,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. + // don't accidentally consume something legal. return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); } return false; @@ -10231,7 +9659,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(184 /* YieldExpression */); + var node = createNode(188 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -10245,20 +9673,20 @@ var ts; } else { // if the next token is not on the same line as yield. or we don't have an '*' or - // the start of an expressin, then this is just a simple "yield" expression. + // the start of an expression, then this is just a simple "yield" expression. return finishNode(node); } } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(174 /* ArrowFunction */, identifier.pos); - var parameter = createNode(138 /* Parameter */, identifier.pos); + var node = createNode(178 /* ArrowFunction */, identifier.pos); + var parameter = createNode(140 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = [parameter]; node.parameters.pos = parameter.pos; node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, false, ts.Diagnostics._0_expected, "=>"); + node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ false); return finishNode(node); } @@ -10404,7 +9832,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(174 /* ArrowFunction */); + var node = createNode(178 /* ArrowFunction */); setModifiers(node, parseModifiersForArrowFunction()); var isAsync = !!(node.flags & 256 /* Async */); // Arrow functions are never generators. @@ -10470,7 +9898,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(182 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(186 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -10483,7 +9911,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 90 /* InKeyword */ || t === 134 /* OfKeyword */; + return t === 90 /* InKeyword */ || t === 136 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -10494,7 +9922,7 @@ var ts; // Check the precedence to see if we should "take" this operator // - For left associative operator (all operator but **), consume the operator, // recursively call the function below, and parse binaryExpression as a rightOperand - // of the caller if the new precendence of the operator is greater then or equal to the current precendence. + // of the caller if the new precedence of the operator is greater then or equal to the current precedence. // For example: // a - b - c; // ^token; leftOperand = b. Return b to the caller as a rightOperand @@ -10503,8 +9931,8 @@ var ts; // a - b * c; // ^token; leftOperand = b. Return b * c to the caller as a rightOperand // - For right associative operator (**), consume the operator, recursively call the function - // and parse binaryExpression as a rightOperand of the caller if the new precendence of - // the operator is strictly grater than the current precendence + // and parse binaryExpression as a rightOperand of the caller if the new precedence of + // the operator is strictly grater than the current precedence // For example: // a ** b ** c; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand @@ -10591,39 +10019,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(181 /* BinaryExpression */, left.pos); + var node = createNode(185 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(189 /* AsExpression */, left.pos); + var node = createNode(193 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(179 /* PrefixUnaryExpression */); + var node = createNode(183 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(175 /* DeleteExpression */); + var node = createNode(179 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(176 /* TypeOfExpression */); + var node = createNode(180 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(177 /* VoidExpression */); + var node = createNode(181 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -10639,7 +10067,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(178 /* AwaitExpression */); + var node = createNode(182 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -10664,9 +10092,8 @@ var ts; var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === 38 /* AsteriskAsteriskToken */) { - var diagnostic; var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 171 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 175 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -10722,7 +10149,7 @@ var ts; */ function isIncrementExpression() { // This function is called inside parseUnaryExpression to decide - // whether to call parseSimpleUnaryExpression or call parseIncrmentExpression directly + // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: @@ -10756,7 +10183,7 @@ var ts; */ function parseIncrementExpression() { if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { - var node = createNode(179 /* PrefixUnaryExpression */); + var node = createNode(183 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -10769,7 +10196,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(180 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(184 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -10873,24 +10300,37 @@ 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(166 /* PropertyAccessExpression */, expression.pos); + var node = createNode(170 /* PropertyAccessExpression */, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 69 /* Identifier */) { + return lhs.text === rhs.text; + } + return lhs.right.text === rhs.right.text && + tagNamesAreEquivalent(lhs.left, rhs.left); + } function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 235 /* JsxOpeningElement */) { - var node = createNode(233 /* JsxElement */, opening.pos); + if (opening.kind === 239 /* JsxOpeningElement */) { + var node = createNode(237 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 238 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -10905,7 +10345,7 @@ var ts; var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(181 /* BinaryExpression */, result.pos); + var badNode = createNode(185 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -10917,13 +10357,13 @@ var ts; return result; } function parseJsxText() { - var node = createNode(236 /* JsxText */, scanner.getStartPos()); + var node = createNode(240 /* JsxText */, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token) { - case 236 /* JsxText */: + case 240 /* JsxText */: return parseJsxText(); case 15 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); @@ -10940,10 +10380,13 @@ var ts; while (true) { token = scanner.reScanJsxToken(); if (token === 26 /* LessThanSlashToken */) { + // Closing tag break; } else if (token === 1 /* EndOfFileToken */) { - parseErrorAtCurrentToken(ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } result.push(parseJsxChild()); @@ -10962,7 +10405,7 @@ var ts; // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(235 /* JsxOpeningElement */, fullStart); + node = createNode(239 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { @@ -10971,10 +10414,10 @@ var ts; parseExpected(27 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(234 /* JsxSelfClosingElement */, fullStart); + node = createNode(238 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -10985,7 +10428,7 @@ var ts; var elementName = parseIdentifierName(); while (parseOptional(21 /* DotToken */)) { scanJsxIdentifier(); - var node = createNode(135 /* QualifiedName */, elementName.pos); + var node = createNode(137 /* QualifiedName */, elementName.pos); node.left = elementName; node.right = parseIdentifierName(); elementName = finishNode(node); @@ -10993,16 +10436,16 @@ var ts; return elementName; } function parseJsxExpression(inExpressionContext) { - var node = createNode(240 /* JsxExpression */); + var node = createNode(244 /* JsxExpression */); parseExpected(15 /* OpenBraceToken */); if (token !== 16 /* CloseBraceToken */) { - node.expression = parseExpression(); + node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { parseExpected(16 /* CloseBraceToken */); } else { - parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*advance*/ false); + parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); @@ -11012,7 +10455,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(238 /* JsxAttribute */); + var node = createNode(242 /* JsxAttribute */); node.name = parseIdentifierName(); if (parseOptional(56 /* EqualsToken */)) { switch (token) { @@ -11027,7 +10470,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(239 /* JsxSpreadAttribute */); + var node = createNode(243 /* JsxSpreadAttribute */); parseExpected(15 /* OpenBraceToken */); parseExpected(22 /* DotDotDotToken */); node.expression = parseExpression(); @@ -11035,20 +10478,20 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(237 /* JsxClosingElement */); + var node = createNode(241 /* JsxClosingElement */); parseExpected(26 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { parseExpected(27 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(171 /* TypeAssertionExpression */); + var node = createNode(175 /* TypeAssertionExpression */); parseExpected(25 /* LessThanToken */); node.type = parseType(); parseExpected(27 /* GreaterThanToken */); @@ -11059,7 +10502,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(21 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(166 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(170 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -11068,7 +10511,7 @@ var ts; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(19 /* OpenBracketToken */)) { - var indexedAccess = createNode(167 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(171 /* 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. @@ -11084,7 +10527,7 @@ var ts; continue; } if (token === 11 /* NoSubstitutionTemplateLiteral */ || token === 12 /* TemplateHead */) { - var tagExpression = createNode(170 /* TaggedTemplateExpression */, expression.pos); + var tagExpression = createNode(174 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 11 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() @@ -11107,7 +10550,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(168 /* CallExpression */, expression.pos); + var callExpr = createNode(172 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -11115,7 +10558,7 @@ var ts; continue; } else if (token === 17 /* OpenParenToken */) { - var callExpr = createNode(168 /* CallExpression */, expression.pos); + var callExpr = createNode(172 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -11139,7 +10582,7 @@ var ts; // If it doesn't have the closing > then it's definitely not an type argument list. return undefined; } - // If we have a '<', then only parse this as a arugment list if the type arguments + // If we have a '<', then only parse this as a argument list if the type arguments // are complete and we have an open paren. if we don't, rewind and return nothing. return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments @@ -11225,41 +10668,42 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(172 /* ParenthesizedExpression */); + var node = createNode(176 /* ParenthesizedExpression */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(185 /* SpreadElementExpression */); + var node = createNode(189 /* SpreadElementExpression */); parseExpected(22 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token === 24 /* CommaToken */ ? createNode(187 /* OmittedExpression */) : + token === 24 /* CommaToken */ ? createNode(191 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(164 /* ArrayLiteralExpression */); + var node = createNode(168 /* ArrayLiteralExpression */); parseExpected(19 /* OpenBracketToken */); - if (scanner.hasPrecedingLineBreak()) - node.flags |= 1024 /* MultiLine */; + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); parseExpected(20 /* CloseBracketToken */); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(123 /* GetKeyword */)) { - return parseAccessorDeclaration(145 /* GetAccessor */, fullStart, decorators, modifiers); + return parseAccessorDeclaration(147 /* GetAccessor */, fullStart, decorators, modifiers); } - else if (parseContextualModifier(129 /* SetKeyword */)) { - return parseAccessorDeclaration(146 /* SetAccessor */, fullStart, decorators, modifiers); + else if (parseContextualModifier(130 /* SetKeyword */)) { + return parseAccessorDeclaration(148 /* SetAccessor */, fullStart, decorators, modifiers); } return undefined; } @@ -11273,7 +10717,6 @@ var ts; } var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); - var nameToken = token; var propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); @@ -11287,7 +10730,7 @@ var ts; // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 /* CommaToken */ || token === 16 /* CloseBraceToken */ || token === 56 /* EqualsToken */); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(246 /* ShorthandPropertyAssignment */, fullStart); + var shorthandDeclaration = createNode(250 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; var equalsToken = parseOptionalToken(56 /* EqualsToken */); @@ -11295,24 +10738,25 @@ var ts; shorthandDeclaration.equalsToken = equalsToken; shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return finishNode(shorthandDeclaration); + return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(245 /* PropertyAssignment */, fullStart); + var propertyAssignment = createNode(249 /* PropertyAssignment */, fullStart); + propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(54 /* ColonToken */); propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return finishNode(propertyAssignment); + return addJSDocComment(finishNode(propertyAssignment)); } } function parseObjectLiteralExpression() { - var node = createNode(165 /* ObjectLiteralExpression */); + var node = createNode(169 /* ObjectLiteralExpression */); parseExpected(15 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { - node.flags |= 1024 /* MultiLine */; + node.multiLine = true; } - node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimeter*/ true); + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); parseExpected(16 /* CloseBraceToken */); return finishNode(node); } @@ -11324,9 +10768,9 @@ var ts; // function BindingIdentifier[opt](FormalParameters){ FunctionBody } var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } - var node = createNode(173 /* FunctionExpression */); + var node = createNode(177 /* FunctionExpression */); setModifiers(node, parseModifiers()); parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); @@ -11340,15 +10784,15 @@ var ts; fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(169 /* NewExpression */); + var node = createNode(173 /* NewExpression */); parseExpected(92 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -11359,7 +10803,7 @@ var ts; } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(192 /* Block */); + var node = createNode(196 /* Block */); if (parseExpected(15 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); @@ -11378,23 +10822,23 @@ var ts; // arrow function. The body of the function is not in [Decorator] context. var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return block; } function parseEmptyStatement() { - var node = createNode(194 /* EmptyStatement */); + var node = createNode(198 /* EmptyStatement */); parseExpected(23 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(196 /* IfStatement */); + var node = createNode(200 /* IfStatement */); parseExpected(88 /* IfKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -11404,7 +10848,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(197 /* DoStatement */); + var node = createNode(201 /* DoStatement */); parseExpected(79 /* DoKeyword */); node.statement = parseStatement(); parseExpected(104 /* WhileKeyword */); @@ -11419,7 +10863,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(198 /* WhileStatement */); + var node = createNode(202 /* WhileStatement */); parseExpected(104 /* WhileKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -11442,21 +10886,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(90 /* InKeyword */)) { - var forInStatement = createNode(200 /* ForInStatement */, pos); + var forInStatement = createNode(204 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(134 /* OfKeyword */)) { - var forOfStatement = createNode(201 /* ForOfStatement */, pos); + else if (parseOptional(136 /* OfKeyword */)) { + var forOfStatement = createNode(205 /* ForOfStatement */, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(18 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(199 /* ForStatement */, pos); + var forStatement = createNode(203 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(23 /* SemicolonToken */); if (token !== 23 /* SemicolonToken */ && token !== 18 /* CloseParenToken */) { @@ -11474,7 +10918,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); + parseExpected(kind === 207 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -11482,7 +10926,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(204 /* ReturnStatement */); + var node = createNode(208 /* ReturnStatement */); parseExpected(94 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -11491,7 +10935,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(205 /* WithStatement */); + var node = createNode(209 /* WithStatement */); parseExpected(105 /* WithKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -11500,7 +10944,7 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(241 /* CaseClause */); + var node = createNode(245 /* CaseClause */); parseExpected(71 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(54 /* ColonToken */); @@ -11508,7 +10952,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(242 /* DefaultClause */); + var node = createNode(246 /* DefaultClause */); parseExpected(77 /* DefaultKeyword */); parseExpected(54 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); @@ -11518,12 +10962,12 @@ var ts; return token === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(206 /* SwitchStatement */); + var node = createNode(210 /* SwitchStatement */); parseExpected(96 /* SwitchKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); - var caseBlock = createNode(220 /* CaseBlock */, scanner.getStartPos()); + var caseBlock = createNode(224 /* CaseBlock */, scanner.getStartPos()); parseExpected(15 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(16 /* CloseBraceToken */); @@ -11538,7 +10982,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(208 /* ThrowStatement */); + var node = createNode(212 /* ThrowStatement */); parseExpected(98 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -11546,7 +10990,7 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(209 /* TryStatement */); + var node = createNode(213 /* TryStatement */); parseExpected(100 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -11559,7 +11003,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(244 /* CatchClause */); + var result = createNode(248 /* CatchClause */); parseExpected(72 /* CatchKeyword */); if (parseExpected(17 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); @@ -11569,7 +11013,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(210 /* DebuggerStatement */); + var node = createNode(214 /* DebuggerStatement */); parseExpected(76 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -11581,16 +11025,16 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 69 /* Identifier */ && parseOptional(54 /* ColonToken */)) { - var labeledStatement = createNode(207 /* LabeledStatement */, fullStart); + var labeledStatement = createNode(211 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); - return finishNode(labeledStatement); + return addJSDocComment(finishNode(labeledStatement)); } else { - var expressionStatement = createNode(195 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(199 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); - return finishNode(expressionStatement); + return addJSDocComment(finishNode(expressionStatement)); } } function nextTokenIsIdentifierOrKeywordOnSameLine() { @@ -11637,7 +11081,7 @@ var ts; // // could be legal, it would add complexity for very little gain. case 107 /* InterfaceKeyword */: - case 132 /* TypeKeyword */: + case 133 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); case 125 /* ModuleKeyword */: case 126 /* NamespaceKeyword */: @@ -11648,12 +11092,15 @@ var ts; case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: case 112 /* PublicKeyword */: + case 127 /* ReadonlyKeyword */: nextToken(); // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; + case 135 /* GlobalKeyword */: + return nextToken() === 15 /* OpenBraceToken */; case 89 /* ImportKeyword */: nextToken(); return token === 9 /* StringLiteral */ || token === 37 /* AsteriskToken */ || @@ -11712,13 +11159,15 @@ var ts; case 107 /* InterfaceKeyword */: case 125 /* ModuleKeyword */: case 126 /* NamespaceKeyword */: - case 132 /* TypeKeyword */: + case 133 /* TypeKeyword */: + case 135 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: case 113 /* StaticKeyword */: + case 127 /* ReadonlyKeyword */: // When these don't start a declaration, they may be the start of a class member if an identifier // immediately follows. Otherwise they're an identifier in an expression statement. return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); @@ -11761,9 +11210,9 @@ var ts; case 86 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 75 /* ContinueKeyword */: - return parseBreakOrContinueStatement(202 /* ContinueStatement */); + return parseBreakOrContinueStatement(206 /* ContinueStatement */); case 70 /* BreakKeyword */: - return parseBreakOrContinueStatement(203 /* BreakStatement */); + return parseBreakOrContinueStatement(207 /* BreakStatement */); case 94 /* ReturnKeyword */: return parseReturnStatement(); case 105 /* WithKeyword */: @@ -11783,7 +11232,7 @@ var ts; return parseDeclaration(); case 118 /* AsyncKeyword */: case 107 /* InterfaceKeyword */: - case 132 /* TypeKeyword */: + case 133 /* TypeKeyword */: case 125 /* ModuleKeyword */: case 126 /* NamespaceKeyword */: case 122 /* DeclareKeyword */: @@ -11796,6 +11245,8 @@ var ts; case 112 /* PublicKeyword */: case 115 /* AbstractKeyword */: case 113 /* StaticKeyword */: + case 127 /* ReadonlyKeyword */: + case 135 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -11818,10 +11269,11 @@ var ts; return parseClassDeclaration(fullStart, decorators, modifiers); case 107 /* InterfaceKeyword */: return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 132 /* TypeKeyword */: + case 133 /* TypeKeyword */: return parseTypeAliasDeclaration(fullStart, decorators, modifiers); case 81 /* EnumKeyword */: return parseEnumDeclaration(fullStart, decorators, modifiers); + case 135 /* GlobalKeyword */: case 125 /* ModuleKeyword */: case 126 /* NamespaceKeyword */: return parseModuleDeclaration(fullStart, decorators, modifiers); @@ -11836,7 +11288,7 @@ var ts; 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(231 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(235 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -11858,17 +11310,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token === 24 /* CommaToken */) { - return createNode(187 /* OmittedExpression */); + return createNode(191 /* OmittedExpression */); } - var node = createNode(163 /* BindingElement */); + var node = createNode(167 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(/*inParameter*/ false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(163 /* BindingElement */); - // TODO(andersh): Handle computed properties + var node = createNode(167 /* BindingElement */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 54 /* ColonToken */) { @@ -11883,14 +11334,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(161 /* ObjectBindingPattern */); + var node = createNode(165 /* ObjectBindingPattern */); parseExpected(15 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(16 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(162 /* ArrayBindingPattern */); + var node = createNode(166 /* ArrayBindingPattern */); parseExpected(19 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(20 /* CloseBracketToken */); @@ -11909,7 +11360,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(211 /* VariableDeclaration */); + var node = createNode(215 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -11918,15 +11369,15 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(212 /* VariableDeclarationList */); + var node = createNode(216 /* VariableDeclarationList */); switch (token) { case 102 /* VarKeyword */: break; case 108 /* LetKeyword */: - node.flags |= 8192 /* Let */; + node.flags |= 1024 /* Let */; break; case 74 /* ConstKeyword */: - node.flags |= 16384 /* Const */; + node.flags |= 2048 /* Const */; break; default: ts.Debug.fail(); @@ -11941,7 +11392,7 @@ 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 === 134 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token === 136 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -11956,15 +11407,15 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 18 /* CloseParenToken */; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(193 /* VariableStatement */, fullStart); + var node = createNode(197 /* VariableStatement */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(213 /* FunctionDeclaration */, fullStart); + var node = createNode(217 /* FunctionDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(87 /* FunctionKeyword */); @@ -11974,19 +11425,19 @@ var ts; var isAsync = !!(node.flags & 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(144 /* Constructor */, pos); + var node = createNode(146 /* Constructor */, pos); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(121 /* ConstructorKeyword */); fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, ts.Diagnostics.or_expected); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(143 /* MethodDeclaration */, fullStart); + var method = createNode(145 /* MethodDeclaration */, fullStart); method.decorators = decorators; setModifiers(method, modifiers); method.asteriskToken = asteriskToken; @@ -11996,10 +11447,10 @@ var ts; var isAsync = !!(method.flags & 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); - return finishNode(method); + return addJSDocComment(finishNode(method)); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(141 /* PropertyDeclaration */, fullStart); + var property = createNode(143 /* PropertyDeclaration */, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; @@ -12010,13 +11461,13 @@ var ts; // 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]; + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. - property.initializer = modifiers && modifiers.flags & 64 /* Static */ + property.initializer = modifiers && modifiers.flags & 32 /* Static */ ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(2 /* Yield */ | 1 /* DisallowIn */, parseNonParameterInitializer); + : doOutsideOfContext(8388608 /* YieldContext */ | 4194304 /* DisallowInContext */, parseNonParameterInitializer); parseSemicolon(); return finishNode(property); } @@ -12051,6 +11502,7 @@ var ts; case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: case 113 /* StaticKeyword */: + case 127 /* ReadonlyKeyword */: return true; default: return false; @@ -12062,7 +11514,7 @@ var ts; return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { idToken = token; // If the idToken is a class modifier (protected, private, public, and static), it is // certain that we are starting to parse class member. This allows better error recovery @@ -12091,7 +11543,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 === 129 /* SetKeyword */ || idToken === 123 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 130 /* SetKeyword */ || idToken === 123 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along @@ -12123,9 +11575,9 @@ var ts; } if (!decorators) { decorators = []; - decorators.pos = scanner.getStartPos(); + decorators.pos = decoratorStart; } - var decorator = createNode(139 /* Decorator */, decoratorStart); + var decorator = createNode(141 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -12134,14 +11586,30 @@ var ts; } return decorators; } - function parseModifiers() { + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token; - if (!parseAnyContextualModifier()) { - break; + if (token === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } } if (!modifiers) { modifiers = []; @@ -12174,13 +11642,13 @@ var ts; } function parseClassElement() { if (token === 23 /* SemicolonToken */) { - var result = createNode(191 /* SemicolonClassElement */); + var result = createNode(195 /* SemicolonClassElement */); nextToken(); return finishNode(result); } var fullStart = getNodePos(); var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; @@ -12212,10 +11680,10 @@ var ts; return parseClassDeclarationOrExpression( /*fullStart*/ scanner.getStartPos(), /*decorators*/ undefined, - /*modifiers*/ undefined, 186 /* ClassExpression */); + /*modifiers*/ undefined, 190 /* ClassExpression */); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 214 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 218 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); @@ -12240,8 +11708,8 @@ var ts; // implements is a future reserved word so // 'class implements' might mean either // - class expression with omitted name, 'implements' starts heritage clause - // - class with name 'implements' - // 'isImplementsClause' helps to disambiguate between these two cases + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases return isIdentifier() && !isImplementsClause() ? parseIdentifier() : undefined; @@ -12257,12 +11725,9 @@ var ts; } return undefined; } - function parseHeritageClausesWorker() { - return parseList(20 /* HeritageClauses */, parseHeritageClause); - } function parseHeritageClause() { if (token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */) { - var node = createNode(243 /* HeritageClause */); + var node = createNode(247 /* HeritageClause */); node.token = token; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); @@ -12271,7 +11736,7 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(188 /* ExpressionWithTypeArguments */); + var node = createNode(192 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); @@ -12285,7 +11750,7 @@ var ts; return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(215 /* InterfaceDeclaration */, fullStart); + var node = createNode(219 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(107 /* InterfaceKeyword */); @@ -12296,10 +11761,10 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216 /* TypeAliasDeclaration */, fullStart); + var node = createNode(220 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - parseExpected(132 /* TypeKeyword */); + parseExpected(133 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); parseExpected(56 /* EqualsToken */); @@ -12312,13 +11777,13 @@ 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(247 /* EnumMember */, scanner.getStartPos()); + var node = createNode(251 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(217 /* EnumDeclaration */, fullStart); + var node = createNode(221 /* EnumDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(81 /* EnumKeyword */); @@ -12333,7 +11798,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(219 /* ModuleBlock */, scanner.getStartPos()); + var node = createNode(223 /* ModuleBlock */, scanner.getStartPos()); if (parseExpected(15 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); @@ -12344,31 +11809,42 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(218 /* ModuleDeclaration */, fullStart); + var node = createNode(222 /* ModuleDeclaration */, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. - var namespaceFlag = flags & 65536 /* Namespace */; + var namespaceFlag = flags & 4096 /* Namespace */; node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21 /* DotToken */) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 2 /* Export */ | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 1 /* Export */ | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(218 /* ModuleDeclaration */, fullStart); + var node = createNode(222 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.name = parseLiteralNode(/*internName*/ true); + if (token === 135 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation + node.name = parseIdentifier(); + node.flags |= 131072 /* GlobalAugmentation */; + } + else { + node.name = parseLiteralNode(/*internName*/ true); + } node.body = parseModuleBlock(); return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (parseOptional(126 /* NamespaceKeyword */)) { - flags |= 65536 /* Namespace */; + if (token === 135 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(126 /* NamespaceKeyword */)) { + flags |= 4096 /* Namespace */; } else { parseExpected(125 /* ModuleKeyword */); @@ -12379,7 +11855,7 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 127 /* RequireKeyword */ && + return token === 128 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -12388,22 +11864,17 @@ var ts; function nextTokenIsSlash() { return nextToken() === 39 /* SlashToken */; } - function nextTokenIsCommaOrFromKeyword() { - nextToken(); - return token === 24 /* CommaToken */ || - token === 133 /* FromKeyword */; - } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(89 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 24 /* CommaToken */ && token !== 133 /* FromKeyword */) { + if (token !== 24 /* CommaToken */ && token !== 134 /* FromKeyword */) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - var importEqualsDeclaration = createNode(221 /* ImportEqualsDeclaration */, fullStart); + var importEqualsDeclaration = createNode(225 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -12414,7 +11885,7 @@ var ts; } } // Import statement - var importDeclaration = createNode(222 /* ImportDeclaration */, fullStart); + var importDeclaration = createNode(226 /* ImportDeclaration */, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); // ImportDeclaration: @@ -12424,7 +11895,7 @@ var ts; token === 37 /* AsteriskToken */ || token === 15 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(133 /* FromKeyword */); + parseExpected(134 /* FromKeyword */); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); @@ -12437,7 +11908,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(223 /* ImportClause */, fullStart); + var importClause = createNode(227 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -12447,7 +11918,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(24 /* CommaToken */)) { - importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(225 /* NamedImports */); + importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(229 /* NamedImports */); } return finishNode(importClause); } @@ -12457,29 +11928,30 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(232 /* ExternalModuleReference */); - parseExpected(127 /* RequireKeyword */); + var node = createNode(236 /* ExternalModuleReference */); + parseExpected(128 /* RequireKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = parseModuleSpecifier(); parseExpected(18 /* CloseParenToken */); return finishNode(node); } function parseModuleSpecifier() { - // We allow arbitrary expressions here, even though the grammar only allows string - // literals. We check to ensure that it is only a string literal later in the grammar - // walker. - var result = parseExpression(); - // Ensure the string being required is in our 'identifier' table. This will ensure - // that features like 'find refs' will look inside this file when search for its name. - if (result.kind === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */) { + var result = parseLiteralNode(); internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); } - return result; } function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(224 /* NamespaceImport */); + var namespaceImport = createNode(228 /* NamespaceImport */); parseExpected(37 /* AsteriskToken */); parseExpected(116 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -12494,21 +11966,21 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 225 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); + node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 229 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(230 /* ExportSpecifier */); + return parseImportOrExportSpecifier(234 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(226 /* ImportSpecifier */); + return parseImportOrExportSpecifier(230 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); // ImportSpecifier: // BindingIdentifier // IdentifierName as BindingIdentifier - // ExportSpecififer: + // ExportSpecifier: // IdentifierName // IdentifierName as IdentifierName var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); @@ -12526,27 +11998,27 @@ var ts; else { node.name = identifierName; } - if (kind === 226 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 230 /* 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(228 /* ExportDeclaration */, fullStart); + var node = createNode(232 /* ExportDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(37 /* AsteriskToken */)) { - parseExpected(133 /* FromKeyword */); + parseExpected(134 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(229 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(233 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token === 133 /* FromKeyword */ || (token === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(133 /* FromKeyword */); + if (token === 134 /* FromKeyword */ || (token === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(134 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -12554,7 +12026,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(227 /* ExportAssignment */, fullStart); + var node = createNode(231 /* ExportAssignment */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(56 /* EqualsToken */)) { @@ -12577,11 +12049,13 @@ var ts; // reference comment. while (true) { var kind = triviaScanner.scan(); - if (kind === 5 /* WhitespaceTrivia */ || kind === 4 /* NewLineTrivia */ || kind === 3 /* MultiLineCommentTrivia */) { - continue; - } if (kind !== 2 /* SingleLineCommentTrivia */) { - break; + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } } var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; var comment = sourceText.substring(range.pos, range.end); @@ -12626,11 +12100,11 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 2 /* Export */ - || node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */ - || node.kind === 222 /* ImportDeclaration */ - || node.kind === 227 /* ExportAssignment */ - || node.kind === 228 /* ExportDeclaration */ + return node.flags & 1 /* Export */ + || node.kind === 225 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 236 /* ExternalModuleReference */ + || node.kind === 226 /* ImportDeclaration */ + || node.kind === 231 /* ExportAssignment */ + || node.kind === 232 /* ExportDeclaration */ ? node : undefined; }); @@ -12691,21 +12165,19 @@ var ts; } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined); - var jsDocTypeExpression = parseJSDocTypeExpression(start, length); + initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + scanner.setText(content, start, length); + token = scanner.scan(); + var jsDocTypeExpression = parseJSDocTypeExpression(); 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. + // Parses out a JSDoc type expression. /* @internal */ - function parseJSDocTypeExpression(start, length) { - scanner.setText(sourceText, start, length); - // Prime the first token for us to start processing. - token = nextToken(); - var result = createNode(249 /* JSDocTypeExpression */); + function parseJSDocTypeExpression() { + var result = createNode(253 /* JSDocTypeExpression */, scanner.getTokenPos()); parseExpected(15 /* OpenBraceToken */); result.type = parseJSDocTopLevelType(); parseExpected(16 /* CloseBraceToken */); @@ -12716,12 +12188,12 @@ var ts; function parseJSDocTopLevelType() { var type = parseJSDocType(); if (token === 47 /* BarToken */) { - var unionType = createNode(253 /* JSDocUnionType */, type.pos); + var unionType = createNode(257 /* JSDocUnionType */, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === 56 /* EqualsToken */) { - var optionalType = createNode(260 /* JSDocOptionalType */, type.pos); + var optionalType = createNode(264 /* JSDocOptionalType */, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -12732,20 +12204,20 @@ var ts; var type = parseBasicTypeExpression(); while (true) { if (token === 19 /* OpenBracketToken */) { - var arrayType = createNode(252 /* JSDocArrayType */, type.pos); + var arrayType = createNode(256 /* JSDocArrayType */, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20 /* CloseBracketToken */); type = finishNode(arrayType); } else if (token === 53 /* QuestionToken */) { - var nullableType = createNode(255 /* JSDocNullableType */, type.pos); + var nullableType = createNode(259 /* JSDocNullableType */, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } else if (token === 49 /* ExclamationToken */) { - var nonNullableType = createNode(256 /* JSDocNonNullableType */, type.pos); + var nonNullableType = createNode(260 /* JSDocNonNullableType */, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -12779,37 +12251,38 @@ var ts; case 97 /* ThisKeyword */: return parseJSDocThisType(); case 117 /* AnyKeyword */: - case 130 /* StringKeyword */: - case 128 /* NumberKeyword */: + case 131 /* StringKeyword */: + case 129 /* NumberKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: case 103 /* VoidKeyword */: return parseTokenNode(); } + // TODO (drosen): Parse string literal types in JSDoc as well. return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(264 /* JSDocThisType */); + var result = createNode(268 /* JSDocThisType */); nextToken(); parseExpected(54 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(263 /* JSDocConstructorType */); + var result = createNode(267 /* JSDocConstructorType */); nextToken(); parseExpected(54 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(262 /* JSDocVariadicType */); + var result = createNode(266 /* JSDocVariadicType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(261 /* JSDocFunctionType */); + var result = createNode(265 /* JSDocFunctionType */); nextToken(); parseExpected(17 /* OpenParenToken */); result.parameters = parseDelimitedList(22 /* JSDocFunctionParameters */, parseJSDocParameter); @@ -12822,26 +12295,28 @@ var ts; return finishNode(result); } function parseJSDocParameter() { - var parameter = createNode(138 /* Parameter */); + var parameter = createNode(140 /* Parameter */); parameter.type = parseJSDocType(); + if (parseOptional(56 /* EqualsToken */)) { + parameter.questionToken = createNode(56 /* EqualsToken */); + } return finishNode(parameter); } - function parseJSDocOptionalType(type) { - var result = createNode(260 /* JSDocOptionalType */, type.pos); - nextToken(); - result.type = type; - return finishNode(result); - } function parseJSDocTypeReference() { - var result = createNode(259 /* JSDocTypeReference */); + var result = createNode(263 /* JSDocTypeReference */); result.name = parseSimplePropertyName(); - while (parseOptional(21 /* DotToken */)) { - if (token === 25 /* LessThanToken */) { - result.typeArguments = parseTypeArguments(); - break; - } - else { - result.name = parseQualifiedName(result.name); + if (token === 25 /* LessThanToken */) { + result.typeArguments = parseTypeArguments(); + } + else { + while (parseOptional(21 /* DotToken */)) { + if (token === 25 /* LessThanToken */) { + result.typeArguments = parseTypeArguments(); + break; + } + else { + result.name = parseQualifiedName(result.name); + } } } return finishNode(result); @@ -12863,13 +12338,13 @@ var ts; } } function parseQualifiedName(left) { - var result = createNode(135 /* QualifiedName */, left.pos); + var result = createNode(137 /* QualifiedName */, left.pos); result.left = left; result.right = parseIdentifierName(); return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(257 /* JSDocRecordType */); + var result = createNode(261 /* JSDocRecordType */); nextToken(); result.members = parseDelimitedList(24 /* JSDocRecordMembers */, parseJSDocRecordMember); checkForTrailingComma(result.members); @@ -12877,7 +12352,7 @@ var ts; return finishNode(result); } function parseJSDocRecordMember() { - var result = createNode(258 /* JSDocRecordMember */); + var result = createNode(262 /* JSDocRecordMember */); result.name = parseSimplePropertyName(); if (token === 54 /* ColonToken */) { nextToken(); @@ -12886,13 +12361,13 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(256 /* JSDocNonNullableType */); + var result = createNode(260 /* JSDocNonNullableType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(254 /* JSDocTupleType */); + var result = createNode(258 /* JSDocTupleType */); nextToken(); result.types = parseDelimitedList(25 /* JSDocTupleTypes */, parseJSDocType); checkForTrailingComma(result.types); @@ -12906,7 +12381,7 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(253 /* JSDocUnionType */); + var result = createNode(257 /* JSDocUnionType */); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); parseExpected(18 /* CloseParenToken */); @@ -12924,7 +12399,7 @@ var ts; return types; } function parseJSDocAllType() { - var result = createNode(250 /* JSDocAllType */); + var result = createNode(254 /* JSDocAllType */); nextToken(); return finishNode(result); } @@ -12947,29 +12422,35 @@ var ts; token === 27 /* GreaterThanToken */ || token === 56 /* EqualsToken */ || token === 47 /* BarToken */) { - var result = createNode(251 /* JSDocUnknownType */, pos); + var result = createNode(255 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(255 /* JSDocNullableType */, pos); + var result = createNode(259 /* JSDocNullableType */, pos); result.type = parseJSDocType(); return finishNode(result); } } function parseIsolatedJSDocComment(content, start, length) { - initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined); - var jsDocComment = parseJSDocComment(/*parent:*/ undefined, start, length); + initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = { languageVariant: 0 /* Standard */, text: content }; + var jsDocComment = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var saveToken = token; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { - fixupParentReferences(comment); comment.parent = parent; } + token = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; } JSDocParser.parseJSDocComment = parseJSDocComment; @@ -12982,77 +12463,75 @@ var ts; 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 */) { + var result; + // Check for /** (JSDoc opening part) + if (content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */) { + // + 3 for leading /**, - 5 in total for /** */ + scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. var 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. + nextJSDocToken(); + while (token !== 1 /* EndOfFileToken */) { + switch (token) { + case 55 /* AtToken */: + if (canParseTag) { + parseTag(); + } + // This will take us to the end of the line, so it's OK to parse a tag on the next pass through the loop + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + // After a line break, we can parse a tag, and we haven't seen an asterisk on the next line yet + canParseTag = true; + seenAsterisk = false; + break; + case 37 /* AsteriskToken */: + if (seenAsterisk) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + canParseTag = false; + } + // Ignore the first asterisk on a line + seenAsterisk = true; + break; + case 69 /* Identifier */: + // 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; - } - seenAsterisk = true; - continue; + break; + case 1 /* EndOfFileToken */: + break; } - // 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; + nextJSDocToken(); } - } + result = createJSDocComment(); + }); } - return createJSDocComment(); + return result; function createJSDocComment() { if (!tags) { return undefined; } - var result = createNode(265 /* JSDocComment */, start); + var result = createNode(269 /* JSDocComment */, start); result.tags = tags; return finishNode(result, end); } function skipWhitespace() { - while (pos < end && ts.isWhiteSpace(content.charCodeAt(pos))) { - pos++; + while (token === 5 /* WhitespaceTrivia */ || token === 4 /* NewLineTrivia */) { + nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(content.charCodeAt(pos - 1) === 64 /* at */); - var atToken = createNode(55 /* AtToken */, pos - 1); - atToken.end = pos; - var tagName = scanIdentifier(); + ts.Debug.assert(token === 55 /* AtToken */); + var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifier(); if (!tagName) { return; } @@ -13076,10 +12555,10 @@ var ts; return undefined; } function handleUnknownTag(atToken, tagName) { - var result = createNode(266 /* JSDocTag */, atToken.pos); + var result = createNode(270 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - return finishNode(result, pos); + return finishNode(result); } function addTag(tag) { if (tag) { @@ -13092,12 +12571,10 @@ var ts; } } function tryParseTypeExpression() { - skipWhitespace(); - if (content.charCodeAt(pos) !== 123 /* openBrace */) { + if (token !== 15 /* OpenBraceToken */) { return undefined; } - var typeExpression = parseJSDocTypeExpression(pos, end - pos); - pos = typeExpression.end; + var typeExpression = parseJSDocTypeExpression(); return typeExpression; } function handleParamTag(atToken, tagName) { @@ -13105,17 +12582,22 @@ var ts; skipWhitespace(); var name; var isBracketed; - if (content.charCodeAt(pos) === 91 /* openBracket */) { - pos++; - skipWhitespace(); - name = scanIdentifier(); + // Looking for something like '[foo]' or 'foo' + if (parseOptionalToken(19 /* OpenBracketToken */)) { + name = parseJSDocIdentifier(); isBracketed = true; + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(56 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(20 /* CloseBracketToken */); } - else { - name = scanIdentifier(); + else if (token === 69 /* Identifier */) { + name = parseJSDocIdentifier(); } if (!name) { - parseErrorAtPosition(pos, 0, ts.Diagnostics.Identifier_expected); + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; } var preName, postName; if (typeExpression) { @@ -13127,84 +12609,82 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(267 /* JSDocParameterTag */, atToken.pos); + var result = createNode(271 /* 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); + return finishNode(result); } function handleReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 268 /* JSDocReturnTag */; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 272 /* JSDocReturnTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(268 /* JSDocReturnTag */, atToken.pos); + var result = createNode(272 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); - return finishNode(result, pos); + return finishNode(result); } function handleTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 269 /* JSDocTypeTag */; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 273 /* JSDocTypeTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(269 /* JSDocTypeTag */, atToken.pos); + var result = createNode(273 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); - return finishNode(result, pos); + return finishNode(result); } function handleTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 270 /* JSDocTemplateTag */; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 274 /* JSDocTemplateTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } + // Type parameter list looks like '@template T,U,V' var typeParameters = []; - typeParameters.pos = pos; + typeParameters.pos = scanner.getStartPos(); while (true) { - skipWhitespace(); - var startPos = pos; - var name_8 = scanIdentifier(); + var name_8 = parseJSDocIdentifier(); if (!name_8) { - parseErrorAtPosition(startPos, 0, ts.Diagnostics.Identifier_expected); + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(137 /* TypeParameter */, name_8.pos); + var typeParameter = createNode(139 /* TypeParameter */, name_8.pos); typeParameter.name = name_8; - finishNode(typeParameter, pos); + finishNode(typeParameter); typeParameters.push(typeParameter); - skipWhitespace(); - if (content.charCodeAt(pos) !== 44 /* comma */) { + if (token === 24 /* CommaToken */) { + nextJSDocToken(); + } + else { break; } - pos++; } - typeParameters.end = pos; - var result = createNode(270 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(274 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; - return finishNode(result, pos); + finishNode(result); + typeParameters.end = result.end; + return result; } - 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) { + function nextJSDocToken() { + return token = scanner.scanJSDocToken(); + } + function parseJSDocIdentifier() { + if (token !== 69 /* Identifier */) { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); return undefined; } - var result = createNode(69 /* Identifier */, startPos); - result.text = content.substring(startPos, pos); - return finishNode(result, pos); + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(69 /* Identifier */, pos); + result.text = content.substring(pos, end); + finishNode(result, end); + nextJSDocToken(); + return result; } } JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; @@ -13222,10 +12702,10 @@ var ts; if (sourceFile.statements.length === 0) { // If we don't have any statements in the current source file, then there's no real // way to incrementally parse. So just do a full parse instead. - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true); + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); } // Make sure we're not trying to incrementally update a source file more than once. Once - // we do an update the original source file is considered unusbale from that point onwards. + // we do an update the original source file is considered unusable from that point onwards. // // This is because we do incremental parsing in-place. i.e. we take nodes from the old // tree and give them new positions and parents. From that point on, trusting the old @@ -13278,7 +12758,7 @@ var ts; // inconsistent tree. Setting the parents on the new tree should be very fast. We // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); return result; } IncrementalParser.updateSourceFile = updateSourceFile; @@ -13337,7 +12817,7 @@ var ts; // We have an element that intersects the change range in some way. It may have its // start, or its end (or both) in the changed range. We want to adjust any part // that intersects such that the final tree is in a consistent state. i.e. all - // chlidren have spans within the span of their parent, and all siblings are ordered + // children have spans within the span of their parent, and all siblings are ordered // properly. // We may need to update both the 'pos' and the 'end' of the element. // If the 'pos' is before the start of the change, then we don't need to touch it. @@ -13357,7 +12837,7 @@ var ts; // -------------------ZZZ----------------- // // In this case, any element that started in the 'X' range will keep its position. - // However any element htat started after that will have their pos adjusted to be + // However any element that started after that will have their pos adjusted to be // at the end of the new range. i.e. any node that started in the 'Y' range will // be adjusted to have their start at the end of the 'Z' range. // @@ -13381,7 +12861,7 @@ var ts; // -------------------ZZZ----------------- // // In this case, any element that ended in the 'X' range will keep its position. - // However any element htat ended after that will have their pos adjusted to be + // However any element that ended after that will have their pos adjusted to be // at the end of the new range. i.e. any node that ended in the 'Y' range will // be adjusted to have their end at the end of the 'Z' range. if (element.end >= changeRangeOldEnd) { @@ -13401,12 +12881,12 @@ var ts; } function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { - var pos = node.pos; + var pos_2 = node.pos; forEachChild(node, function (child) { - ts.Debug.assert(child.pos >= pos); - pos = child.end; + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; }); - ts.Debug.assert(pos <= node.end); + ts.Debug.assert(pos_2 <= node.end); } } function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { @@ -13640,7 +13120,7 @@ var ts; if (position >= node.pos && position < node.end) { // Position was within this node. Keep searching deeper to find the node. forEachChild(node, visitNode, visitArray); - // don't procede any futher in the search. + // don't proceed any further in the search. return true; } // position wasn't in this node, have to keep searching. @@ -13682,6 +13162,1533 @@ var ts; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); })(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + ts.bindTime = 0; + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); + var ModuleInstanceState = ts.ModuleInstanceState; + var Reachability; + (function (Reachability) { + Reachability[Reachability["Uninitialized"] = 1] = "Uninitialized"; + Reachability[Reachability["Reachable"] = 2] = "Reachable"; + Reachability[Reachability["Unreachable"] = 4] = "Unreachable"; + Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable"; + })(Reachability || (Reachability = {})); + function or(state1, state2) { + return (state1 | state2) & 2 /* Reachable */ + ? 2 /* Reachable */ + : (state1 & state2) & 8 /* ReportedUnreachable */ + ? 8 /* ReportedUnreachable */ + : 4 /* Unreachable */; + } + function getModuleInstanceState(node) { + // A module is uninstantiated if it contains only + // 1. interface declarations, type alias declarations + if (node.kind === 219 /* InterfaceDeclaration */ || node.kind === 220 /* TypeAliasDeclaration */) { + return 0 /* NonInstantiated */; + } + else if (ts.isConstEnumDeclaration(node)) { + return 2 /* ConstEnumOnly */; + } + else if ((node.kind === 226 /* ImportDeclaration */ || node.kind === 225 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { + return 0 /* NonInstantiated */; + } + else if (node.kind === 223 /* ModuleBlock */) { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + switch (getModuleInstanceState(n)) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return false; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return false; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + } + }); + return state_1; + } + else if (node.kind === 222 /* ModuleDeclaration */) { + return getModuleInstanceState(node.body); + } + else { + return 1 /* Instantiated */; + } + } + ts.getModuleInstanceState = getModuleInstanceState; + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + 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 = {})); + var binder = createBinder(); + function bindSourceFile(file, options) { + var start = new Date().getTime(); + binder(file, options); + ts.bindTime += new Date().getTime() - start; + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var parent; + var container; + var blockScopeContainer; + var lastContainer; + var seenThisKeyword; + // state used by reachability checks + var hasExplicitReturn; + var currentReachabilityState; + var labelStack; + var labelIndexMap; + var implicitLabels; + // state used for emit helpers + var hasClassExtends; + var hasAsyncFunctions; + var hasDecorators; + var hasParameterDecorators; + // 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; + var symbolCount = 0; + var Symbol; + var classifiableNames; + function bindSourceFile(f, opts) { + file = f; + options = opts; + inStrictMode = !!file.externalModuleIndicator; + classifiableNames = {}; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + file = undefined; + options = undefined; + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + hasExplicitReturn = false; + labelStack = undefined; + labelIndexMap = undefined; + implicitLabels = undefined; + hasClassExtends = false; + hasAsyncFunctions = false; + hasDecorators = false; + hasParameterDecorators = false; + } + return bindSourceFile; + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { + symbol.exports = {}; + } + if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + symbol.members = {}; + } + if (symbolFlags & 107455 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 222 /* ModuleDeclaration */)) { + // other kinds of value declarations take precedence over modules + symbol.valueDeclaration = node; + } + } + } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. + function getDeclarationName(node) { + if (node.name) { + if (ts.isAmbientModule(node)) { + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + } + if (node.name.kind === 138 /* ComputedPropertyName */) { + var nameExpression = node.name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + return nameExpression.text; + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); + } + return node.name.text; + } + switch (node.kind) { + case 146 /* Constructor */: + return "__constructor"; + case 154 /* FunctionType */: + case 149 /* CallSignature */: + return "__call"; + case 155 /* ConstructorType */: + case 150 /* ConstructSignature */: + return "__new"; + case 151 /* IndexSignature */: + return "__index"; + case 232 /* ExportDeclaration */: + return "__export"; + case 231 /* ExportAssignment */: + return node.isExportEquals ? "export=" : "default"; + case 185 /* BinaryExpression */: + switch (ts.getSpecialPropertyAssignmentKind(node)) { + case 2 /* ModuleExports */: + // module.exports = ... + return "export="; + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + // exports.x = ... or this.y = ... + return node.left.name.text; + case 3 /* PrototypeProperty */: + // className.prototype.methodName = ... + return node.left.expression.name.text; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 217 /* FunctionDeclaration */: + case 218 /* ClassDeclaration */: + return node.flags & 512 /* Default */ ? "default" : undefined; + case 265 /* JSDocFunctionType */: + return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; + case 140 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 265 /* JSDocFunctionType */); + var functionType = node.parent; + var index = ts.indexOf(functionType.parameters, node); + return "p" + index; + } + } + function getDisplayName(node) { + return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = node.flags & 512 /* Default */; + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" : getDeclarationName(node); + var symbol; + if (name !== undefined) { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // 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; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.flags & 512 /* Default */) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0 /* None */, name); + } + } + else { + symbol = createSymbol(0 /* None */, "__missing"); + } + addDeclarationToSymbol(symbol, node, includes); + symbol.parent = parent; + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedNodeFlags(node) & 1 /* Export */; + if (symbolFlags & 8388608 /* Alias */) { + if (node.kind === 234 /* ExportSpecifier */ || (node.kind === 225 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue, + // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set + // on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192 /* ExportContext */)) { + 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, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + 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) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var 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; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we proactively initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + var containerFlags = getContainerFlags(node); + if (containerFlags & 1 /* IsContainer */) { + container = blockScopeContainer = node; + if (containerFlags & 4 /* HasLocals */) { + container.locals = {}; + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + var savedReachabilityState; + var savedLabelStack; + var savedLabels; + var savedImplicitLabels; + var savedHasExplicitReturn; + var kind = node.kind; + var flags = node.flags; + // reset all reachability check related flags on node (for incremental scenarios) + flags &= ~98304 /* ReachabilityCheckFlags */; + // reset all emit helper flags on node (for incremental scenarios) + flags &= ~3932160 /* EmitHelperFlags */; + if (kind === 219 /* InterfaceDeclaration */) { + seenThisKeyword = false; + } + var saveState = kind === 252 /* SourceFile */ || kind === 223 /* ModuleBlock */ || ts.isFunctionLikeKind(kind); + if (saveState) { + savedReachabilityState = currentReachabilityState; + savedLabelStack = labelStack; + savedLabels = labelIndexMap; + savedImplicitLabels = implicitLabels; + savedHasExplicitReturn = hasExplicitReturn; + currentReachabilityState = 2 /* Reachable */; + hasExplicitReturn = false; + labelStack = labelIndexMap = implicitLabels = undefined; + } + if (ts.isInJavaScriptFile(node) && node.jsDocComment) { + bind(node.jsDocComment); + } + bindReachableStatement(node); + if (currentReachabilityState === 2 /* Reachable */ && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { + flags |= 32768 /* HasImplicitReturn */; + if (hasExplicitReturn) { + flags |= 65536 /* HasExplicitReturn */; + } + } + if (kind === 219 /* InterfaceDeclaration */) { + flags = seenThisKeyword ? flags | 16384 /* ContainsThis */ : flags & ~16384 /* ContainsThis */; + } + if (kind === 252 /* SourceFile */) { + if (hasClassExtends) { + flags |= 262144 /* HasClassExtends */; + } + if (hasDecorators) { + flags |= 524288 /* HasDecorators */; + } + if (hasParameterDecorators) { + flags |= 1048576 /* HasParamDecorators */; + } + if (hasAsyncFunctions) { + flags |= 2097152 /* HasAsyncFunctions */; + } + } + node.flags = flags; + if (saveState) { + hasExplicitReturn = savedHasExplicitReturn; + currentReachabilityState = savedReachabilityState; + labelStack = savedLabelStack; + labelIndexMap = savedLabels; + implicitLabels = savedImplicitLabels; + } + container = saveContainer; + parent = saveParent; + blockScopeContainer = savedBlockScopeContainer; + } + /** + * Returns true if node and its subnodes were successfully traversed. + * Returning false means that node was not examined and caller needs to dive into the node himself. + */ + function bindReachableStatement(node) { + if (checkUnreachable(node)) { + ts.forEachChild(node, bind); + return; + } + switch (node.kind) { + case 202 /* WhileStatement */: + bindWhileStatement(node); + break; + case 201 /* DoStatement */: + bindDoStatement(node); + break; + case 203 /* ForStatement */: + bindForStatement(node); + break; + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 200 /* IfStatement */: + bindIfStatement(node); + break; + case 208 /* ReturnStatement */: + case 212 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 207 /* BreakStatement */: + case 206 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 213 /* TryStatement */: + bindTryStatement(node); + break; + case 210 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 224 /* CaseBlock */: + bindCaseBlock(node); + break; + case 211 /* LabeledStatement */: + bindLabeledStatement(node); + break; + default: + ts.forEachChild(node, bind); + break; + } + } + function bindWhileStatement(n) { + var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + // bind expressions (don't affect reachability) + bind(n.expression); + currentReachabilityState = preWhileState; + var postWhileLabel = pushImplicitLabel(); + bind(n.statement); + popImplicitLabel(postWhileLabel, postWhileState); + } + function bindDoStatement(n) { + var preDoState = currentReachabilityState; + var postDoLabel = pushImplicitLabel(); + bind(n.statement); + var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState; + popImplicitLabel(postDoLabel, postDoState); + // bind expressions (don't affect reachability) + bind(n.expression); + } + function bindForStatement(n) { + var preForState = currentReachabilityState; + var postForLabel = pushImplicitLabel(); + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.condition); + bind(n.incrementor); + bind(n.statement); + // for statement is considered infinite when it condition is either omitted or is true keyword + // - for(..;;..) + // - for(..;true;..) + var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */); + var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState; + popImplicitLabel(postForLabel, postForState); + } + function bindForInOrForOfStatement(n) { + var preStatementState = currentReachabilityState; + var postStatementLabel = pushImplicitLabel(); + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.expression); + bind(n.statement); + popImplicitLabel(postStatementLabel, preStatementState); + } + function bindIfStatement(n) { + // denotes reachability state when entering 'thenStatement' part of the if statement: + // i.e. if condition is false then thenStatement is unreachable + var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + // denotes reachability state when entering 'elseStatement': + // i.e. if condition is true then elseStatement is unreachable + var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + currentReachabilityState = ifTrueState; + // bind expression (don't affect reachability) + bind(n.expression); + bind(n.thenStatement); + if (n.elseStatement) { + var preElseState = currentReachabilityState; + currentReachabilityState = ifFalseState; + bind(n.elseStatement); + currentReachabilityState = or(currentReachabilityState, preElseState); + } + else { + currentReachabilityState = or(currentReachabilityState, ifFalseState); + } + } + function bindReturnOrThrow(n) { + // bind expression (don't affect reachability) + bind(n.expression); + if (n.kind === 208 /* ReturnStatement */) { + hasExplicitReturn = true; + } + currentReachabilityState = 4 /* Unreachable */; + } + function bindBreakOrContinueStatement(n) { + // call bind on label (don't affect reachability) + bind(n.label); + // for continue case touch label so it will be marked a used + var isValidJump = jumpToLabel(n.label, n.kind === 207 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); + if (isValidJump) { + currentReachabilityState = 4 /* Unreachable */; + } + } + function bindTryStatement(n) { + // catch\finally blocks has the same reachability as try block + var preTryState = currentReachabilityState; + bind(n.tryBlock); + var postTryState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.catchClause); + var postCatchState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.finallyBlock); + // post catch/finally state is reachable if + // - post try state is reachable - control flow can fall out of try block + // - post catch state is reachable - control flow can fall out of catch block + currentReachabilityState = or(postTryState, postCatchState); + } + function bindSwitchStatement(n) { + var preSwitchState = currentReachabilityState; + var postSwitchLabel = pushImplicitLabel(); + // bind expression (don't affect reachability) + bind(n.expression); + bind(n.caseBlock); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 246 /* DefaultClause */; }); + // post switch state is unreachable if switch is exhaustive (has a default case ) and does not have fallthrough from the last case + var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState; + popImplicitLabel(postSwitchLabel, postSwitchState); + } + function bindCaseBlock(n) { + var startState = currentReachabilityState; + for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + currentReachabilityState = startState; + bind(clause); + if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + } + function bindLabeledStatement(n) { + // call bind on label (don't affect reachability) + bind(n.label); + var ok = pushNamedLabel(n.label); + bind(n.statement); + if (ok) { + popNamedLabel(n.label, currentReachabilityState); + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 190 /* ClassExpression */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 169 /* ObjectLiteralExpression */: + case 157 /* TypeLiteral */: + case 261 /* JSDocRecordType */: + return 1 /* IsContainer */; + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 217 /* FunctionDeclaration */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 222 /* ModuleDeclaration */: + case 252 /* SourceFile */: + case 220 /* TypeAliasDeclaration */: + return 5 /* IsContainerWithLocals */; + case 248 /* CatchClause */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 224 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 196 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + // Just call this directly so that the return type of this function stays "void". + 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 222 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 252 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 190 /* ClassExpression */: + case 218 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 221 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 157 /* TypeLiteral */: + case 169 /* ObjectLiteralExpression */: + case 219 /* InterfaceDeclaration */: + case 261 /* JSDocRecordType */: + // 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 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 265 /* JSDocFunctionType */: + case 220 /* 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 & 32 /* Static */ + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 252 /* SourceFile */ ? node : node.body; + if (body.kind === 252 /* SourceFile */ || body.kind === 223 /* ModuleBlock */) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 232 /* ExportDeclaration */ || stat.kind === 231 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 8192 /* ExportContext */; + } + else { + node.flags &= ~8192 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (node.flags & 1 /* Export */) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); + } + else { + var state = getModuleInstanceState(node); + if (state === 0 /* NonInstantiated */) { + declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); + if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { + // if module was already merged with some function, class or non-const enum + // treat is a non-const-enum-only + node.symbol.constEnumOnlyModule = false; + } + else { + var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; + if (node.symbol.constEnumOnlyModule === undefined) { + // non-merged case - use the current state + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + } + else { + // merged case: module is const enum only if all its pieces are non-instantiated or const enum + node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + } + } + } + } + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; + } + 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 !== 69 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 249 /* PropertyAssignment */ || prop.kind === 250 /* ShorthandPropertyAssignment */ || prop.kind === 145 /* 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 bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 222 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 252 /* SourceFile */: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // fall through. + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = {}; + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 114 /* 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.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 69 /* 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 === 69 /* Identifier */ && + (node.text === "eval" || node.text === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 69 /* 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.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.isOctalLiteral) { + 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 === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function getDestructuringParameterName(node) { + return "__" + ts.indexOf(node.parent.parameters, node); + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var 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 252 /* SourceFile */: + case 223 /* ModuleBlock */: + updateStrictModeStatementList(node.statements); + return; + case 196 /* Block */: + if (ts.isFunctionLike(node.parent)) { + updateStrictModeStatementList(node.statements); + } + return; + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return; + } + } + function updateStrictModeStatementList(statements) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === "\"use strict\"" || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 69 /* Identifier */: + return checkStrictModeIdentifier(node); + case 185 /* BinaryExpression */: + if (ts.isInJavaScriptFile(node)) { + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + } + return checkStrictModeBinaryExpression(node); + case 248 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 179 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 184 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 183 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 209 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 163 /* ThisType */: + seenThisKeyword = true; + return; + case 152 /* TypePredicate */: + return checkTypePredicate(node); + case 139 /* TypeParameter */: + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); + case 140 /* Parameter */: + return bindParameter(node); + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: + return bindVariableDeclarationOrBindingElement(node); + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 262 /* JSDocRecordMember */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); + case 249 /* PropertyAssignment */: + case 250 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); + case 251 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + case 217 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 146 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 147 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + case 148 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 265 /* JSDocFunctionType */: + return bindFunctionOrConstructorType(node); + case 157 /* TypeLiteral */: + case 261 /* JSDocRecordType */: + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); + case 169 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + return bindFunctionExpression(node); + case 172 /* CallExpression */: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 190 /* ClassExpression */: + case 218 /* ClassDeclaration */: + return bindClassLikeDeclaration(node); + case 219 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); + case 220 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); + case 221 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 222 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Imports and exports + case 225 /* ImportEqualsDeclaration */: + case 228 /* NamespaceImport */: + case 230 /* ImportSpecifier */: + case 234 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); + case 227 /* ImportClause */: + return bindImportClause(node); + case 232 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 231 /* ExportAssignment */: + return bindExportAssignment(node); + case 252 /* SourceFile */: + return bindSourceFileIfExternalModule(); + } + } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 69 /* Identifier */) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 163 /* ThisType */) { + seenThisKeyword = true; + } + bind(type); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + var boundExpression = node.kind === 231 /* ExportAssignment */ ? node.expression : node.right; + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); + } + else if (boundExpression.kind === 69 /* Identifier */ && node.kind === 231 /* ExportAssignment */) { + // 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 setCommonJsModuleIndicator(node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 7340032 /* Export */, 0 /* None */); + } + function bindModuleExportsAssignment(node) { + // 'module.exports = expr' assignment + setCommonJsModuleIndicator(node); + bindExportAssignment(node); + } + function bindThisPropertyAssignment(node) { + // Declare a 'member' in case it turns out the container was an ES5 class + if (container.kind === 177 /* FunctionExpression */ || container.kind === 217 /* FunctionDeclaration */) { + container.symbol.members = container.symbol.members || {}; + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ & ~4 /* Property */); + } + } + function bindPrototypePropertyAssignment(node) { + // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var leftSideOfAssignment = node.left; + var classPrototype = leftSideOfAssignment.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + var funcSymbol = container.locals[constructorFunction.text]; + if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */)) { + return; + } + // Set up the members collection if it doesn't exist already + if (!funcSymbol.members) { + funcSymbol.members = {}; + } + // Declare the method/property + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 107455 /* PropertyExcludes */); + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { + hasClassExtends = true; + } + if (ts.nodeIsDecorated(node)) { + hasDecorators = true; + } + } + if (node.kind === 218 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.text : "__class"; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames[node.name.text] = node.name.text; + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 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 (!ts.isDeclarationFile(file) && + !ts.isInAmbientContext(node) && + ts.nodeIsDecorated(node)) { + hasDecorators = true; + hasParameterDecorators = true; + } + 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)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + } + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + } + function bindFunctionExpression(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.text : "__function"; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + if (ts.nodeIsDecorated(node)) { + hasDecorators = true; + } + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + // reachability checks + function pushNamedLabel(name) { + initializeReachabilityStateIfNecessary(); + if (ts.hasProperty(labelIndexMap, name.text)) { + return false; + } + labelIndexMap[name.text] = labelStack.push(1 /* Uninitialized */) - 1; + return true; + } + function pushImplicitLabel() { + initializeReachabilityStateIfNecessary(); + var index = labelStack.push(1 /* Uninitialized */) - 1; + implicitLabels.push(index); + return index; + } + function popNamedLabel(label, outerState) { + var index = labelIndexMap[label.text]; + ts.Debug.assert(index !== undefined); + ts.Debug.assert(labelStack.length == index + 1); + labelIndexMap[label.text] = undefined; + setCurrentStateAtLabel(labelStack.pop(), outerState, label); + } + function popImplicitLabel(implicitLabelIndex, outerState) { + if (labelStack.length !== implicitLabelIndex + 1) { + ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); + } + var i = implicitLabels.pop(); + if (implicitLabelIndex !== i) { + ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); + } + setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined); + } + function setCurrentStateAtLabel(innerMergedState, outerState, label) { + if (innerMergedState === 1 /* Uninitialized */) { + if (label && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); + } + currentReachabilityState = outerState; + } + else { + currentReachabilityState = or(innerMergedState, outerState); + } + } + function jumpToLabel(label, outerState) { + initializeReachabilityStateIfNecessary(); + var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); + if (index === undefined) { + // reference to unknown label or + // break/continue used outside of loops + return false; + } + var stateAtLabel = labelStack[index]; + labelStack[index] = stateAtLabel === 1 /* Uninitialized */ ? outerState : or(stateAtLabel, outerState); + return true; + } + function checkUnreachable(node) { + switch (currentReachabilityState) { + case 4 /* Unreachable */: + var reportError = + // report error on all statements except empty ones + (ts.isStatement(node) && node.kind !== 198 /* EmptyStatement */) || + // report error on class declarations + node.kind === 218 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 222 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (node.kind === 221 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentReachabilityState = 8 /* ReportedUnreachable */; + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 197 /* VariableStatement */ || + ts.getCombinedNodeFlags(node.declarationList) & 3072 /* BlockScoped */ || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + case 8 /* ReportedUnreachable */: + return true; + default: + return false; + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); + } + } + function initializeReachabilityStateIfNecessary() { + if (labelIndexMap) { + return; + } + currentReachabilityState = 2 /* Reachable */; + labelIndexMap = {}; + labelStack = []; + implicitLabels = []; + } + } +})(ts || (ts = {})); /// /* @internal */ var ts; @@ -13690,15 +14697,18 @@ var ts; var nextNodeId = 1; var nextMergeId = 1; function getNodeId(node) { - if (!node.id) - node.id = nextNodeId++; + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } return node.id; } ts.getNodeId = getNodeId; ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { - symbol.id = nextSymbolId++; + symbol.id = nextSymbolId; + nextSymbolId++; } return symbol.id; } @@ -13723,9 +14733,11 @@ var ts; var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0 /* ES3 */; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + var modulekind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; var emitResolver = createResolver(); var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined"); + undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -13734,11 +14746,13 @@ var ts; getTypeCount: function () { return typeCount; }, isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, getDiagnostics: getDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, // The language service will always care about the narrowed type of a symbol, because that is // the type the language says the symbol should have. getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, + getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: getPropertyOfType, @@ -13749,6 +14763,7 @@ var ts; getSymbolsInScope: getSymbolsInScope, getSymbolAtLocation: getSymbolAtLocation, getShorthandAssignmentValueSymbol: getShorthandAssignmentValueSymbol, + getExportSpecifierLocalTargetSymbol: getExportSpecifierLocalTargetSymbol, getTypeAtLocation: getTypeOfNode, typeToString: typeToString, getSymbolDisplayBuilder: getSymbolDisplayBuilder, @@ -13780,8 +14795,8 @@ var ts; var undefinedType = createIntrinsicType(32 /* Undefined */ | 2097152 /* ContainsUndefinedOrNull */, "undefined"); var nullType = createIntrinsicType(64 /* Null */ | 2097152 /* ContainsUndefinedOrNull */, "null"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var circularType = createIntrinsicType(1 /* Any */, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyUnionType = emptyObjectType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -13789,27 +14804,27 @@ var ts; // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = {}; var globalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; var globalObjectType; var globalFunctionType; var globalArrayType; + var globalReadonlyArrayType; var globalStringType; var globalNumberType; var globalBooleanType; var globalRegExpType; var globalTemplateStringsArrayType; var globalESSymbolType; - var jsxElementType; - /** Lazily loaded, use getJsxIntrinsicElementType() */ - var jsxIntrinsicElementsType; var globalIterableType; var globalIteratorType; var globalIterableIteratorType; var anyArrayType; + var anyReadonlyArrayType; var getGlobalClassDecoratorType; var getGlobalParameterDecoratorType; var getGlobalPropertyDecoratorType; @@ -13822,15 +14837,11 @@ var ts; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; var jsxElementClassType; + var deferredNodes; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; var stringLiteralTypes = {}; - var emitExtends = false; - var emitDecorate = false; - var emitParam = false; - var emitAwaiter = false; - var emitGenerator = false; var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -13856,14 +14867,23 @@ var ts; "symbol": { type: esSymbolType, flags: 16777216 /* ESSymbol */ + }, + "undefined": { + type: undefinedType, + flags: 2097152 /* ContainsUndefinedOrNull */ } }; + var jsxElementType; + /** Things we lazy load from the JSX namespace */ + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", ElementClass: "ElementClass", ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - Element: "Element" + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" }; var subtypeRelation = {}; var assignableRelation = {}; @@ -13877,6 +14897,10 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -13932,8 +14956,10 @@ var ts; return result; } function recordMergedSymbol(target, source) { - if (!source.mergeId) - source.mergeId = nextMergeId++; + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { @@ -13958,8 +14984,12 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (!target.valueDeclaration && source.valueDeclaration) + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 222 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 222 /* ModuleDeclaration */))) { + // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; + } ts.forEach(source.declarations, function (node) { target.declarations.push(node); }); @@ -13976,13 +15006,13 @@ var ts; recordMergedSymbol(target, source); } else { - var message = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ + var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message, symbolToString(source)); + error(node.name ? node.name : node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message, symbolToString(source)); + error(node.name ? node.name : node, message_2, symbolToString(source)); }); } } @@ -14011,6 +15041,53 @@ var ts; } } } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.valueDeclaration !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1536 /* Namespace */) { + // if module symbol has already been merged - it is safe to use it. + // otherwise clone it + mainModule = mainModule.flags & 33554432 /* Merged */ ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + for (var id in source) { + if (ts.hasProperty(source, id)) { + if (ts.hasProperty(target, id)) { + // Error on redeclarations + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } + } + } + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } function getSymbolLinks(symbol) { if (symbol.flags & 67108864 /* Transient */) return symbol; @@ -14021,11 +15098,8 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } - function getSourceFile(node) { - return ts.getAncestor(node, 248 /* SourceFile */); - } function isGlobalSourceFile(node) { - return node.kind === 248 /* SourceFile */ && !ts.isExternalModule(node); + return node.kind === 252 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -14044,6 +15118,22 @@ var ts; } // return undefined if we can't find a symbol. } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); @@ -14058,7 +15148,7 @@ var ts; if (declaration.pos <= usage.pos) { // declaration is before usage // still might be illegal if usage is in the initializer of the variable declaration - return declaration.kind !== 211 /* VariableDeclaration */ || + return declaration.kind !== 215 /* VariableDeclaration */ || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } // declaration is after usage @@ -14066,14 +15156,14 @@ var ts; return isUsedInFunctionOrNonStaticProperty(declaration, usage); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); - if (declaration.parent.parent.kind === 193 /* VariableStatement */ || - declaration.parent.parent.kind === 199 /* ForStatement */) { + if (declaration.parent.parent.kind === 197 /* VariableStatement */ || + declaration.parent.parent.kind === 203 /* ForStatement */) { // variable statement/for statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) return isSameScopeDescendentOf(usage, declaration, container); } - else if (declaration.parent.parent.kind === 201 /* ForOfStatement */ || - declaration.parent.parent.kind === 200 /* ForInStatement */) { + else if (declaration.parent.parent.kind === 205 /* ForOfStatement */ || + declaration.parent.parent.kind === 204 /* ForInStatement */) { // ForIn/ForOf case - use site should not be used in expression part var expression = declaration.parent.parent.expression; return isSameScopeDescendentOf(usage, expression, container); @@ -14090,8 +15180,8 @@ var ts; return true; } var initializerOfNonStaticProperty = current.parent && - current.parent.kind === 141 /* PropertyDeclaration */ && - (current.parent.flags & 64 /* Static */) === 0 && + current.parent.kind === 143 /* PropertyDeclaration */ && + (current.parent.flags & 32 /* Static */) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -14114,28 +15204,59 @@ 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)) { - // 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) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 793056 /* Type */ && lastLocation.kind !== 269 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + ? lastLocation === location.type || + lastLocation.kind === 140 /* Parameter */ || + lastLocation.kind === 139 /* TypeParameter */ + : false; + } + if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 140 /* Parameter */ || + (lastLocation === location.type && + result.valueDeclaration.kind === 140 /* Parameter */); + } + } + if (useResult) { break loop; } - result = undefined; + else { + result = undefined; + } } } switch (location.kind) { - case 248 /* SourceFile */: - if (!ts.isExternalModule(location)) + case 252 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) break; - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 248 /* SourceFile */ || - (location.kind === 218 /* ModuleDeclaration */ && location.name.kind === 9 /* 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. + if (location.kind === 252 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports["default"]) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { + break loop; + } + result = undefined; + } + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. // Two things to note about this: // 1. We have to check this without calling getSymbol. The problem with calling getSymbol // on an export specifier is that it might find the export specifier itself, and try to @@ -14146,34 +15267,28 @@ var ts; // which is not the desired behavior. if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 /* Alias */ && - ts.getDeclarationOfKind(moduleExports[name], 230 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExports[name], 234 /* ExportSpecifier */)) { break; } - 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 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (ts.isClassLike(location.parent) && !(location.flags & 64 /* Static */)) { + if (ts.isClassLike(location.parent) && !(location.flags & 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -14183,11 +15298,11 @@ var ts; } } break; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 219 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { - if (lastLocation && lastLocation.flags & 64 /* Static */) { + if (lastLocation && lastLocation.flags & 32 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. @@ -14196,7 +15311,7 @@ var ts; } break loop; } - if (location.kind === 186 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 190 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -14212,9 +15327,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 136 /* ComputedPropertyName */: + case 138 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 215 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 219 /* 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); @@ -14222,19 +15337,19 @@ var ts; } } break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 178 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 173 /* FunctionExpression */: + case 177 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -14247,7 +15362,7 @@ var ts; } } break; - case 139 /* Decorator */: + case 141 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -14256,7 +15371,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 === 138 /* Parameter */) { + if (location.parent && location.parent.kind === 140 /* Parameter */) { location = location.parent; } // @@ -14278,7 +15393,9 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } return undefined; } @@ -14297,7 +15414,7 @@ var ts; // declare module foo { // interface bar {} // } - // let foo/*1*/: foo/*2*/.bar; + // const foo/*1*/: foo/*2*/.bar; // The foo at /*1*/ and /*2*/ will share same symbol with two meaning // block - scope variable and namespace module. However, only when we // try to resolve name in /*1*/ which is used in variable position, @@ -14311,12 +15428,44 @@ var ts; } return result; } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!errorLocation || (errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + return false; + } + var container = ts.getThisContainer(errorLocation, /* includeArrowFunctions */ true); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + // Check to see if a static member exists. + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); + return true; + } + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !(location.flags & 32 /* Static */)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 211 /* VariableDeclaration */), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 215 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -14337,10 +15486,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 225 /* ImportEqualsDeclaration */) { return node; } - while (node && node.kind !== 222 /* ImportDeclaration */) { + while (node && node.kind !== 226 /* ImportDeclaration */) { node = node.parent; } return node; @@ -14350,7 +15499,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 232 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 236 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -14359,9 +15508,12 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); - if (!exportDefaultSymbol) { + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } return exportDefaultSymbol; } } @@ -14369,14 +15521,6 @@ var ts; var moduleSpecifier = node.parent.parent.moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } - function getMemberOfModuleVariable(moduleSymbol, name) { - if (moduleSymbol.flags & 3 /* Variable */) { - var typeAnnotation = moduleSymbol.valueDeclaration.type; - if (typeAnnotation) { - return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); - } - } - } // This function creates a synthetic symbol that combines the value side of one symbol with the // type/namespace side of another symbol. Consider this example: // @@ -14457,17 +15601,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node); - case 223 /* ImportClause */: + case 227 /* ImportClause */: return getTargetOfImportClause(node); - case 224 /* NamespaceImport */: + case 228 /* NamespaceImport */: return getTargetOfNamespaceImport(node); - case 226 /* ImportSpecifier */: + case 230 /* ImportSpecifier */: return getTargetOfImportSpecifier(node); - case 230 /* ExportSpecifier */: + case 234 /* ExportSpecifier */: return getTargetOfExportSpecifier(node); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return getTargetOfExportAssignment(node); } } @@ -14512,11 +15656,11 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 227 /* ExportAssignment */) { + if (node.kind === 231 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 230 /* ExportSpecifier */) { + else if (node.kind === 234 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -14529,7 +15673,7 @@ var ts; // This function is only for imports with entity names function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 221 /* ImportEqualsDeclaration */); + importDeclaration = ts.getAncestor(entityName, 225 /* ImportEqualsDeclaration */); ts.Debug.assert(importDeclaration !== undefined); } // There are three things we might try to look for. In the following examples, @@ -14542,13 +15686,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 135 /* QualifiedName */) { + if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 137 /* 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 === 221 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 225 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } } @@ -14568,9 +15712,9 @@ var ts; return undefined; } } - else if (name.kind === 135 /* QualifiedName */ || name.kind === 166 /* PropertyAccessExpression */) { - var left = name.kind === 135 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 135 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 137 /* QualifiedName */ || name.kind === 170 /* PropertyAccessExpression */) { + var left = name.kind === 137 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 137 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors); if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) { return undefined; @@ -14590,11 +15734,13 @@ var ts; return symbol.flags & meaning ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError) { if (moduleReferenceExpression.kind !== 9 /* StringLiteral */) { return; } var moduleReferenceLiteral = moduleReferenceExpression; - var searchPath = ts.getDirectoryPath(getSourceFile(location).fileName); // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); @@ -14605,24 +15751,33 @@ var ts; if (!isRelative) { var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); if (symbol) { - return symbol; + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(symbol); } } - var resolvedModule = ts.getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReferenceLiteral.text); var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - return sourceFile.symbol; + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); } - error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - return; + if (moduleNotFoundError) { + // report errors only if it was requested + error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; } - error(moduleReferenceLiteral, ts.Diagnostics.Cannot_find_module_0, moduleName); + if (moduleNotFoundError) { + // report errors only if it was requested + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + } + return undefined; } // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, // and an external module with no 'export =' declaration resolves to the module itself. function resolveExternalModuleSymbol(moduleSymbol) { - return moduleSymbol && resolveSymbol(moduleSymbol.exports["export="]) || moduleSymbol; + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports["export="])) || moduleSymbol; } // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may @@ -14635,8 +15790,8 @@ var ts; } return symbol; } - function getExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports["export="]; + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports["export="] !== undefined; } function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); @@ -14648,38 +15803,66 @@ var ts; var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } - function extendExportSymbols(target, source) { + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; + if (lookupTable && exportNode) { + lookupTable[id] = { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }; + } + } + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + if (!lookupTable[id].exportsWithDuplicate) { + lookupTable[id].exportsWithDuplicate = [exportNode]; + } + else { + lookupTable[id].exportsWithDuplicate.push(exportNode); + } } } } function getExportsForModule(moduleSymbol) { - var result; var visitedSymbols = []; - visit(moduleSymbol); - return result || moduleSymbol.exports; + return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. function visit(symbol) { - if (symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol)) { - visitedSymbols.push(symbol); - if (symbol !== moduleSymbol) { - if (!result) { - result = cloneSymbolTable(moduleSymbol.exports); - } - extendExportSymbols(result, symbol.exports); - } - // All export * declarations are collected in an __export symbol by the binder - var exportStars = symbol.exports["__export"]; - if (exportStars) { - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - visit(resolveExternalModuleName(node, node.moduleSpecifier)); - } - } + if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { + return; } + visitedSymbols.push(symbol); + var symbols = cloneSymbolTable(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports["__export"]; + if (exportStars) { + var nestedSymbols = {}; + var lookupTable = {}; + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); + } + for (var id in lookupTable) { + var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + continue; + } + for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { + var node = exportsWithDuplicate_1[_b]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable[id].specifierText, id)); + } + } + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; } } function getMergedSymbol(symbol) { @@ -14717,14 +15900,15 @@ var ts; var members = node.members; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var member = members_1[_i]; - if (member.kind === 144 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 146 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount++; + result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -14763,19 +15947,19 @@ var ts; } return result || emptyArray; } - function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { + function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; type.properties = getNamedMembers(members); type.callSignatures = callSignatures; type.constructSignatures = constructSignatures; - if (stringIndexType) - type.stringIndexType = stringIndexType; - if (numberIndexType) - type.numberIndexType = numberIndexType; + if (stringIndexInfo) + type.stringIndexInfo = stringIndexInfo; + if (numberIndexInfo) + type.numberIndexInfo = numberIndexInfo; return type; } - function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { - return setObjectTypeMembers(createObjectType(65536 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setObjectTypeMembers(createObjectType(65536 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -14787,17 +15971,17 @@ var ts; } } switch (location_1.kind) { - case 248 /* SourceFile */: - if (!ts.isExternalModule(location_1)) { + case 252 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -14824,7 +16008,7 @@ var ts; function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) - // and if symbolfrom symbolTable or alias resolution matches the symbol, + // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && canQualifySymbol(symbolFromSymbolTable, meaning); @@ -14838,7 +16022,7 @@ var ts; return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 /* Alias */ && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) { + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 234 /* ExportSpecifier */)) { if (!useOnlyExternalAliasing || // Is this external alias, then use it to name ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { @@ -14875,7 +16059,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 234 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -14910,7 +16094,7 @@ var ts; // export class c { // } // } - // let x: typeof m.c + // const x: typeof m.c // In the above example when we start with checking if typeof m.c symbol is accessible, // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible @@ -14948,8 +16132,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 218 /* ModuleDeclaration */ && declaration.name.kind === 9 /* StringLiteral */) || - (declaration.kind === 248 /* SourceFile */ && ts.isExternalModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 252 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -14963,7 +16146,7 @@ var ts; // because these kind of aliases can be used to name types in declaration file var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 2 /* Export */) && + !(anyImportSyntax.flags & 1 /* Export */) && isDeclarationVisible(anyImportSyntax.parent)) { getNodeLinks(declaration).isVisible = true; if (aliasesToMakeVisible) { @@ -14985,12 +16168,12 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 154 /* TypeQuery */) { + if (entityName.parent.kind === 156 /* TypeQuery */) { // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 135 /* QualifiedName */ || entityName.kind === 166 /* PropertyAccessExpression */ || - entityName.parent.kind === 221 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 137 /* QualifiedName */ || entityName.kind === 170 /* PropertyAccessExpression */ || + entityName.parent.kind === 225 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1536 /* Namespace */; @@ -15024,9 +16207,9 @@ var ts; ts.releaseStringWriter(writer); return result; } - function signatureToString(signature, enclosingDeclaration, flags) { + function signatureToString(signature, enclosingDeclaration, flags, kind) { var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); var result = writer.string(); ts.releaseStringWriter(writer); return result; @@ -15042,18 +16225,39 @@ var ts; } return result; } + function typePredicateToString(typePredicate, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + return result; + } + function visibilityToString(flags) { + if (flags === 8 /* Private */) { + return "private"; + } + if (flags === 16 /* Protected */) { + return "protected"; + } + return "public"; + } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { var node = type.symbol.declarations[0].parent; - while (node.kind === 160 /* ParenthesizedType */) { + while (node.kind === 162 /* ParenthesizedType */) { node = node.parent; } - if (node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 220 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } return undefined; } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 223 /* ModuleBlock */ && + ts.isExternalModuleAugmentation(node.parent.parent); + } function getSymbolDisplayBuilder() { function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { @@ -15062,10 +16266,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: return "(Anonymous class)"; - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return "(Anonymous function)"; } } @@ -15100,7 +16304,7 @@ var ts; parentSymbol = symbol; appendSymbolNameOnly(symbol, writer); } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses + // const the writer know we just wrote out a symbol. The declaration emitter writer uses // this to determine if an import it has previously seen (and not written out) needs // to be written to the file once the walk of the tree is complete. // @@ -15181,7 +16385,7 @@ var ts; writeAnonymousType(type, flags); } else if (type.flags & 256 /* StringLiteral */) { - writer.writeStringLiteral(type.text); + writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } else { // Should never get here @@ -15212,11 +16416,13 @@ var ts; } if (pos < end) { writePunctuation(writer, 25 /* LessThanToken */); - writeType(typeArguments[pos++], 0 /* None */); + writeType(typeArguments[pos], 0 /* None */); + pos++; while (pos < end) { writePunctuation(writer, 24 /* CommaToken */); writeSpace(writer); - writeType(typeArguments[pos++], 0 /* None */); + writeType(typeArguments[pos], 0 /* None */); + pos++; } writePunctuation(writer, 27 /* GreaterThanToken */); } @@ -15239,14 +16445,14 @@ var ts; 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]); + var parent_4 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_3); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_4); // 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, flags); + writeSymbolTypeReference(parent_4, typeArguments, start, i, flags); writePunctuation(writer, 21 /* DotToken */); } } @@ -15308,11 +16514,11 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 64 /* Static */; })); + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 32 /* Static */; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 248 /* SourceFile */ || declaration.parent.kind === 219 /* ModuleBlock */; + return declaration.parent.kind === 252 /* SourceFile */ || declaration.parent.kind === 223 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -15326,19 +16532,38 @@ var ts; writeSpace(writer); buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); } - function getIndexerParameterName(type, indexKind, fallbackName) { - var declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); - if (!declaration) { - // declaration might not be found if indexer was added from the contextual type. - // in this case use fallback name - return fallbackName; + function writeIndexSignature(info, keyword) { + if (info) { + if (info.isReadonly) { + writeKeyword(writer, 127 /* ReadonlyKeyword */); + writeSpace(writer); + } + writePunctuation(writer, 19 /* OpenBracketToken */); + writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); + writePunctuation(writer, 54 /* ColonToken */); + writeSpace(writer); + writeKeyword(writer, keyword); + writePunctuation(writer, 20 /* CloseBracketToken */); + writePunctuation(writer, 54 /* ColonToken */); + writeSpace(writer); + writeType(info.type, 0 /* None */); + writePunctuation(writer, 23 /* SemicolonToken */); + writer.writeLine(); + } + } + function writePropertyWithModifiers(prop) { + if (isReadonlySymbol(prop)) { + writeKeyword(writer, 127 /* ReadonlyKeyword */); + writeSpace(writer); + } + buildSymbolDisplay(prop, writer); + if (prop.flags & 536870912 /* Optional */) { + writePunctuation(writer, 53 /* QuestionToken */); } - ts.Debug.assert(declaration.parameters.length !== 0); - return ts.declarationNameToString(declaration.parameters[0].name); } function writeLiteralType(type, flags) { var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) { + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { writePunctuation(writer, 15 /* OpenBraceToken */); writePunctuation(writer, 16 /* CloseBraceToken */); @@ -15348,7 +16573,7 @@ var ts; if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* OpenParenToken */); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -15360,7 +16585,7 @@ var ts; } writeKeyword(writer, 92 /* NewKeyword */); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -15374,46 +16599,18 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - writeKeyword(writer, 92 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); - writePunctuation(writer, 23 /* SemicolonToken */); - writer.writeLine(); - } - if (resolved.stringIndexType) { - // [x: string]: - writePunctuation(writer, 19 /* OpenBracketToken */); - writer.writeParameter(getIndexerParameterName(resolved, 0 /* String */, /*fallbackName*/ "x")); - writePunctuation(writer, 54 /* ColonToken */); - writeSpace(writer); - writeKeyword(writer, 130 /* StringKeyword */); - writePunctuation(writer, 20 /* CloseBracketToken */); - writePunctuation(writer, 54 /* ColonToken */); - writeSpace(writer); - writeType(resolved.stringIndexType, 0 /* None */); - writePunctuation(writer, 23 /* SemicolonToken */); - writer.writeLine(); - } - if (resolved.numberIndexType) { - // [x: number]: - writePunctuation(writer, 19 /* OpenBracketToken */); - writer.writeParameter(getIndexerParameterName(resolved, 1 /* Number */, /*fallbackName*/ "x")); - writePunctuation(writer, 54 /* ColonToken */); - writeSpace(writer); - writeKeyword(writer, 128 /* NumberKeyword */); - writePunctuation(writer, 20 /* CloseBracketToken */); - writePunctuation(writer, 54 /* ColonToken */); - writeSpace(writer); - writeType(resolved.numberIndexType, 0 /* None */); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } + writeIndexSignature(resolved.stringIndexInfo, 131 /* StringKeyword */); + writeIndexSignature(resolved.numberIndexInfo, 129 /* NumberKeyword */); for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); @@ -15421,20 +16618,14 @@ var ts; var signatures = getSignaturesOfType(t, 0 /* Call */); for (var _f = 0, signatures_1 = signatures; _f < signatures_1.length; _f++) { var signature = signatures_1[_f]; - buildSymbolDisplay(p, writer); - if (p.flags & 536870912 /* Optional */) { - writePunctuation(writer, 53 /* QuestionToken */); - } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + writePropertyWithModifiers(p); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } } else { - buildSymbolDisplay(p, writer); - if (p.flags & 536870912 /* Optional */) { - writePunctuation(writer, 53 /* QuestionToken */); - } + writePropertyWithModifiers(p); writePunctuation(writer, 54 /* ColonToken */); writeSpace(writer); writeType(t, 0 /* None */); @@ -15447,10 +16638,10 @@ var ts; inObjectTypeLiteral = saveInObjectTypeLiteral; } } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaraiton, flags) { + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { var targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); } } function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { @@ -15513,6 +16704,18 @@ var ts; } writePunctuation(writer, 18 /* CloseParenToken */); } + function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 97 /* ThisKeyword */); + } + writeSpace(writer); + writeKeyword(writer, 124 /* IsKeyword */); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8 /* WriteArrowStyleSignature */) { writeSpace(writer); @@ -15522,20 +16725,19 @@ var ts; writePunctuation(writer, 54 /* ColonToken */); } writeSpace(writer); - var returnType; if (signature.typePredicate) { - writer.writeParameter(signature.typePredicate.parameterName); - writeSpace(writer); - writeKeyword(writer, 124 /* IsKeyword */); - writeSpace(writer); - returnType = signature.typePredicate.type; + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); } else { - returnType = getReturnTypeOfSignature(signature); + var returnType = getReturnTypeOfSignature(signature); + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1 /* Construct */) { + writeKeyword(writer, 92 /* NewKeyword */); + writeSpace(writer); + } if (signature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */)) { // Instantiated signature, write type arguments instead // This is achieved by passing in the mapper separately @@ -15551,6 +16753,7 @@ var ts; buildSymbolDisplay: buildSymbolDisplay, buildTypeDisplay: buildTypeDisplay, buildTypeParameterDisplay: buildTypeParameterDisplay, + buildTypePredicateDisplay: buildTypePredicateDisplay, buildParameterDisplay: buildParameterDisplay, buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, @@ -15560,131 +16763,6 @@ var ts; }); } function isDeclarationVisible(node) { - function getContainingExternalModule(node) { - for (; node; node = node.parent) { - if (node.kind === 218 /* ModuleDeclaration */) { - if (node.name.kind === 9 /* StringLiteral */) { - return node; - } - } - else if (node.kind === 248 /* SourceFile */) { - return ts.isExternalModule(node) ? node : undefined; - } - } - ts.Debug.fail("getContainingModule cant reach here"); - } - function isUsedInExportAssignment(node) { - // Get source File and see if it is external module and has export assigned symbol - var externalModule = getContainingExternalModule(node); - var exportAssignmentSymbol; - var resolvedExportSymbol; - if (externalModule) { - // This is export assigned symbol node - var externalModuleSymbol = getSymbolOfNode(externalModule); - exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - var symbolOfNode = getSymbolOfNode(node); - if (isSymbolUsedInExportAssignment(symbolOfNode)) { - return true; - } - // if symbolOfNode is alias declaration, resolve the symbol declaration and check - if (symbolOfNode.flags & 8388608 /* Alias */) { - return isSymbolUsedInExportAssignment(resolveAlias(symbolOfNode)); - } - } - // Check if the symbol is used in export assignment - function isSymbolUsedInExportAssignment(symbol) { - if (exportAssignmentSymbol === symbol) { - return true; - } - if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608 /* Alias */)) { - // if export assigned symbol is alias declaration, resolve the alias - resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol); - if (resolvedExportSymbol === symbol) { - return true; - } - // Container of resolvedExportSymbol is visible - return ts.forEach(resolvedExportSymbol.declarations, function (current) { - while (current) { - if (current === node) { - return true; - } - current = current.parent; - } - }); - } - } - } - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 163 /* BindingElement */: - return isDeclarationVisible(node.parent.parent); - case 211 /* 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 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 213 /* FunctionDeclaration */: - case 217 /* EnumDeclaration */: - case 221 /* 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) & 2 /* Export */) && - !(node.kind !== 221 /* ImportEqualsDeclaration */ && parent_4.kind !== 248 /* 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_4); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - if (node.flags & (16 /* Private */ | 32 /* 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 144 /* Constructor */: - case 148 /* ConstructSignature */: - case 147 /* CallSignature */: - case 149 /* IndexSignature */: - case 138 /* Parameter */: - case 219 /* ModuleBlock */: - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 155 /* TypeLiteral */: - case 151 /* TypeReference */: - case 156 /* ArrayType */: - case 157 /* TupleType */: - case 158 /* UnionType */: - case 159 /* IntersectionType */: - case 160 /* 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 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - return false; - // Type parameters are always visible - case 137 /* TypeParameter */: - // Source file is always visible - case 248 /* SourceFile */: - return true; - // Export assignements do not create name bindings outside the module - case 227 /* ExportAssignment */: - return false; - default: - ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); - } - } if (node) { var links = getNodeLinks(node); if (links.isVisible === undefined) { @@ -15692,13 +16770,89 @@ var ts; } return links.isVisible; } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 167 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 215 /* 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 222 /* ModuleDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 217 /* FunctionDeclaration */: + case 221 /* EnumDeclaration */: + case 225 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent_5 = 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 !== 225 /* ImportEqualsDeclaration */ && parent_5.kind !== 252 /* SourceFile */ && ts.isInAmbientContext(parent_5))) { + return isGlobalSourceFile(parent_5); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent_5); + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + if (node.flags & (8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so const it fall into next case statement + case 146 /* Constructor */: + case 150 /* ConstructSignature */: + case 149 /* CallSignature */: + case 151 /* IndexSignature */: + case 140 /* Parameter */: + case 223 /* ModuleBlock */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 157 /* TypeLiteral */: + case 153 /* TypeReference */: + case 158 /* ArrayType */: + case 159 /* TupleType */: + case 160 /* UnionType */: + case 161 /* IntersectionType */: + case 162 /* 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 227 /* ImportClause */: + case 228 /* NamespaceImport */: + case 230 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 139 /* TypeParameter */: + // Source file is always visible + case 252 /* SourceFile */: + return true; + // Export assignments do not create name bindings outside the module + case 231 /* ExportAssignment */: + return false; + default: + ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); + } + } } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 227 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 231 /* ExportAssignment */) { exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 230 /* ExportSpecifier */) { + else if (node.parent.kind === 234 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -15721,7 +16875,9 @@ var ts; var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, ts.Diagnostics.Cannot_find_name_0, firstIdentifier); - buildVisibleNodeList(importSymbol.declarations); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } } }); } @@ -15748,7 +16904,7 @@ var ts; return false; } resolutionTargets.push(target); - resolutionResults.push(true); + resolutionResults.push(/*items*/ true); resolutionPropertyNames.push(propertyName); return true; } @@ -15788,16 +16944,27 @@ var ts; } function getDeclarationContainer(node) { node = ts.getRootDeclaration(node); - // Parent chain: - // VaribleDeclaration -> VariableDeclarationList -> VariableStatement -> 'Declaration Container' - return node.kind === 211 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; + while (node) { + switch (node.kind) { + case 215 /* VariableDeclaration */: + case 216 /* VariableDeclarationList */: + case 230 /* ImportSpecifier */: + case 229 /* NamedImports */: + case 228 /* NamespaceImport */: + case 227 /* ImportClause */: + node = node.parent; + break; + default: + return node.parent; + } + } } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 // Every class automatically contains a static property member named 'prototype', // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. // It is an error to explicitly declare a static property member with the name 'prototype'. - var classType = getDeclaredTypeOfSymbol(prototype.parent); + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; } // Return the type of the given property in the given type, or undefined if no such property exists @@ -15814,6 +16981,23 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); } + function getTextOfPropertyName(name) { + switch (name.kind) { + case 69 /* Identifier */: + return name.text; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + case 138 /* ComputedPropertyName */: + if (ts.isStringOrNumericLiteral(name.expression.kind)) { + return name.expression.text; + } + } + return undefined; + } + function isComputedNonLiteralName(name) { + return name.kind === 138 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression.kind); + } // Return the inferred type for a binding element function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -15832,13 +17016,18 @@ var ts; return parentType; } var type; - if (pattern.kind === 161 /* ObjectBindingPattern */) { + if (pattern.kind === 165 /* ObjectBindingPattern */) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name_10 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_10)) { + // computed properties with non-literal names are treated as 'any' + return anyType; + } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - type = getTypeOfPropertyOfType(parentType, name_10.text) || - isNumericLiteralName(name_10.text) && getIndexTypeOfType(parentType, 1 /* Number */) || + var text = getTextOfPropertyName(name_10); + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10)); @@ -15873,13 +17062,53 @@ var ts; } return type; } + function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return getTypeFromTypeNode(jsDocType); + } + } + function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + // First, see if this node has an @type annotation on it directly. + var typeTag = ts.getJSDocTypeTag(declaration); + if (typeTag && typeTag.typeExpression) { + return typeTag.typeExpression.type; + } + if (declaration.kind === 215 /* VariableDeclaration */ && + declaration.parent.kind === 216 /* VariableDeclarationList */ && + declaration.parent.parent.kind === 197 /* VariableStatement */) { + // @type annotation might have been on the variable statement, try that instead. + var annotation = ts.getJSDocTypeTag(declaration.parent.parent); + if (annotation && annotation.typeExpression) { + return annotation.typeExpression.type; + } + } + else if (declaration.kind === 140 /* Parameter */) { + // If it's a parameter, see if the parent has a jsdoc comment with an @param + // annotation. + var paramTag = ts.getCorrespondingJSDocParameterTag(declaration); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type; + } + } + return undefined; + } // 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 === 200 /* ForInStatement */) { - return anyType; + if (declaration.flags & 134217728 /* JavaScriptFile */) { + // If this is a variable in a JavaScript file, then use the JSDoc type (if it has + // one as its type), otherwise fallback to the below standard TS codepaths to + // try to figure it out. + var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (type && type !== unknownType) { + return type; + } } - if (declaration.parent.parent.kind === 201 /* ForOfStatement */) { + // A variable declared in a for..in statement is always of type string + if (declaration.parent.parent.kind === 204 /* ForInStatement */) { + return stringType; + } + if (declaration.parent.parent.kind === 205 /* 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, @@ -15893,11 +17122,11 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 138 /* Parameter */) { + if (declaration.kind === 140 /* 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 === 146 /* SetAccessor */ && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 145 /* GetAccessor */); + if (func.kind === 148 /* SetAccessor */ && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 147 /* GetAccessor */); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } @@ -15913,7 +17142,7 @@ var ts; return checkExpressionCached(declaration.initializer); } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 246 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 250 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // If the declaration specifies a binding pattern, use the type implied by the binding pattern @@ -15938,10 +17167,17 @@ var ts; // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType) { var members = {}; + var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { - var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); var name = e.propertyName || e.name; - var symbol = createSymbol(flags, name.text); + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + hasComputedProperties = true; + return; + } + var text = getTextOfPropertyName(name); + var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); + var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; @@ -15950,6 +17186,9 @@ var ts; if (includePatternInType) { result.pattern = pattern; } + if (hasComputedProperties) { + result.flags |= 67108864 /* ObjectLiteralPatternWithComputedProperties */; + } return result; } // Return the type implied by an array binding pattern @@ -15959,7 +17198,7 @@ var ts; return languageVersion >= 2 /* ES6 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - var elementTypes = ts.map(elements, function (e) { return e.kind === 187 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return e.kind === 191 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { var result = createNewTupleType(elementTypes); result.pattern = pattern; @@ -15975,7 +17214,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, includePatternInType) { - return pattern.kind === 161 /* ObjectBindingPattern */ + return pattern.kind === 165 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType) : getTypeFromArrayBindingPattern(pattern, includePatternInType); } @@ -15997,14 +17236,17 @@ 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 !== 245 /* PropertyAssignment */ ? getWidenedType(type) : type; + if (declaration.kind === 249 /* PropertyAssignment */) { + return type; + } + return getWidenedType(type); } // Rest parameters default to type any[], other parameters default to type any type = declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && compilerOptions.noImplicitAny) { var root = ts.getRootDeclaration(declaration); - if (!isPrivateWithinAmbient(root) && !(root.kind === 138 /* Parameter */ && isPrivateWithinAmbient(root.parent))) { + if (!isPrivateWithinAmbient(root) && !(root.kind === 140 /* Parameter */ && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } } @@ -16019,13 +17261,25 @@ var ts; } // Handle catch clause variables var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 244 /* CatchClause */) { + if (declaration.parent.kind === 248 /* CatchClause */) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 227 /* ExportAssignment */) { + if (declaration.kind === 231 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } + // Handle module.exports = expr + if (declaration.kind === 185 /* BinaryExpression */) { + return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + if (declaration.kind === 170 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 185 /* BinaryExpression */) { + // Handle exports.p = expr or this.p = expr or className.prototype.method = expr + return links.type = checkExpressionCached(declaration.parent.right); + } + } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; @@ -16051,7 +17305,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 145 /* GetAccessor */) { + if (accessor.kind === 147 /* GetAccessor */) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -16067,9 +17321,9 @@ var ts; if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var getter = ts.getDeclarationOfKind(symbol, 145 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 146 /* SetAccessor */); - var type; + var getter = ts.getDeclarationOfKind(symbol, 147 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 148 /* SetAccessor */); + var type = void 0; // First try to see if the user specified a return type on the get-accessor. var getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { @@ -16097,7 +17351,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 145 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 147 /* 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)); } } @@ -16197,9 +17451,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */ || - node.kind === 213 /* FunctionDeclaration */ || node.kind === 173 /* FunctionExpression */ || - node.kind === 143 /* MethodDeclaration */ || node.kind === 174 /* ArrowFunction */) { + if (node.kind === 218 /* ClassDeclaration */ || node.kind === 190 /* ClassExpression */ || + node.kind === 217 /* FunctionDeclaration */ || node.kind === 177 /* FunctionExpression */ || + node.kind === 145 /* MethodDeclaration */ || node.kind === 178 /* ArrowFunction */) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -16209,7 +17463,7 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 215 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 219 /* InterfaceDeclaration */); return appendOuterTypeParameters(undefined, declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -16218,8 +17472,8 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 214 /* ClassDeclaration */ || - node.kind === 186 /* ClassExpression */ || node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 219 /* InterfaceDeclaration */ || node.kind === 218 /* ClassDeclaration */ || + node.kind === 190 /* ClassExpression */ || node.kind === 220 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -16246,8 +17500,8 @@ var ts; 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); }); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); + signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; } @@ -16283,9 +17537,6 @@ var ts; } return type.resolvedBaseConstructorType; } - function hasClassBaseType(type) { - return !!ts.forEach(getBaseTypes(type), function (t) { return !!(t.symbol.flags & 32 /* Class */); }); - } function getBaseTypes(type) { var isClass = type.symbol.flags & 32 /* Class */; var isInterface = type.symbol.flags & 64 /* Interface */; @@ -16304,23 +17555,25 @@ var ts; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - var baseContructorType = getBaseConstructorTypeOfClass(type); - if (!(baseContructorType.flags & 80896 /* ObjectType */)) { + var baseConstructorType = getBaseConstructorTypeOfClass(type); + if (!(baseConstructorType.flags & 80896 /* 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 + var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.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); + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return; @@ -16345,11 +17598,22 @@ var ts; type.resolvedBaseTypes.push(baseType); } } + function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 219 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -16381,8 +17645,8 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 /* InterfaceDeclaration */) { - if (declaration.flags & 262144 /* ContainsThis */) { + if (declaration.kind === 219 /* InterfaceDeclaration */) { + if (declaration.flags & 16384 /* ContainsThis */) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); @@ -16424,7 +17688,7 @@ var ts; type.typeArguments = type.typeParameters; type.thisType = createType(512 /* TypeParameter */ | 33554432 /* ThisType */); type.thisType.symbol = symbol; - type.thisType.constraint = getTypeWithThisArgument(type); + type.thisType.constraint = type; } } return links.declaredType; @@ -16437,7 +17701,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 216 /* TypeAliasDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 220 /* TypeAliasDeclaration */); var type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -16470,7 +17734,7 @@ var ts; if (!links.declaredType) { var type = createType(512 /* TypeParameter */); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).constraint) { + if (!ts.getDeclarationOfKind(symbol, 139 /* TypeParameter */).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -16521,16 +17785,16 @@ var ts; function isIndependentType(node) { switch (node.kind) { case 117 /* AnyKeyword */: - case 130 /* StringKeyword */: - case 128 /* NumberKeyword */: + case 131 /* StringKeyword */: + case 129 /* NumberKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 9 /* StringLiteral */: + case 164 /* StringLiteralType */: return true; - case 156 /* ArrayType */: + case 158 /* ArrayType */: return isIndependentType(node.elementType); - case 151 /* TypeReference */: + case 153 /* TypeReference */: return isIndependentTypeReference(node); } return false; @@ -16543,7 +17807,7 @@ var ts; // A function-like declaration is considered independent (free of this references) if it has a return type // annotation that is considered independent and if each parameter is considered independent. function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 144 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { + if (node.kind !== 146 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { return false; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -16557,19 +17821,19 @@ var ts; // Returns true if the class or interface member given by the symbol is free of "this" references. The // function may return false for symbols that are actually free of "this" references because it is not // feasible to perform a complete analysis in all cases. In particular, property members with types - // inferred from their initializers and function members with inferred return types are convervatively + // inferred from their initializers and function members with inferred return types are conservatively // assumed not to be free of "this" references. function isIndependentMember(symbol) { if (symbol.declarations && symbol.declarations.length === 1) { var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return isIndependentVariableLikeDeclaration(declaration); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: return isIndependentFunctionLikeDeclaration(declaration); } } @@ -16602,22 +17866,14 @@ var ts; } } } - function addInheritedSignatures(signatures, baseSignatures) { - if (baseSignatures) { - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var signature = baseSignatures_1[_i]; - signatures.push(signature); - } - } - } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; type.declaredProperties = getNamedMembers(symbol.members); type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]); type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]); - type.declaredStringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); - type.declaredNumberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); } return type; } @@ -16632,15 +17888,15 @@ var ts; var members = source.symbol.members; var callSignatures = source.declaredCallSignatures; var constructSignatures = source.declaredConstructSignatures; - var stringIndexType = source.declaredStringIndexType; - var numberIndexType = source.declaredNumberIndexType; + var stringIndexInfo = source.declaredStringIndexInfo; + var numberIndexInfo = source.declaredNumberIndexInfo; if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); - stringIndexType = instantiateType(source.declaredStringIndexType, mapper); - numberIndexType = instantiateType(source.declaredNumberIndexType, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } var baseTypes = getBaseTypes(source); if (baseTypes.length) { @@ -16654,11 +17910,11 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); - stringIndexType = stringIndexType || getIndexTypeOfType(instantiatedBaseType, 0 /* String */); - numberIndexType = numberIndexType || getIndexTypeOfType(instantiatedBaseType, 1 /* Number */); + stringIndexInfo = stringIndexInfo || getIndexInfoOfType(instantiatedBaseType, 0 /* String */); + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type) { resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); @@ -16686,17 +17942,17 @@ var ts; return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - if (!hasClassBaseType(classType)) { - return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; + } var baseTypeNode = getBaseTypeNodeOfClass(classType); var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { - var baseSig = baseSignatures_2[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -16722,12 +17978,12 @@ var ts; var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); var members = createTupleTypeMemberSymbols(type.elementTypes); addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); } function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreReturnTypes, compareTypesIdentical)) { return s; } } @@ -16788,78 +18044,76 @@ var ts; } return result || emptyArray; } - function getUnionIndexType(types, kind) { + function getUnionIndexInfo(types, kind) { var indexTypes = []; + var isAnyReadonly = false; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; - var indexType = getIndexTypeOfType(type, kind); - if (!indexType) { + var indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { return undefined; } - indexTypes.push(indexType); + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return getUnionType(indexTypes); + return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); } function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union // type use getPropertiesOfType (only the language service uses this). var callSignatures = getUnionSignatures(type.types, 0 /* Call */); var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */); - var stringIndexType = getUnionIndexType(type.types, 0 /* String */); - var numberIndexType = getUnionIndexType(type.types, 1 /* Number */); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); + var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1, type2) { return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } function resolveIntersectionTypeMembers(type) { // The members and properties collections are empty for intersection types. To get all properties of an // intersection type use getPropertiesOfType (only the language service uses this). var callSignatures = emptyArray; var constructSignatures = emptyArray; - var stringIndexType = undefined; - var numberIndexType = undefined; + var stringIndexInfo = undefined; + var numberIndexInfo = undefined; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(t, 1 /* Construct */)); - stringIndexType = intersectTypes(stringIndexType, getIndexTypeOfType(t, 0 /* String */)); - numberIndexType = intersectTypes(numberIndexType, getIndexTypeOfType(t, 1 /* Number */)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; - var members; - var callSignatures; - var constructSignatures; - var stringIndexType; - var numberIndexType; if (type.target) { - members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); - callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); - constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); - stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0 /* String */), type.mapper); - numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1 /* Number */), type.mapper); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); + var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048 /* TypeLiteral */) { - members = symbol.members; - callSignatures = getSignaturesOfSymbol(members["__call"]); - constructSignatures = getSignaturesOfSymbol(members["__new"]); - stringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); - numberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members["__call"]); + var constructSignatures = getSignaturesOfSymbol(members["__new"]); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { // Combinations of function, class, enum and module - members = emptySymbols; - callSignatures = emptyArray; - constructSignatures = emptyArray; + var members = emptySymbols; + var constructSignatures = emptyArray; if (symbol.flags & 1952 /* HasExports */) { members = getExportsOfSymbol(symbol); } - if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { - callSignatures = getSignaturesOfSymbol(symbol); - } if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); @@ -16872,10 +18126,16 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } - stringIndexType = undefined; - numberIndexType = (symbol.flags & 384 /* Enum */) ? stringType : undefined; + var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; + setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -16900,15 +18160,15 @@ var ts; } return type; } - // Return properties of an object type or an empty array for other types + /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { if (type.flags & 80896 /* ObjectType */) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } - // If the given type is an object type and that type has a property by the given name, - // return the symbol for that property.Otherwise return undefined. + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); @@ -16939,6 +18199,20 @@ var ts; type = getApparentType(type); return type.flags & 49152 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + /** + * The apparent type of a type parameter is the base constraint instantiated with the type parameter + * as the type argument for the 'this' type. + */ + function getApparentTypeOfTypeParameter(type) { + if (!type.resolvedApparentType) { + var constraintType = getConstraintOfTypeParameter(type); + while (constraintType && constraintType.flags & 512 /* TypeParameter */) { + constraintType = getConstraintOfTypeParameter(constraintType); + } + type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); + } + return type.resolvedApparentType; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -16946,12 +18220,7 @@ var ts; */ function getApparentType(type) { if (type.flags & 512 /* TypeParameter */) { - do { - type = getConstraintOfTypeParameter(type); - } while (type && type.flags & 512 /* TypeParameter */); - if (!type) { - type = emptyObjectType; - } + type = getApparentTypeOfTypeParameter(type); } if (type.flags & 258 /* StringLike */) { type = globalStringType; @@ -16970,12 +18239,15 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = (containingType.flags & 32768 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 /* Private */ | 32 /* Protected */))) { + if (prop && !(getDeclarationFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))) { + commonFlags &= prop.flags; if (!props) { props = [prop]; } @@ -17004,7 +18276,10 @@ var ts; } propTypes.push(getTypeOfSymbol(prop)); } - var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */, name); + var result = createSymbol(4 /* Property */ | + 67108864 /* Transient */ | + 268435456 /* SyntheticProperty */ | + commonFlags, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & 16384 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -17061,33 +18336,48 @@ var ts; function getSignaturesOfType(type, kind) { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function typeHasConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & (80896 /* ObjectType */ | 16384 /* Union */)) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.constructSignatures.length > 0; - } - return false; - } - function typeHasCallOrConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & 130048 /* StructuredType */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; - } - return false; - } - function getIndexTypeOfStructuredType(type, kind) { + function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 130048 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); - return kind === 0 /* String */ ? resolved.stringIndexType : resolved.numberIndexType; + return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexTypeOfType(type, kind) { return getIndexTypeOfStructuredType(getApparentType(type), kind); } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectLiteralType(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.name)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + return getUnionType(propTypes); + } + return undefined; + } + function getTypeParametersFromJSDocTemplate(declaration) { + if (declaration.flags & 134217728 /* JavaScriptFile */) { + var templateTag = ts.getJSDocTemplateTag(declaration); + if (templateTag) { + return getTypeParametersFromDeclaration(templateTag.typeParameters); + } + } + return undefined; + } // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(typeParameterDeclarations) { @@ -17110,33 +18400,77 @@ var ts; return result; } function isOptionalParameter(node) { + if (node.flags & 134217728 /* JavaScriptFile */) { + if (node.type && node.type.kind === 264 /* JSDocOptionalType */) { + return true; + } + var paramTag = ts.getCorrespondingJSDocParameterTag(node); + if (paramTag) { + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 264 /* JSDocOptionalType */; + } + } + } if (ts.hasQuestionToken(node)) { return true; } if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = signatureDeclaration.parameters.indexOf(node); + var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } return false; } + function createTypePredicateFromTypePredicateNode(node) { + if (node.parameterName.kind === 69 /* Identifier */) { + var parameterName = node.parameterName; + return { + kind: 1 /* Identifier */, + parameterName: parameterName ? parameterName.text : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0 /* This */, + type: getTypeFromTypeNode(node.type) + }; + } + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { - var classType = declaration.kind === 144 /* Constructor */ ? + var classType = declaration.kind === 146 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; + declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : + getTypeParametersFromJSDocTemplate(declaration); var parameters = []; var hasStringLiterals = false; var minArgumentCount = -1; - for (var i = 0, n = declaration.parameters.length; i < n; i++) { + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var returnType = undefined; + var typePredicate = undefined; + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (var i = isJSConstructSignature ? 1 : 0, n = declaration.parameters.length; i < n; i++) { var param = declaration.parameters[i]; - parameters.push(param.symbol); - if (param.type && param.type.kind === 9 /* StringLiteral */) { + var paramSymbol = param.symbol; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.name, 107455 /* Value */, undefined, undefined); + paramSymbol = resolvedSymbol; + } + parameters.push(paramSymbol); + if (param.type && param.type.kind === 164 /* StringLiteralType */) { hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken) { @@ -17152,27 +18486,30 @@ var ts; if (minArgumentCount < 0) { minArgumentCount = declaration.parameters.length; } - var returnType; - var typePredicate; - if (classType) { + if (isJSConstructSignature) { + minArgumentCount--; + returnType = getTypeFromTypeNode(declaration.parameters[0].type); + } + else if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); - if (declaration.type.kind === 150 /* 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) - }; + if (declaration.type.kind === 152 /* TypePredicate */) { + typePredicate = createTypePredicateFromTypePredicateNode(declaration.type); } } else { + if (declaration.flags & 134217728 /* JavaScriptFile */) { + var type = getReturnTypeFromJSDocComment(declaration); + if (type && type !== unknownType) { + returnType = type; + } + } // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 145 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 146 /* SetAccessor */); + if (declaration.kind === 147 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 148 /* SetAccessor */); returnType = getAnnotatedAccessorType(setter); } if (!returnType && ts.nodeIsMissing(declaration.body)) { @@ -17190,19 +18527,20 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 265 /* JSDocFunctionType */: // Don't include signature if node is the implementation of an overloaded function. A node is considered // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). @@ -17217,12 +18555,22 @@ var ts; } return result; } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return unknownType; } - var type; + var type = void 0; if (signature.target) { type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } @@ -17258,7 +18606,7 @@ var ts; return anyType; } function getSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature) { if (!signature.typeParameters) @@ -17268,7 +18616,7 @@ var ts; signature.erasedSignatureCache = instantiateSignature(getErasedSignature(signature.target), signature.mapper); } else { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); } } return signature.erasedSignatureCache; @@ -17279,7 +18627,7 @@ 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 === 144 /* Constructor */ || signature.declaration.kind === 148 /* ConstructSignature */; + var isConstructor = signature.declaration.kind === 146 /* Constructor */ || signature.declaration.kind === 150 /* ConstructSignature */; var type = createObjectType(65536 /* Anonymous */ | 262144 /* FromSignature */); type.members = emptySymbols; type.properties = emptyArray; @@ -17293,7 +18641,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 128 /* NumberKeyword */ : 130 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 129 /* NumberKeyword */ : 131 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -17309,26 +18657,51 @@ var ts; } return undefined; } - function getIndexTypeOfSymbol(symbol, kind) { - var declaration = getIndexDeclarationOfSymbol(symbol, kind); - return declaration - ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType - : undefined; + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; } - function getConstraintOfTypeParameter(type) { - if (!type.constraint) { - if (type.target) { - var targetConstraint = getConstraintOfTypeParameter(type.target); - type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (declaration.flags & 64 /* Readonly */) !== 0, declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 139 /* TypeParameter */).constraint; + } + function hasConstraintReferenceTo(type, target) { + var checked; + while (type && !(type.flags & 33554432 /* ThisType */) && type.flags & 512 /* TypeParameter */ && !ts.contains(checked, type)) { + if (type === target) { + return true; + } + (checked || (checked = [])).push(type); + var constraintDeclaration = getConstraintDeclaration(type); + type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration); + } + return false; + } + function getConstraintOfTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 137 /* TypeParameter */).constraint); + var constraintDeclaration = getConstraintDeclaration(typeParameter); + var constraint = getTypeFromTypeNode(constraintDeclaration); + if (hasConstraintReferenceTo(constraint, typeParameter)) { + error(constraintDeclaration, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + constraint = unknownType; + } + typeParameter.constraint = constraint; } } - return type.constraint === noConstraintType ? undefined : type.constraint; + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 137 /* TypeParameter */).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 139 /* TypeParameter */).parent); } function getTypeListId(types) { if (types) { @@ -17373,50 +18746,6 @@ var ts; } return type; } - function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode, typeParameterSymbol) { - var links = getNodeLinks(typeReferenceNode); - if (links.isIllegalTypeReferenceInConstraint !== undefined) { - return links.isIllegalTypeReferenceInConstraint; - } - // bubble up to the declaration - var currentNode = typeReferenceNode; - // forEach === exists - while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { - 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 === 137 /* TypeParameter */; - return links.isIllegalTypeReferenceInConstraint; - } - function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { - var typeParameterSymbol; - function check(n) { - if (n.kind === 151 /* TypeReference */ && n.typeName.kind === 69 /* Identifier */) { - var links = getNodeLinks(n); - if (links.isIllegalTypeReferenceInConstraint === undefined) { - var symbol = resolveName(typeParameter, n.typeName.text, 793056 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (symbol && (symbol.flags & 262144 /* TypeParameter */)) { - // 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 - // symbol.declaration.parent === typeParameter.parent - // -> 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; }); - } - } - if (links.isIllegalTypeReferenceInConstraint) { - error(typeParameter, ts.Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); - } - } - ts.forEachChild(n, check); - } - if (typeParameter.constraint) { - typeParameterSymbol = getSymbolOfNode(typeParameter); - check(typeParameter.constraint); - } - } // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(symbol); @@ -17461,31 +18790,74 @@ var ts; } // 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 getTypeReferenceName(node) { + switch (node.kind) { + case 153 /* TypeReference */: + return node.typeName; + case 263 /* JSDocTypeReference */: + return node.name; + case 192 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + if (ts.isSupportedExpressionWithTypeArguments(node)) { + return node.expression; + } + } + return undefined; + } + function resolveTypeReferenceName(node, typeReferenceName) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, 793056 /* Type */) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + if (symbol === unknownSymbol) { + return unknownType; + } + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getTypeFromClassOrInterfaceReference(node, symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol); + } + if (symbol.flags & 107455 /* Value */ && node.kind === 263 /* JSDocTypeReference */) { + // A JSDocTypeReference may have resolved to a value (as opposed to a type). In + // that case, the type of this reference is just the type of the value we resolved + // to. + return getTypeOfSymbol(symbol); + } + return getTypeFromNonGenericTypeReference(node, symbol); + } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - // We only support expressions that are simple qualified names. For other expressions this produces undefined. - var typeNameOrExpression = node.kind === 151 /* 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); + var symbol = void 0; + var type = void 0; + if (node.kind === 263 /* JSDocTypeReference */) { + var typeReferenceName = getTypeReferenceName(node); + symbol = resolveTypeReferenceName(node, typeReferenceName); + type = getTypeReferenceType(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + else { + // We only support expressions that are simple qualified names. For other expressions this produces undefined. + var typeNameOrExpression = node.kind === 153 /* TypeReference */ ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056 /* Type */) || unknownSymbol; + type = symbol === unknownSymbol ? unknownType : + symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : + symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : + getTypeFromNonGenericTypeReference(node, symbol); + } // 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; @@ -17510,9 +18882,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: return declaration; } } @@ -17544,10 +18916,6 @@ var ts; if (arity === void 0) { arity = 0; } return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } - function tryGetGlobalType(name, arity) { - if (arity === void 0) { arity = 0; } - return getTypeOfGlobalSymbol(getGlobalSymbol(name, 793056 /* Type */, /*diagnostic*/ undefined), arity); - } /** * Returns a type that is inside a namespace at the global scope, e.g. * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type @@ -17667,7 +19035,7 @@ var ts; // a named type that circularly references itself. function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { - return emptyObjectType; + return emptyUnionType; } var typeSet = []; addTypesToSet(typeSet, types, 16384 /* Union */); @@ -17739,27 +19107,43 @@ var ts; } return links.resolvedType; } - function getStringLiteralType(node) { - if (ts.hasProperty(stringLiteralTypes, node.text)) { - return stringLiteralTypes[node.text]; + function getStringLiteralTypeForText(text) { + if (ts.hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; } - var type = stringLiteralTypes[node.text] = createType(256 /* StringLiteral */); - type.text = ts.getTextOfNode(node); + var type = stringLiteralTypes[text] = createType(256 /* StringLiteral */); + type.text = text; return type; } - function getTypeFromStringLiteral(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralType(node); + links.resolvedType = getStringLiteralTypeForText(node.text); + } + return links.resolvedType; + } + function getTypeFromJSDocVariadicType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + function getTypeFromJSDocTupleType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var types = ts.map(node.types, getTypeFromTypeNode); + links.resolvedType = createTupleType(types); } return links.resolvedType; } function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 215 /* InterfaceDeclaration */)) { - if (!(container.flags & 64 /* Static */) && - (container.kind !== 144 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { + if (parent && (ts.isClassLike(parent) || parent.kind === 219 /* InterfaceDeclaration */)) { + if (!(container.flags & 32 /* Static */) && + (container.kind !== 146 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -17776,49 +19160,65 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 117 /* AnyKeyword */: + case 254 /* JSDocAllType */: + case 255 /* JSDocUnknownType */: return anyType; - case 130 /* StringKeyword */: + case 131 /* StringKeyword */: return stringType; - case 128 /* NumberKeyword */: + case 129 /* NumberKeyword */: return numberType; case 120 /* BooleanKeyword */: return booleanType; - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: return esSymbolType; case 103 /* VoidKeyword */: return voidType; - case 97 /* ThisKeyword */: + case 163 /* ThisType */: return getTypeFromThisTypeNode(node); - case 9 /* StringLiteral */: - return getTypeFromStringLiteral(node); - case 151 /* TypeReference */: + case 164 /* StringLiteralType */: + return getTypeFromStringLiteralTypeNode(node); + case 153 /* TypeReference */: + case 263 /* JSDocTypeReference */: return getTypeFromTypeReference(node); - case 150 /* TypePredicate */: + case 152 /* TypePredicate */: return booleanType; - case 188 /* ExpressionWithTypeArguments */: + case 192 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 154 /* TypeQuery */: + case 156 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 156 /* ArrayType */: + case 158 /* ArrayType */: + case 256 /* JSDocArrayType */: return getTypeFromArrayTypeNode(node); - case 157 /* TupleType */: + case 159 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 158 /* UnionType */: + case 160 /* UnionType */: + case 257 /* JSDocUnionType */: return getTypeFromUnionTypeNode(node); - case 159 /* IntersectionType */: + case 161 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 160 /* ParenthesizedType */: + case 162 /* ParenthesizedType */: + case 259 /* JSDocNullableType */: + case 260 /* JSDocNonNullableType */: + case 267 /* JSDocConstructorType */: + case 268 /* JSDocThisType */: + case 264 /* JSDocOptionalType */: return getTypeFromTypeNode(node.type); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 155 /* TypeLiteral */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 157 /* TypeLiteral */: + case 265 /* JSDocFunctionType */: + case 261 /* JSDocRecordType */: 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 69 /* Identifier */: - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); + case 258 /* JSDocTupleType */: + return getTypeFromJSDocTupleType(node); + case 266 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -17875,18 +19275,22 @@ var ts; return t; }; } - function createInferenceMapper(context) { - var mapper = function (t) { - for (var i = 0; i < context.typeParameters.length; i++) { - if (t === context.typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); + function getInferenceMapper(context) { + if (!context.mapper) { + var mapper = function (t) { + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (t === typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } } - } - return t; - }; - mapper.context = context; - return mapper; + return t; + }; + mapper.context = context; + context.mapper = mapper; + } + return context.mapper; } function identityMapper(type) { return type; @@ -17894,31 +19298,44 @@ var ts; function combineTypeMappers(mapper1, mapper2) { return function (t) { return instantiateType(mapper1(t), mapper2); }; } - function instantiateTypeParameter(typeParameter, mapper) { + function cloneTypeParameter(typeParameter) { var result = createType(512 /* TypeParameter */); result.symbol = typeParameter.symbol; - if (typeParameter.constraint) { - result.constraint = instantiateType(typeParameter.constraint, mapper); + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; } else { - result.target = typeParameter; - result.mapper = mapper; + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; } - return result; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } } if (signature.typePredicate) { - freshTypePredicate = { - parameterName: signature.typePredicate.parameterName, - parameterIndex: signature.typePredicate.parameterIndex, - type: instantiateType(signature.typePredicate.type, mapper) - }; + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; @@ -17987,30 +19404,33 @@ var ts; } return type; } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return isContextSensitiveFunctionLikeDeclaration(node); - case 165 /* ObjectLiteralExpression */: + case 169 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return node.operatorToken.kind === 52 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 245 /* PropertyAssignment */: + case 249 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return isContextSensitive(node.expression); } return false; @@ -18036,9 +19456,12 @@ var ts; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); } - function compareTypes(source, target) { + function compareTypesIdentical(source, target) { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; } + function compareTypesAssignable(source, target) { + return checkTypeRelatedTo(source, target, assignableRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; + } function isTypeSubtypeOf(source, target) { return checkTypeSubtypeOf(source, target, /*errorNode*/ undefined); } @@ -18051,10 +19474,127 @@ var ts; function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } - function isSignatureAssignableTo(source, target) { - var sourceType = getOrCreateTypeFromSignature(source); - var targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, /*errorNode*/ undefined); + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return 0 /* False */; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1 /* True */; + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + var sourceParams = source.parameters; + var targetParams = target.parameters; + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(sourceParams[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(targetParams[i]) : getRestTypeOfSignature(target); + var related = compareTypes(t, s, /*reportErrors*/ false) || compareTypes(s, t, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name); + } + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } + else { + result &= compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */) { + var sourceIdentifierPredicate = source; + var targetIdentifierPredicate = target; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 /* False */ && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, /*errorNode*/ undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, /*errorNode*/ undefined)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + // If both have rest parameters, get the max and add 1 to + // compensate for the rest parameter. + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + // Return the count for whichever signature doesn't have rest parameters. + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). @@ -18074,22 +19614,12 @@ var ts; var expandingFlags; var depth = 0; var overflow = false; - var elaborateErrors = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, errorNode !== undefined, headMessage); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (overflow) { error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { - // If we already computed this relation, but in a context where we didn't want to report errors (e.g. overload resolution), - // then we'll only have a top-level error (e.g. 'Class X does not implement interface Y') without any details. If this happened, - // request a recompuation to get a complete error message. This will be skipped if we've already done this computation in a context - // where errors were being reported. - if (errorInfo.next === undefined) { - errorInfo = undefined; - elaborateErrors = true; - isRelatedTo(source, target, errorNode !== undefined, headMessage); - } if (containingMessageChain) { errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } @@ -18097,6 +19627,7 @@ var ts; } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { + ts.Debug.assert(!!errorNode); errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } function reportRelationError(message, source, target) { @@ -18128,6 +19659,11 @@ var ts; return -1 /* True */; if (source.flags & 128 /* Enum */ && target === numberType) return -1 /* True */; + if (source.flags & 128 /* Enum */ && target.flags & 128 /* Enum */) { + if (result = enumRelatedTo(source, target)) { + return result; + } + } if (source.flags & 256 /* StringLiteral */ && target === stringType) return -1 /* True */; if (relation === assignableRelation) { @@ -18136,6 +19672,9 @@ var ts; if (source === numberType && target.flags & 128 /* Enum */) return -1 /* True */; } + if (source.flags & 8 /* Boolean */ && target.flags & 8 /* Boolean */) { + return -1 /* True */; + } if (source.flags & 1048576 /* FreshObjectLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -18200,14 +19739,14 @@ var ts; } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var apparentType = getApparentType(source); + var apparentSource = getApparentType(source); // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (apparentType.flags & (80896 /* ObjectType */ | 32768 /* Intersection */) && target.flags & 80896 /* ObjectType */) { + if (apparentSource.flags & (80896 /* ObjectType */ | 32768 /* Intersection */) && target.flags & 80896 /* ObjectType */) { // Report structural errors only if we haven't reported any errors yet - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; - if (result = objectTypeRelatedTo(apparentType, source, target, reportStructuralErrors)) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726 /* Primitive */); + if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; } @@ -18229,9 +19768,6 @@ var ts; } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & 512 /* TypeParameter */ && target.flags & 512 /* TypeParameter */) { - return typeParameterIdenticalTo(source, target); - } if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -18250,7 +19786,7 @@ var ts; if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (relation === assignableRelation && (type === globalObjectType || resolved.properties.length === 0) || - resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) { + resolved.stringIndexInfo || resolved.numberIndexInfo || getPropertyOfType(type, name)) { return true; } } @@ -18265,7 +19801,7 @@ var ts; return false; } function hasExcessProperties(source, target, reportErrors) { - if (someConstituentTypeHasKind(target, 80896 /* ObjectType */)) { + if (!(target.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 80896 /* ObjectType */)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -18273,6 +19809,7 @@ var ts; // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. + ts.Debug.assert(!!errorNode); errorNode = prop.valueDeclaration; reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } @@ -18287,7 +19824,7 @@ var ts; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { var sourceType = sourceTypes_1[_i]; - var related = typeRelatedToSomeType(sourceType, target, false); + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); if (!related) { return 0 /* False */; } @@ -18347,8 +19884,9 @@ var ts; if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } + var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1 /* True */; - for (var i = 0; i < targets.length; i++) { + for (var i = 0; i < length; i++) { var related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return 0 /* False */; @@ -18357,34 +19895,24 @@ var ts; } return result; } - function typeParameterIdenticalTo(source, target) { - if (source.symbol.name !== target.symbol.name) { - return 0 /* False */; - } - // covers case when both type parameters does not have constraint (both equal to noConstraintType) - if (source.constraint === target.constraint) { - return -1 /* True */; - } - if (source.constraint === noConstraintType || target.constraint === noConstraintType) { - return 0 /* False */; - } - return isIdenticalTo(source.constraint, target.constraint); - } // Determine if two object types are related by structure. First, check if the result is already available in the global cache. // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function objectTypeRelatedTo(apparentSource, originalSource, target, reportErrors) { + function objectTypeRelatedTo(source, originalSource, target, reportErrors) { if (overflow) { return 0 /* False */; } - var id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { - // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate - // errors, we can use the cached value. Otherwise, recompute the relation - if (!elaborateErrors || (related === 3 /* FailedAndReported */)) { + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported + // failure and continue computing the relation such that errors get reported. + relation[id] = 3 /* FailedAndReported */; + } + else { return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; } } @@ -18406,13 +19934,13 @@ var ts; maybeStack = []; expandingFlags = 0; } - sourceStack[depth] = apparentSource; + sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; @@ -18421,15 +19949,15 @@ var ts; result = 1 /* Maybe */; } else { - result = propertiesRelatedTo(apparentSource, target, reportErrors); + result = propertiesRelatedTo(source, target, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 0 /* Call */, reportErrors); + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 1 /* Construct */, reportErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportErrors); if (result) { - result &= stringIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= indexTypesRelatedTo(source, originalSource, target, 0 /* String */, reportErrors); if (result) { - result &= numberIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= indexTypesRelatedTo(source, originalSource, target, 1 /* Number */, reportErrors); } } } @@ -18472,23 +20000,23 @@ var ts; else if (!(targetProp.flags & 134217728 /* Prototype */)) { var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); - if (sourcePropFlags & 16 /* Private */ || targetPropFlags & 16 /* Private */) { + if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & 16 /* Private */ && targetPropFlags & 16 /* Private */) { + if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 16 /* Private */ ? source : target), typeToString(sourcePropFlags & 16 /* Private */ ? target : source)); + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); } } return 0 /* False */; } } - else if (targetPropFlags & 32 /* Protected */) { + else if (targetPropFlags & 16 /* Protected */) { var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32 /* Class */; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; - var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); + var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; + var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); @@ -18496,7 +20024,7 @@ var ts; return 0 /* False */; } } - else if (sourcePropFlags & 32 /* Protected */) { + else if (sourcePropFlags & 16 /* Protected */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -18561,154 +20089,49 @@ var ts; } var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0 /* False */; + } + } var result = -1 /* True */; var saveErrorInfo = errorInfo; - if (kind === 1 /* Construct */) { - // Only want to compare the construct signatures for abstractness guarantees. - // Because the "abstractness" of a class is the same across all construct signatures - // (internally we are checking the corresponding declaration), it is enough to perform - // the check and report an error once over all pairs of source and target construct signatures. - // - // sourceSig and targetSig are (possibly) undefined. - // - // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. - var sourceSig = sourceSignatures[0]; - var targetSig = targetSignatures[0]; - result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); - if (result !== -1 /* True */) { - return result; - } - } outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; - if (!t.hasStringLiterals || target.flags & 262144 /* FromSignature */) { - var localErrors = reportErrors; - var checkedAbstractAssignability = false; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { - var related = signatureRelatedTo(s, t, localErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; - } - // Only report errors from the first failure - localErrors = false; - } + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; } - return 0 /* False */; + shouldElaborateErrors = false; } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; } return result; - function abstractSignatureRelatedTo(source, sourceSig, target, targetSig) { - if (sourceSig && targetSig) { - var sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - var targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); - if (!sourceDecl) { - // If the source object isn't itself a class declaration, it can be freely assigned, regardless - // of whether the constructed object is abstract or not. - return -1 /* True */; - } - var sourceErasedSignature = getErasedSignature(sourceSig); - var targetErasedSignature = getErasedSignature(targetSig); - var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128 /* Abstract */; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128 /* Abstract */; - if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { - // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0 /* False */; - } - } - return -1 /* True */; - } } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ function signatureRelatedTo(source, target, reportErrors) { - if (source === target) { - return -1 /* True */; - } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return 0 /* False */; - } - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var checkCount; - if (source.hasRestParameter && target.hasRestParameter) { - checkCount = sourceMax > targetMax ? sourceMax : targetMax; - sourceMax--; - targetMax--; - } - else if (source.hasRestParameter) { - sourceMax--; - checkCount = targetMax; - } - else if (target.hasRestParameter) { - targetMax--; - checkCount = sourceMax; - } - else { - checkCount = sourceMax < targetMax ? sourceMax : targetMax; - } - // Spec 1.0 Section 3.8.3 & 3.8.4: - // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1 /* True */; - for (var i = 0; i < checkCount; i++) { - var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); - var saveErrorInfo = errorInfo; - var related = isRelatedTo(s, t, reportErrors); - if (!related) { - related = isRelatedTo(t, s, false); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); - } - return 0 /* False */; - } - errorInfo = saveErrorInfo; - } - 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 targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) - return result; - var sourceReturnType = getReturnTypeOfSignature(source); - return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); + return compareSignaturesRelated(source, target, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -18717,8 +20140,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var i = 0, len = sourceSignatures.length; i < len; ++i) { - var related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + for (var i = 0, len = sourceSignatures.length; i < len; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); if (!related) { return 0 /* False */; } @@ -18726,83 +20149,128 @@ var ts; } return result; } - function stringIndexTypesRelatedTo(source, originalSource, target, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(0 /* String */, source, target); - } - var targetType = getIndexTypeOfType(target, 0 /* String */); - if (targetType) { - if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { - // non-primitive assignment to any is always allowed, eg - // `var x: { [index: string]: any } = { property: 12 };` - return -1 /* True */; - } - var sourceType = getIndexTypeOfType(source, 0 /* String */); - if (!sourceType) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1 /* True */; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.name)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0 /* False */; } - return 0 /* False */; + result &= related; } - var related = isRelatedTo(sourceType, targetType, reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return 0 /* False */; - } - return related; } - return -1 /* True */; + return result; } - function numberIndexTypesRelatedTo(source, originalSource, target, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(1 /* Number */, source, target); + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); } - var targetType = getIndexTypeOfType(target, 1 /* Number */); - if (targetType) { - if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { - // non-primitive assignment to any is always allowed, eg - // `var x: { [index: number]: any } = { property: 12 };` - return -1 /* True */; - } - var sourceStringType = getIndexTypeOfType(source, 0 /* String */); - var sourceNumberType = getIndexTypeOfType(source, 1 /* Number */); - if (!(sourceStringType || sourceNumberType)) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); - } - return 0 /* False */; - } - var related; - if (sourceStringType && sourceNumberType) { - // If we know for sure we're testing both string and numeric index types then only report errors from the second one - related = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors); - } - else { - related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); - } - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return 0 /* False */; - } - return related; - } - return -1 /* True */; + return related; } - function indexTypesIdenticalTo(indexKind, source, target) { - var targetType = getIndexTypeOfType(target, indexKind); - var sourceType = getIndexTypeOfType(source, indexKind); - if (!sourceType && !targetType) { + function indexTypesRelatedTo(source, originalSource, target, kind, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */))) { + // Index signature of type any permits assignment from everything but primitives return -1 /* True */; } - if (sourceType && targetType) { - return isRelatedTo(sourceType, targetType); + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isObjectLiteralType(source)) { + var related = -1 /* True */; + if (kind === 0 /* String */) { + var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } return 0 /* False */; } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1 /* True */; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0 /* False */; + } + function enumRelatedTo(source, target) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & 128 /* ConstEnum */ || + target.symbol.flags & 128 /* ConstEnum */) { + return 0 /* False */; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + return 0 /* False */; + } + } + } + return -1 /* True */; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = sourceSignature.declaration.flags & (8 /* Private */ | 16 /* Protected */); + var targetAccessibility = targetSignature.declaration.flags & (8 /* Private */ | 16 /* Protected */); + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === 8 /* Private */) { + return true; + } + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { + return true; + } + // Only a public signature is assignable to public signature. + if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type) { + if (type.flags & 65536 /* Anonymous */) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && declaration.flags & 128 /* Abstract */) { + return true; + } + } + } + return 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, @@ -18826,7 +20294,7 @@ var ts; return false; } function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypes) !== 0 /* False */; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; } function compareProperties(sourceProp, targetProp, compareTypes) { // Two members are considered identical when @@ -18835,8 +20303,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (16 /* Private */ | 32 /* Protected */); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (16 /* Private */ | 32 /* Protected */); + var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (8 /* Private */ | 16 /* Protected */); + var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (8 /* Private */ | 16 /* Protected */); if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -18850,41 +20318,52 @@ var ts; return 0 /* False */; } } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0 /* False */; + } return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } - function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + function isMatchingSignature(source, target, partialMatch) { + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters and no more overall parameters than the source signature (where a signature with a rest + // parameter is always considered to have more overall parameters than one without). + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; } - if (source.parameters.length !== target.parameters.length || - source.minArgumentCount !== target.minArgumentCount || - source.hasRestParameter !== target.hasRestParameter) { - if (!partialMatch || - source.parameters.length < target.parameters.length && !source.hasRestParameter || - source.minArgumentCount > target.minArgumentCount) { - return 0 /* False */; - } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0 /* False */; } - var result = -1 /* True */; - if (source.typeParameters && target.typeParameters) { - if (source.typeParameters.length !== target.typeParameters.length) { - return 0 /* False */; - } - for (var i = 0, len = source.typeParameters.length; i < len; ++i) { - var related = compareTypes(source.typeParameters[i], target.typeParameters[i]); - if (!related) { - return 0 /* False */; - } - result &= related; - } - } - else if (source.typeParameters || target.typeParameters) { + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) { return 0 /* False */; } // Spec 1.0 Section 3.8.3 & 3.8.4: // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N source = getErasedSignature(source); target = getErasedSignature(target); + var result = -1 /* True */; var targetLen = target.parameters.length; for (var i = 0; i < targetLen; i++) { var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); @@ -18951,12 +20430,17 @@ var ts; return type.flags & 4096 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { - // A type is array-like if it is not the undefined or null type and if it is assignable to any[] - return !(type.flags & (32 /* Undefined */ | 64 /* Null */)) && isTypeAssignableTo(type, anyArrayType); + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return type.flags & 4096 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & (32 /* Undefined */ | 64 /* Null */)) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } + function isStringLiteralType(type) { + return type.flags & 256 /* StringLiteral */; + } /** * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. @@ -18964,6 +20448,15 @@ var ts; function isTupleType(type) { return !!(type.flags & 8192 /* Tuple */); } + /** + * Return true if type was inferred from an object literal or written as an object type literal + * with no call or construct signatures. + */ + function isObjectLiteralType(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && + getSignaturesOfType(type, 0 /* Call */).length === 0 && + getSignaturesOfType(type, 1 /* Construct */).length === 0; + } function getRegularTypeOfObjectLiteral(type) { if (type.flags & 1048576 /* FreshObjectLiteral */) { var regularType = type.regularType; @@ -18974,8 +20467,8 @@ var ts; regularType.properties = type.properties; regularType.callSignatures = type.callSignatures; regularType.constructSignatures = type.constructSignatures; - regularType.stringIndexType = type.stringIndexType; - regularType.numberIndexType = type.numberIndexType; + regularType.stringIndexInfo = type.stringIndexInfo; + regularType.numberIndexInfo = type.numberIndexInfo; type.regularType = regularType; } return regularType; @@ -19000,13 +20493,9 @@ var ts; } members[p.name] = p; }); - var stringIndexType = getIndexTypeOfType(type, 0 /* String */); - var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); - if (stringIndexType) - stringIndexType = getWidenedType(stringIndexType); - if (numberIndexType) - numberIndexType = getWidenedType(numberIndexType); - return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); + var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedType(type) { if (type.flags & 6291456 /* RequiresWidening */) { @@ -19078,22 +20567,22 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 138 /* Parameter */: + case 140 /* 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 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -19140,13 +20629,7 @@ var ts; } } function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var unused = typeParameters_1[_i]; - inferences.push({ - primary: undefined, secondary: undefined, isFixed: false - }); - } + var inferences = ts.map(typeParameters, createTypeInferencesObject); return { typeParameters: typeParameters, inferUnionTypes: inferUnionTypes, @@ -19154,11 +20637,19 @@ var ts; inferredTypes: new Array(typeParameters.length) }; } + function createTypeInferencesObject() { + return { + primary: undefined, + secondary: undefined, + isFixed: false + }; + } function inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; + var visited = {}; inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -19169,6 +20660,29 @@ var ts; return false; } function inferFromTypes(source, target) { + if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || + source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { + // Source and target are both unions or both intersections. First, find each + // target constituent type that has an identically matching source constituent + // type, and for each such target constituent type infer from the type to itself. + // When inferring from a type to itself we effectively find all type parameter + // occurrences within that type and infer themselves as their type arguments. + var matchingTypes = void 0; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (typeIdenticalToSomeType(t, source.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } if (target.flags & 512 /* TypeParameter */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). @@ -19221,10 +20735,10 @@ var ts; else if (target.flags & 49152 /* UnionOrIntersection */) { var targetTypes = target.types; var typeParameterCount = 0; - var typeParameter; + var typeParameter = void 0; // First infer to each type in union or intersection that isn't a type parameter - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var t = targetTypes_2[_i]; + for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { + var t = targetTypes_2[_b]; if (t.flags & 512 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -19244,24 +20758,31 @@ var ts; } } else if (source.flags & 49152 /* UnionOrIntersection */) { - // Source is a union or intersection type, infer from each consituent type + // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { - var sourceType = sourceTypes_3[_a]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 /* ObjectType */ && (target.flags & (4096 /* Reference */ | 8192 /* Tuple */) || - (target.flags & 65536 /* Anonymous */) && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { - // 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 (source.flags & 80896 /* ObjectType */ && (target.flags & 4096 /* Reference */ && target.typeArguments || + target.flags & 8192 /* Tuple */ || + target.flags & 65536 /* Anonymous */ && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { + // If source is an object type, and target is a type reference with type arguments, a tuple type, + // the type of a method, or a type literal, infer from members if (isInProcess(source, target)) { return; } if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { return; } + var key = source.id + "," + target.id; + if (ts.hasProperty(visited, key)) { + return; + } + visited[key] = true; if (depth === 0) { sourceStack = []; targetStack = []; @@ -19272,9 +20793,7 @@ var ts; 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 */); + inferFromIndexTypes(source, target); depth--; } } @@ -19301,28 +20820,56 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - 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); - } + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } } - function inferFromIndexTypes(source, target, sourceKind, targetKind) { - var targetIndexType = getIndexTypeOfType(target, targetKind); - if (targetIndexType) { - var sourceIndexType = getIndexTypeOfType(source, sourceKind); + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 0 /* String */); if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetIndexType); + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || + getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 1 /* Number */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); } } } } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 16384 /* Union */ ? getUnionType(reducedTypes, /*noSubtypeReduction*/ true) : getIntersectionType(reducedTypes); + } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; @@ -19346,10 +20893,16 @@ var ts; inferredType = emptyObjectType; inferenceSucceeded = true; } + context.inferredTypes[index] = inferredType; // Only do the constraint check if inference succeeded (to prevent cascading errors) if (inferenceSucceeded) { var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + context.inferredTypes[index] = inferredType = instantiatedConstraint; + } + } } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { // If inference failed, it is necessary to record the index of the failed type parameter (the one we are on). @@ -19357,7 +20910,6 @@ var ts; // So if this failure is on preceding type parameter, this type parameter is the new failure index. context.failedTypeParameterIndex = index; } - context.inferredTypes[index] = inferredType; } return inferredType; } @@ -19367,9 +20919,6 @@ var ts; } return context.inferredTypes; } - function hasAncestor(node, kind) { - return ts.getAncestor(node, kind) !== undefined; - } // EXPRESSION TYPE CHECKING function getResolvedSymbol(node) { var links = getNodeLinks(node); @@ -19384,10 +20933,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 154 /* TypeQuery */: + case 156 /* TypeQuery */: return true; case 69 /* Identifier */: - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: node = node.parent; continue; default: @@ -19396,26 +20945,6 @@ var ts; } ts.Debug.fail("should not get here"); } - // For a union type, remove all constituent types that are of the given type kind (when isOfTypeKind is true) - // or not of the given type kind (when isOfTypeKind is false) - function removeTypesFromUnionType(type, typeKind, isOfTypeKind, allowEmptyUnionResult) { - if (type.flags & 16384 /* Union */) { - var types = type.types; - if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { - // Above we checked if we have anything to remove, now use the opposite test to do the removal - var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); - if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { - return narrowedType; - } - } - } - else if (allowEmptyUnionResult && !!(type.flags & typeKind) === isOfTypeKind) { - // Use getUnionType(emptyArray) instead of emptyObjectType in case the way empty union types - // are represented ever changes. - return getUnionType(emptyArray); - } - return type; - } function hasInitializer(node) { return !!(node.initializer || ts.isBindingPattern(node.parent) && hasInitializer(node.parent.parent)); } @@ -19434,10 +20963,7 @@ var ts; return links.assignmentChecks[symbol.id] = isAssignedIn(node); function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 56 /* FirstAssignment */ && node.operatorToken.kind <= 68 /* LastAssignment */) { - var n = node.left; - while (n.kind === 172 /* ParenthesizedExpression */) { - n = n.expression; - } + var n = skipParenthesizedNodes(node.left); if (n.kind === 69 /* Identifier */ && getResolvedSymbol(n) === symbol) { return true; } @@ -19452,55 +20978,55 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return isAssignedInBinaryExpression(node); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: return isAssignedInVariableDeclaration(node); - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: - case 172 /* ParenthesizedExpression */: - case 179 /* PrefixUnaryExpression */: - case 175 /* DeleteExpression */: - case 178 /* AwaitExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 180 /* PostfixUnaryExpression */: - case 184 /* YieldExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 192 /* Block */: - case 193 /* VariableStatement */: - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 204 /* ReturnStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - case 235 /* JsxOpeningElement */: - case 240 /* JsxExpression */: + case 165 /* ObjectBindingPattern */: + case 166 /* ArrayBindingPattern */: + case 168 /* ArrayLiteralExpression */: + case 169 /* ObjectLiteralExpression */: + case 170 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 175 /* TypeAssertionExpression */: + case 193 /* AsExpression */: + case 176 /* ParenthesizedExpression */: + case 183 /* PrefixUnaryExpression */: + case 179 /* DeleteExpression */: + case 182 /* AwaitExpression */: + case 180 /* TypeOfExpression */: + case 181 /* VoidExpression */: + case 184 /* PostfixUnaryExpression */: + case 188 /* YieldExpression */: + case 186 /* ConditionalExpression */: + case 189 /* SpreadElementExpression */: + case 196 /* Block */: + case 197 /* VariableStatement */: + case 199 /* ExpressionStatement */: + case 200 /* IfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 208 /* ReturnStatement */: + case 209 /* WithStatement */: + case 210 /* SwitchStatement */: + case 245 /* CaseClause */: + case 246 /* DefaultClause */: + case 211 /* LabeledStatement */: + case 212 /* ThrowStatement */: + case 213 /* TryStatement */: + case 248 /* CatchClause */: + case 237 /* JsxElement */: + case 238 /* JsxSelfClosingElement */: + case 242 /* JsxAttribute */: + case 243 /* JsxSpreadAttribute */: + case 239 /* JsxOpeningElement */: + case 244 /* JsxExpression */: return ts.forEachChild(node, isAssignedIn); } return false; @@ -19512,59 +21038,73 @@ var ts; // Only narrow when symbol is variable of type any or an object, union, or type parameter type if (node && symbol.flags & 3 /* Variable */) { if (isTypeAny(type) || type.flags & (80896 /* ObjectType */ | 16384 /* Union */ | 512 /* TypeParameter */)) { + var declaration = ts.getDeclarationOfKind(symbol, 215 /* VariableDeclaration */); + var top_1 = declaration && getDeclarationContainer(declaration); + var originalType = type; + var nodeStack = []; loop: while (node.parent) { var child = node; node = node.parent; - var narrowedType = type; switch (node.kind) { - case 196 /* 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); - } + case 200 /* IfStatement */: + case 186 /* ConditionalExpression */: + case 185 /* BinaryExpression */: + nodeStack.push({ node: node, child: child }); break; - case 182 /* 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 181 /* BinaryExpression */: - // In the right operand of an && or ||, narrow based on left operand - if (child === node.right) { - if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { - narrowedType = narrowType(type, node.left, /*assumeTrue*/ true); - } - else if (node.operatorToken.kind === 52 /* BarBarToken */) { - narrowedType = narrowType(type, node.left, /*assumeTrue*/ false); - } - } - break; - case 248 /* SourceFile */: - case 218 /* ModuleDeclaration */: - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 144 /* Constructor */: - // Stop at the first containing function or module declaration + case 252 /* SourceFile */: + case 222 /* ModuleDeclaration */: + // Stop at the first containing file 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; + if (node === top_1) { + break; } } + var nodes = void 0; + while (nodes = nodeStack.pop()) { + var node_1 = nodes.node, child = nodes.child; + switch (node_1.kind) { + case 200 /* IfStatement */: + // In a branch of an if statement, narrow based on controlling expression + if (child !== node_1.expression) { + type = narrowType(type, node_1.expression, /*assumeTrue*/ child === node_1.thenStatement); + } + break; + case 186 /* ConditionalExpression */: + // In a branch of a conditional expression, narrow based on controlling condition + if (child !== node_1.condition) { + type = narrowType(type, node_1.condition, /*assumeTrue*/ child === node_1.whenTrue); + } + break; + case 185 /* BinaryExpression */: + // In the right operand of an && or ||, narrow based on left operand + if (child === node_1.right) { + if (node_1.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + type = narrowType(type, node_1.left, /*assumeTrue*/ true); + } + else if (node_1.operatorToken.kind === 52 /* BarBarToken */) { + type = narrowType(type, node_1.left, /*assumeTrue*/ false); + } + } + break; + default: + ts.Debug.fail("Unreachable!"); + } + // Use original type if construct contains assignments to variable + if (type !== originalType && isVariableAssignedWithin(symbol, node_1)) { + type = originalType; + } + } + // Preserve old top-level behavior - if the branch is really an empty set, revert to prior type + if (type === emptyUnionType) { + type = originalType; + } } } 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 !== 176 /* TypeOfExpression */ || expr.right.kind !== 9 /* StringLiteral */) { + if (expr.left.kind !== 180 /* TypeOfExpression */ || expr.right.kind !== 9 /* StringLiteral */) { return type; } var left = expr.left; @@ -19572,31 +21112,34 @@ var ts; if (left.expression.kind !== 69 /* Identifier */ || getResolvedSymbol(left.expression) !== symbol) { return type; } - var typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue) { - // Assumed result is true. If check was not for a primitive type, remove all primitive types - if (!typeInfo) { - return removeTypesFromUnionType(type, /*typeKind*/ 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */ | 16777216 /* ESSymbol */, - /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); - } - // Check was for a primitive type, return that primitive type if it is a subtype - if (isTypeSubtypeOf(typeInfo.type, type)) { - return typeInfo.type; - } - // Otherwise, remove all types that aren't of the primitive type kind. This can happen when the type is - // union of enum types and other types. - return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ false, /*allowEmptyUnionResult*/ false); + var typeInfo = primitiveTypeInfo[right.text]; + // Don't narrow `undefined` + if (typeInfo && typeInfo.type === undefinedType) { + return type; + } + var flags; + if (typeInfo) { + flags = typeInfo.flags; } else { - // Assumed result is false. If check was for a primitive type, remove that primitive type - if (typeInfo) { - return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); + assumeTrue = !assumeTrue; + flags = 132 /* NumberLike */ | 258 /* StringLike */ | 16777216 /* ESSymbol */ | 8 /* Boolean */; + } + // At this point we can bail if it's not a union + if (!(type.flags & 16384 /* Union */)) { + // If we're on the true branch and the type is a subtype, we should return the primitive type + if (assumeTrue && typeInfo && isTypeSubtypeOf(typeInfo.type, type)) { + return typeInfo.type; } - // Otherwise we don't have enough information to do anything. - return type; + // If the active non-union type would be removed from a union by this type guard, return an empty union + return filterUnion(type) ? type : emptyUnionType; + } + return getUnionType(ts.filter(type.types, filterUnion), /*noSubtypeReduction*/ true); + function filterUnion(type) { + return assumeTrue === !!(type.flags & flags); } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -19609,7 +21152,7 @@ var ts; // and the second operand was false. We narrow with those assumptions and union the two resulting types. return getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ false), - narrowType(narrowType(type, expr.left, /*assumeTrue*/ true), expr.right, /*assumeTrue*/ false) + narrowType(type, expr.right, /*assumeTrue*/ false) ]); } } @@ -19619,7 +21162,7 @@ var ts; // and the second operand was true. We narrow with those assumptions and union the two resulting types. return getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ true), - narrowType(narrowType(type, expr.left, /*assumeTrue*/ false), expr.right, /*assumeTrue*/ true) + narrowType(type, expr.right, /*assumeTrue*/ true) ]); } else { @@ -19629,7 +21172,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 (isTypeAny(type) || !assumeTrue || expr.left.kind !== 69 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) { + if (isTypeAny(type) || expr.left.kind !== 69 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) { return type; } // Check that right operand is a function type with a prototype property @@ -19648,7 +21191,7 @@ var ts; } if (!targetType) { // Target type is type of construct signature - var constructSignatures; + var constructSignatures = void 0; if (rightType.flags & 2048 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } @@ -19660,11 +21203,17 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType); + return getNarrowedType(type, targetType, assumeTrue); } return type; } - function getNarrowedType(originalType, narrowedTypeCandidate) { + function getNarrowedType(originalType, narrowedTypeCandidate, assumeTrue) { + if (!assumeTrue) { + if (originalType.flags & 16384 /* Union */) { + return getUnionType(ts.filter(originalType.types, function (t) { return !isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } // If the current type is a union type, remove all constituents that aren't assignable to target. If that produces // 0 candidates, fall back to the assignability check if (originalType.flags & 16384 /* Union */) { @@ -19679,33 +21228,54 @@ var ts; } return originalType; } - function narrowTypeByTypePredicate(type, expr, assumeTrue) { + function narrowTypeByTypePredicate(type, callExpression, 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; + var signature = getResolvedSignature(callExpression); + var predicate = signature.typePredicate; + if (!predicate) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + if (callExpression.arguments[predicate.parameterIndex] && + getSymbolAtTypePredicatePosition(callExpression.arguments[predicate.parameterIndex]) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); } - return getNarrowedType(type, signature.typePredicate.type); + } + else { + var invokedExpression = skipParenthesizedNodes(callExpression.expression); + return narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue); } return type; } + function narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue) { + if (invokedExpression.kind === 171 /* ElementAccessExpression */ || invokedExpression.kind === 170 /* PropertyAccessExpression */) { + var accessExpression = invokedExpression; + var possibleIdentifier = skipParenthesizedNodes(accessExpression.expression); + if (possibleIdentifier.kind === 69 /* Identifier */ && getSymbolAtTypePredicatePosition(possibleIdentifier) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); + } + } + return type; + } + function getSymbolAtTypePredicatePosition(expr) { + expr = skipParenthesizedNodes(expr); + switch (expr.kind) { + case 69 /* Identifier */: + case 170 /* PropertyAccessExpression */: + return getSymbolOfEntityNameOrPropertyAccessExpression(expr); + } + } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 168 /* CallExpression */: + case 172 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: var operator = expr.operatorToken.kind; if (operator === 32 /* EqualsEqualsEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -19720,7 +21290,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: if (expr.operator === 49 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -19729,6 +21299,12 @@ var ts; return type; } } + function skipParenthesizedNodes(expression) { + while (expression.kind === 176 /* ParenthesizedExpression */) { + expression = expression.expression; + } + return expression; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. @@ -19739,23 +21315,40 @@ var ts; // can explicitly bound arguments objects if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 174 /* ArrowFunction */) { + if (container.kind === 178 /* ArrowFunction */) { if (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 (node.parserContextFlags & 8 /* Await */) { - getNodeLinks(container).flags |= 4096 /* CaptureArguments */; - getNodeLinks(node).flags |= 2048 /* LexicalArguments */; + if (node.flags & 33554432 /* AwaitContext */) { + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; } } if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (languageVersion === 2 /* ES6 */ + && localOrExportSymbol.flags & 32 /* Class */ + && localOrExportSymbol.valueDeclaration.kind === 218 /* ClassDeclaration */ + && ts.nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { + getNodeLinks(container).flags |= 524288 /* ClassWithBodyScopedClassBinding */; + getNodeLinks(node).flags |= 1048576 /* BodyScopedClassBinding */; + break; + } + container = ts.getContainingClass(container); + } + } checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); - checkBlockScopedBindingCapturedInLoop(node, symbol); - return getNarrowedTypeOfSymbol(getExportSymbolOfValueSymbolIfExported(symbol), node); + checkNestedBlockScopedBinding(node, symbol); + return getNarrowedTypeOfSymbol(localOrExportSymbol, node); } function isInsideFunction(node, threshold) { var current = node; @@ -19767,52 +21360,79 @@ var ts; } return false; } - function checkBlockScopedBindingCapturedInLoop(node, symbol) { + function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES6 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 244 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 248 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check // if there is anything function like between declaration and use-site (is binding/class is captured in function). // 2. walk from the declaration up to the boundary of lexical environment and check // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) - var container; - if (symbol.flags & 32 /* Class */) { - // get parent of class declaration - container = getClassLikeDeclarationOfSymbol(symbol).parent; - } - else { - // nesting structure: - // (variable declaration or binding element) -> variable declaration list -> container - container = symbol.valueDeclaration; - while (container.kind !== 212 /* VariableDeclarationList */) { - container = container.parent; - } - // get the parent of variable declaration list - container = container.parent; - if (container.kind === 193 /* VariableStatement */) { - // if parent is variable statement - get its parent - container = container.parent; - } - } - var inFunction = isInsideFunction(node.parent, container); + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); var current = container; + var containedInIterationStatement = false; while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - if (inFunction) { - getNodeLinks(current).flags |= 65536 /* LoopWithBlockScopedBindingCapturedInFunction */; - } - // mark value declaration so during emit they can have a special handling - getNodeLinks(symbol.valueDeclaration).flags |= 16384 /* BlockScopedBindingInLoop */; + containedInIterationStatement = true; break; } current = current.parent; } + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 203 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 216 /* VariableDeclarationList */).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + } + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + } + } + function isAssignedInBodyOfForStatement(node, container) { + var current = node; + // skip parenthesized nodes + while (current.parent.kind === 176 /* ParenthesizedExpression */) { + current = current.parent; + } + // check if node is used as LHS in some assignment expression + var isAssigned = false; + if (current.parent.kind === 185 /* BinaryExpression */) { + isAssigned = current.parent.left === current && ts.isAssignmentOperator(current.parent.operatorToken.kind); + } + if ((current.parent.kind === 183 /* PrefixUnaryExpression */ || current.parent.kind === 184 /* PostfixUnaryExpression */)) { + var expr = current.parent; + isAssigned = expr.operator === 41 /* PlusPlusToken */ || expr.operator === 42 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + while (current !== container) { + if (current === container.statement) { + return true; + } + else { + current = current.parent; + } + } + return false; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 141 /* PropertyDeclaration */ || container.kind === 144 /* Constructor */) { + if (container.kind === 143 /* PropertyDeclaration */ || container.kind === 146 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -19820,38 +21440,93 @@ var ts; getNodeLinks(container).flags |= 4 /* CaptureThis */; } } + function findFirstSuperCall(n) { + if (ts.isSuperCallExpression(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullType; + } function checkThisExpression(node) { // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; + if (container.kind === 146 /* Constructor */) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + } + } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 174 /* ArrowFunction */) { + if (container.kind === 178 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code needToCaptureLexicalThis = (languageVersion < 2 /* ES6 */); } switch (container.kind) { - case 218 /* ModuleDeclaration */: + case 222 /* 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 217 /* EnumDeclaration */: + case 221 /* 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 144 /* Constructor */: + case 146 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - if (container.flags & 64 /* Static */) { + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + if (container.flags & 32 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 136 /* ComputedPropertyName */: + case 138 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -19860,69 +21535,183 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - return container.flags & 64 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return container.flags & 32 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + } + if (ts.isInJavaScriptFile(node)) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + // If this is a function in a JS file, it might be a class method. Check if it's the RHS + // of a x.prototype.y = function [name]() { .... } + if (container.kind === 177 /* FunctionExpression */) { + if (ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') + var className = container.parent // x.prototype.y = f + .left // x.prototype.y + .expression // x.prototype + .expression; // x + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + return getInferredClassType(classSymbol); + } + } + } } return anyType; } + function getTypeForThisExpressionFromJSDoc(node) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === 265 /* JSDocFunctionType */) { + var jsDocFunctionType = typeTag.typeExpression.type; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 268 /* JSDocThisType */) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 138 /* Parameter */) { + if (n.kind === 140 /* Parameter */) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 168 /* CallExpression */ && node.parent.expression === node; - var classDeclaration = ts.getContainingClass(node); - var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - var container = ts.getSuperContainer(node, /*includeFunctions*/ true); + var isCallExpression = node.parent.kind === 172 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; if (!isCallExpression) { // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting - while (container && container.kind === 174 /* ArrowFunction */) { - container = ts.getSuperContainer(container, /*includeFunctions*/ true); + while (container && container.kind === 178 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; - // always set NodeCheckFlags for 'super' expression node - if (canUseSuperExpression) { - if ((container.flags & 64 /* Static */) || isCallExpression) { - nodeCheckFlag = 512 /* SuperStatic */; - } - else { - nodeCheckFlag = 256 /* SuperInstance */; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (needToCaptureLexicalThis) { - // call expressions are allowed only in constructors so they should always capture correct 'this' - // super property access expressions can also appear in arrow functions - - // in this case they should also use correct lexical this - captureLexicalThis(node.parent, container); - } - } - if (!baseClassType) { - if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } if (!canUseSuperExpression) { - if (container && container.kind === 136 /* ComputedPropertyName */) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = node; + while (current && current !== container && current.kind !== 138 /* ComputedPropertyName */) { + current = current.parent; + } + if (current && current.kind === 138 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 169 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } else { error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } return unknownType; } - if (container.kind === 144 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if ((container.flags & 32 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = name => super[name]; + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super("asyncMethod").call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + // return __awaiter(this, arguments, Promise, function *() { + // [_super("a").value, _super("b").value] = yield ar; + // }); + // } + // ... + // + // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. + // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment + // while a property access can. + if (container.kind === 145 /* MethodDeclaration */ && container.flags & 256 /* Async */) { + if (ts.isSuperPropertyOrElementAccess(node.parent) && isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; + } + else { + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; + } + } + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 169 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES6 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } + if (container.kind === 146 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; @@ -19937,29 +21726,29 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 144 /* Constructor */; + return container.kind === 146 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) // 'super' property access is allowed // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor - // topmost container must be something that is directly nested in the class declaration - if (container && ts.isClassLike(container.parent)) { - if (container.flags & 64 /* Static */) { - return container.kind === 143 /* MethodDeclaration */ || - container.kind === 142 /* MethodSignature */ || - container.kind === 145 /* GetAccessor */ || - container.kind === 146 /* SetAccessor */; + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 169 /* ObjectLiteralExpression */) { + if (container.flags & 32 /* Static */) { + return container.kind === 145 /* MethodDeclaration */ || + container.kind === 144 /* MethodSignature */ || + container.kind === 147 /* GetAccessor */ || + container.kind === 148 /* SetAccessor */; } else { - return container.kind === 143 /* MethodDeclaration */ || - container.kind === 142 /* MethodSignature */ || - container.kind === 145 /* GetAccessor */ || - container.kind === 146 /* SetAccessor */ || - container.kind === 141 /* PropertyDeclaration */ || - container.kind === 140 /* PropertySignature */ || - container.kind === 144 /* Constructor */; + return container.kind === 145 /* MethodDeclaration */ || + container.kind === 144 /* MethodSignature */ || + container.kind === 147 /* GetAccessor */ || + container.kind === 148 /* SetAccessor */ || + container.kind === 143 /* PropertyDeclaration */ || + container.kind === 142 /* PropertySignature */ || + container.kind === 146 /* Constructor */; } } } @@ -20001,7 +21790,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 138 /* Parameter */) { + if (declaration.kind === 140 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -20034,7 +21823,7 @@ var ts; } function isInParameterInitializerBeforeContainingFunction(node) { while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 138 /* Parameter */ && node.parent.initializer === node) { + if (node.parent.kind === 140 /* Parameter */ && node.parent.initializer === node) { return true; } node = node.parent; @@ -20045,8 +21834,8 @@ var ts; // 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 === 144 /* Constructor */ || - functionDecl.kind === 145 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 146 /* SetAccessor */))) { + functionDecl.kind === 146 /* Constructor */ || + functionDecl.kind === 147 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 148 /* SetAccessor */))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature @@ -20068,7 +21857,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 170 /* TaggedTemplateExpression */) { + if (template.parent.kind === 174 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -20091,6 +21880,11 @@ var ts; } return type; } + else if (operator === 51 /* AmpersandAmpersandToken */ || operator === 24 /* CommaToken */) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } return undefined; } // Apply a mapping function to a contextual type and return the resulting type. If the contextual type @@ -20103,8 +21897,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var current = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -20129,14 +21923,13 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } + function contextualTypeIsStringLiteralType(type) { + return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); + } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } - // Return true if the given contextual type provides an index signature of the given kind - function contextualTypeHasIndexSignature(type, kind) { - return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, function (t) { return getIndexTypeOfStructuredType(t, kind); }) : getIndexTypeOfStructuredType(type, kind)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -20150,7 +21943,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element) { var objectLiteral = element.parent; - var type = getContextualType(objectLiteral); + var type = getApparentTypeOfContextualType(objectLiteral); if (type) { if (!ts.hasDynamicName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name @@ -20173,7 +21966,7 @@ var ts; // type of T. function getContextualTypeForElementExpression(node) { var arrayLiteral = node.parent; - var type = getContextualType(arrayLiteral); + var type = getApparentTypeOfContextualType(arrayLiteral); if (type) { var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) @@ -20187,30 +21980,45 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForJsxExpression(expr) { - // Contextual type only applies to JSX expressions that are in attribute assignments (not in 'Children' positions) - if (expr.parent.kind === 238 /* JsxAttribute */) { - var attrib = expr.parent; - var attrsType = getJsxElementAttributesType(attrib.parent); + function getContextualTypeForJsxAttribute(attribute) { + var kind = attribute.kind; + var jsxElement = attribute.parent; + var attrsType = getJsxElementAttributesType(jsxElement); + if (attribute.kind === 242 /* JsxAttribute */) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } - else { - return getTypeOfPropertyOfType(attrsType, attrib.name.text); - } + return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - if (expr.kind === 239 /* JsxSpreadAttribute */) { - return getJsxElementAttributesType(expr.parent); + else if (attribute.kind === 243 /* JsxSpreadAttribute */) { + return attrsType; } - return undefined; + ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. - function getContextualType(node) { - var type = getContextualTypeWorker(node); + function getApparentTypeOfContextualType(node) { + var type = getContextualType(node); return type && getApparentType(type); } - function getContextualTypeWorker(node) { + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node) { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; @@ -20220,39 +22028,41 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 211 /* VariableDeclaration */: - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 163 /* BindingElement */: + case 215 /* VariableDeclaration */: + case 140 /* Parameter */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 167 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 174 /* ArrowFunction */: - case 204 /* ReturnStatement */: + case 178 /* ArrowFunction */: + case 208 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 184 /* YieldExpression */: + case 188 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 175 /* TypeAssertionExpression */: + case 193 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 245 /* PropertyAssignment */: + case 249 /* PropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 190 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 183 /* TemplateExpression */); + case 194 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 187 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return getContextualType(parent); - case 240 /* JsxExpression */: - case 239 /* JsxSpreadAttribute */: - return getContextualTypeForJsxExpression(parent); + case 244 /* JsxExpression */: + return getContextualType(parent); + case 242 /* JsxAttribute */: + case 243 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); } return undefined; } @@ -20268,7 +22078,7 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 173 /* FunctionExpression */ || node.kind === 174 /* ArrowFunction */; + return node.kind === 177 /* FunctionExpression */ || node.kind === 178 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -20282,10 +22092,10 @@ 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 !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var type = ts.isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) - : getContextualType(node); + : getApparentTypeOfContextualType(node); if (!type) { return undefined; } @@ -20294,15 +22104,15 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature signatureList = [signature]; } - else if (!compareSignatures(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypes)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { // Signatures aren't identical, do not use return undefined; } @@ -20345,13 +22155,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 === 181 /* BinaryExpression */ && parent.operatorToken.kind === 56 /* EqualsToken */ && parent.left === node) { + if (parent.kind === 185 /* BinaryExpression */ && parent.operatorToken.kind === 56 /* EqualsToken */ && parent.left === node) { return true; } - if (parent.kind === 245 /* PropertyAssignment */) { + if (parent.kind === 249 /* PropertyAssignment */) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 164 /* ArrayLiteralExpression */) { + if (parent.kind === 168 /* ArrayLiteralExpression */) { return isAssignmentTarget(parent); } return false; @@ -20367,8 +22177,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } function hasDefaultValue(node) { - return (node.kind === 163 /* BindingElement */ && !!node.initializer) || - (node.kind === 181 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); + return (node.kind === 167 /* BindingElement */ && !!node.initializer) || + (node.kind === 185 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -20377,7 +22187,7 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 185 /* SpreadElementExpression */) { + if (inDestructuringPattern && e.kind === 189 /* SpreadElementExpression */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -20401,7 +22211,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 185 /* SpreadElementExpression */; + hasSpreadElement = hasSpreadElement || e.kind === 189 /* SpreadElementExpression */; } if (!hasSpreadElement) { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such @@ -20411,12 +22221,12 @@ var ts; type.pattern = node; return type; } - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { var pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 162 /* ArrayBindingPattern */ || pattern.kind === 164 /* ArrayLiteralExpression */)) { + if (pattern && (pattern.kind === 166 /* ArrayBindingPattern */ || pattern.kind === 168 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -20424,7 +22234,7 @@ var ts; elementTypes.push(contextualType.elementTypes[i]); } else { - if (patternElement.kind !== 187 /* OmittedExpression */) { + if (patternElement.kind !== 191 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -20439,7 +22249,7 @@ var ts; return createArrayType(elementTypes.length ? getUnionType(elementTypes) : undefinedType); } function isNumericName(name) { - return name.kind === 136 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 138 /* 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, @@ -20447,7 +22257,7 @@ var ts; return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); + return isTypeAny(type) || isTypeOfKind(type, kind); } function isNumericLiteralName(name) { // The intent of numeric names is that @@ -20488,31 +22298,44 @@ var ts; } return links.resolvedType; } + function getObjectLiteralIndexInfo(node, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 /* String */ || isNumericName(node.properties[i].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); + } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = {}; var propertiesArray = []; - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 161 /* ObjectBindingPattern */ || contextualType.pattern.kind === 165 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 165 /* ObjectBindingPattern */ || contextualType.pattern.kind === 169 /* ObjectLiteralExpression */); var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 245 /* PropertyAssignment */ || - memberDecl.kind === 246 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 249 /* PropertyAssignment */ || + memberDecl.kind === 250 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 245 /* PropertyAssignment */) { + if (memberDecl.kind === 249 /* PropertyAssignment */) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 143 /* MethodDeclaration */) { + else if (memberDecl.kind === 145 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 246 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 250 /* ShorthandPropertyAssignment */); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -20520,13 +22343,16 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 245 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 246 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 249 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 250 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912 /* Optional */; } + if (ts.hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } } - else if (contextualTypeHasPattern) { + else if (contextualTypeHasPattern && !(contextualType.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); @@ -20552,10 +22378,18 @@ 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 === 145 /* GetAccessor */ || memberDecl.kind === 146 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 147 /* GetAccessor */ || memberDecl.kind === 148 /* SetAccessor */); checkAccessorDeclaration(memberDecl); } - if (!ts.hasDynamicName(memberDecl)) { + if (ts.hasDynamicName(memberDecl)) { + if (isNumericName(memberDecl.name)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + } + else { propertiesTable[member.name] = member; } propertiesArray.push(member); @@ -20574,74 +22408,36 @@ var ts; } } } - var stringIndexType = getIndexType(0 /* String */); - var numberIndexType = getIndexType(1 /* Number */); - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshObjectLiteral */; - result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); + result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */) | (patternWithComputedProperties ? 67108864 /* ObjectLiteralPatternWithComputedProperties */ : 0); if (inDestructuringPattern) { result.pattern = node; } return result; - function getIndexType(kind) { - if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { - var propTypes = []; - for (var i = 0; i < propertiesArray.length; i++) { - var propertyDecl = node.properties[i]; - if (kind === 0 /* String */ || isNumericName(propertyDecl.name)) { - // Do not call getSymbolOfNode(propertyDecl), as that will get the - // original symbol for the node. We actually want to get the symbol - // created by checkObjectLiteral, since that will be appropriately - // contextually typed and resolved. - var type = getTypeOfSymbol(propertiesArray[i]); - if (!ts.contains(propTypes, type)) { - propTypes.push(type); - } - } - } - var result_1 = propTypes.length ? getUnionType(propTypes) : undefinedType; - typeFlags |= result_1.flags; - return result_1; - } - return undefined; - } } function checkJsxSelfClosingElement(node) { checkJsxOpeningLikeElement(node); return jsxElementType || anyType; } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 69 /* Identifier */) { - return lhs.text === rhs.text; - } - return lhs.right.text === rhs.right.text && - tagNamesAreEquivalent(lhs.left, rhs.left); - } function checkJsxElement(node) { // Check attributes checkJsxOpeningLikeElement(node.openingElement); - // Check that the closing tag matches - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - error(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNode(node.openingElement.tagName)); - } - else { - // Perform resolution on the closing tag so that rename/go to definition/etc work - getJsxElementTagSymbol(node.closingElement); - } + // Perform resolution on the closing tag so that rename/go to definition/etc work + getJsxTagSymbol(node.closingElement); // Check children for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 240 /* JsxExpression */: + case 244 /* JsxExpression */: checkJsxExpression(child); break; - case 233 /* JsxElement */: + case 237 /* JsxElement */: checkJsxElement(child); break; - case 234 /* JsxSelfClosingElement */: + case 238 /* JsxSelfClosingElement */: checkJsxSelfClosingElement(child); break; } @@ -20659,7 +22455,7 @@ var ts; * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name */ function isJsxIntrinsicIdentifier(tagName) { - if (tagName.kind === 135 /* QualifiedName */) { + if (tagName.kind === 137 /* QualifiedName */) { return false; } else { @@ -20723,77 +22519,55 @@ var ts; } return type; } - /// Returns the type JSX.IntrinsicElements. May return `unknownType` if that type is not present. - function getJsxIntrinsicElementsType() { - if (!jsxIntrinsicElementsType) { - jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType; + function getJsxType(name) { + if (jsxTypes[name] === undefined) { + return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType; } - return jsxIntrinsicElementsType; + return jsxTypes[name]; } - /// Given a JSX opening element or self-closing element, return the symbol of the property that the tag name points to if - /// this is an intrinsic tag. This might be a named - /// property of the IntrinsicElements interface, or its string indexer. - /// If this is a class-based tag (otherwise returns undefined), returns the symbol of the class - /// type or factory function. - /// Otherwise, returns unknownSymbol. - function getJsxElementTagSymbol(node) { - var flags = 8 /* UnknownElement */; + function getJsxTagSymbol(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicTagSymbol(node); + } + else { + return checkExpression(node.tagName).symbol; + } + } + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - links.resolvedSymbol = lookupIntrinsicTag(node); - } - else { - links.resolvedSymbol = lookupClassTag(node); - } - } - return links.resolvedSymbol; - function lookupIntrinsicTag(node) { - var intrinsicElementsType = getJsxIntrinsicElementsType(); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { // Property case var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); if (intrinsicProp) { links.jsxFlags |= 1 /* IntrinsicNamedElement */; - return intrinsicProp; + return links.resolvedSymbol = intrinsicProp; } // Intrinsic string indexer case var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); if (indexSignatureType) { links.jsxFlags |= 2 /* IntrinsicIndexedElement */; - return intrinsicElementsType.symbol; + return links.resolvedSymbol = intrinsicElementsType.symbol; } // Wasn't found error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.tagName.text, "JSX." + JsxNames.IntrinsicElements); - return unknownSymbol; + return links.resolvedSymbol = unknownSymbol; } else { if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); } + return links.resolvedSymbol = unknownSymbol; } } - function lookupClassTag(node) { - var valueSymbol = resolveJsxTagName(node); - // Look up the value in the current scope - if (valueSymbol && valueSymbol !== unknownSymbol) { - links.jsxFlags |= 4 /* ClassElement */; - if (valueSymbol.flags & 8388608 /* Alias */) { - markAliasSymbolAsReferenced(valueSymbol); - } - } - return valueSymbol || unknownSymbol; - } - function resolveJsxTagName(node) { - if (node.tagName.kind === 69 /* Identifier */) { - var tag = node.tagName; - var sym = getResolvedSymbol(tag); - return sym.exportSymbol || sym; - } - else { - return checkQualifiedName(node.tagName).symbol; - } - } + return links.resolvedSymbol; } /** * Given a JSX element that is a class element, finds the Element Instance Type. If the @@ -20801,15 +22575,7 @@ var ts; * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node) { - // There is no such thing as an instance type for a non-class element. This - // line shouldn't be hit. - ts.Debug.assert(!!(getNodeLinks(node).jsxFlags & 4 /* ClassElement */), "Should not call getJsxElementInstanceType on non-class Element"); - var classSymbol = getJsxElementTagSymbol(node); - if (classSymbol === unknownSymbol) { - // Couldn't find the class instance type. Error has already been issued - return anyType; - } - var valueType = getTypeOfSymbol(classSymbol); + var valueType = checkExpression(node.tagName); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -20825,19 +22591,13 @@ var ts; return unknownType; } } - var returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); - // Issue an error if this return type isn't assignable to JSX.ElementClass - var elemClassType = getJsxGlobalElementClassType(); - if (elemClassType) { - checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - return returnType; + return getUnionType(signatures.map(getReturnTypeOfSignature)); } /// e.g. "props" for React.d.ts, - /// or 'undefined' if ElementAttributesPropery doesn't exist (which means all + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all /// non-intrinsic elements' attributes type is 'any'), /// or '' if it has 0 properties (which means every - /// non-instrinsic elements' attributes type is the element instance type) + /// non-intrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { // JSX var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); @@ -20845,7 +22605,7 @@ var ts; var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056 /* Type */); // JSX.ElementAttributesProperty [type] var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); - // The properites of JSX.ElementAttributesProperty + // The properties of JSX.ElementAttributesProperty var attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { // Element Attributes has zero properties, so the element attributes type will be the class instance type @@ -20872,9 +22632,40 @@ var ts; function getJsxElementAttributesType(node) { var links = getNodeLinks(node); if (!links.resolvedJsxType) { - var sym = getJsxElementTagSymbol(node); - if (links.jsxFlags & 4 /* ClassElement */) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; + } + } + else { + // Get the element instance type (the result of newing or invoking this tag) var elemInstanceType = getJsxElementInstanceType(node); + var elemClassType = getJsxGlobalElementClassType(); + if (!elemClassType || !isTypeAssignableTo(elemInstanceType, elemClassType)) { + // Is this is a stateless function component? See if its single signature's return type is + // assignable to the JSX Element Type + var elemType = checkExpression(node.tagName); + var callSignatures = elemType && getSignaturesOfType(elemType, 0 /* Call */); + var callSignature = callSignatures && callSignatures.length > 0 && callSignatures[0]; + var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); + var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) { + // Intersect in JSX.IntrinsicAttributes if it exists + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return links.resolvedJsxType = paramType; + } + } + // Issue an error if this return type isn't assignable to JSX.ElementClass + if (elemClassType) { + checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } @@ -20894,27 +22685,38 @@ var ts; return links.resolvedJsxType = emptyObjectType; } else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + // Props is of type 'any' or unknown return links.resolvedJsxType = attributesType; } - else if (!(attributesType.flags & 80896 /* ObjectType */)) { - error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType)); + else if (attributesType.flags & 16384 /* Union */) { + // Props cannot be a union type + error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return links.resolvedJsxType = anyType; } else { - return links.resolvedJsxType = attributesType; + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return links.resolvedJsxType = apparentAttributesType; } } } - else if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { - return links.resolvedJsxType = getTypeOfSymbol(sym); - } - else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { - return links.resolvedJsxType = getIndexTypeOfSymbol(sym, 0 /* String */); - } - else { - // Resolution failed, so we don't know - return links.resolvedJsxType = anyType; - } + return links.resolvedJsxType = unknownType; } return links.resolvedJsxType; } @@ -20936,7 +22738,7 @@ var ts; } /// Returns all the properties of the Jsx.IntrinsicElements interface function getJsxIntrinsicTagNames() { - var intrinsics = getJsxIntrinsicElementsType(); + var intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } function checkJsxPreconditions(errorNode) { @@ -20953,14 +22755,13 @@ var ts; function checkJsxOpeningLikeElement(node) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - // If we're compiling under --jsx react, the symbol 'React' should - // be marked as 'used' so we don't incorrectly elide its import. And if there - // is no 'React' symbol in scope, we should issue an error. - if (compilerOptions.jsx === 2 /* React */) { - var reactSym = resolveName(node.tagName, "React", 107455 /* Value */, ts.Diagnostics.Cannot_find_name_0, "React"); - if (reactSym) { - getSymbolLinks(reactSym).referenced = true; - } + // The reactNamespace symbol should be marked as 'used' so we don't incorrectly elide its import. And if there + // is no reactNamespace symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = {}; @@ -20969,11 +22770,11 @@ var ts; // thus should have their types ignored var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 238 /* JsxAttribute */) { + if (node.attributes[i].kind === 242 /* JsxAttribute */) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 239 /* JsxSpreadAttribute */); + ts.Debug.assert(node.attributes[i].kind === 243 /* JsxSpreadAttribute */); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -21003,10 +22804,10 @@ 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 : 141 /* PropertyDeclaration */; + return s.valueDeclaration ? s.valueDeclaration.kind : 143 /* PropertyDeclaration */; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 8 /* Public */ | 64 /* Static */ : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0; } /** * Check whether the requested property access is valid. @@ -21018,9 +22819,9 @@ var ts; */ function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationFlagsFromSymbol(prop); - var declaringClass = getDeclaredTypeOfSymbol(prop.parent); + var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); if (left.kind === 95 /* SuperKeyword */) { - var errorNode = node.kind === 166 /* PropertyAccessExpression */ ? + var errorNode = node.kind === 170 /* PropertyAccessExpression */ ? node.name : node.right; // TS 1.0 spec (April 2014): 4.8.2 @@ -21030,7 +22831,7 @@ var ts; // - 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 (getDeclarationKindFromSymbol(prop) !== 143 /* MethodDeclaration */) { + if (languageVersion < 2 /* ES6 */ && getDeclarationKindFromSymbol(prop) !== 145 /* MethodDeclaration */) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); @@ -21046,7 +22847,7 @@ var ts; } } // Public properties are otherwise accessible. - if (!(flags & (16 /* Private */ | 32 /* Protected */))) { + if (!(flags & (8 /* Private */ | 16 /* Protected */))) { return true; } // Property is known to be private or protected at this point @@ -21054,7 +22855,7 @@ var ts; var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; // Private property is accessible if declaring and enclosing class are the same - if (flags & 16 /* Private */) { + if (flags & 8 /* Private */) { if (declaringClass !== enclosingClass) { error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; @@ -21072,7 +22873,7 @@ var ts; return false; } // No further restrictions for static properties - if (flags & 64 /* Static */) { + if (flags & 32 /* Static */) { return true; } // An instance property must be accessed through an instance of the enclosing class @@ -21117,7 +22918,7 @@ var ts; return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 166 /* PropertyAccessExpression */ + var left = node.kind === 170 /* PropertyAccessExpression */ ? node.expression : node.left; var type = checkExpression(left); @@ -21129,11 +22930,58 @@ var ts; } return true; } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 216 /* VariableDeclarationList */) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 69 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return undefined; + } + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); + } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr) { + var e = skipParenthesizedNodes(expr); + if (e.kind === 69 /* Identifier */) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 204 /* ForInStatement */ && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(checkExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } function checkIndexedAccess(node) { // Grammar checking if (!node.argumentExpression) { - var sourceFile = getSourceFile(node); - if (node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 173 /* 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); @@ -21182,20 +23030,24 @@ var ts; // Check for compatible indexer types. if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { // Try to use a number indexer. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */)) { - var numberIndexType = getIndexTypeOfType(objectType, 1 /* Number */); - if (numberIndexType) { - return numberIndexType; + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + var numberIndexInfo = getIndexInfoOfType(objectType, 1 /* Number */); + if (numberIndexInfo) { + getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; + return numberIndexInfo.type; } } // Try to use string indexing. - var stringIndexType = getIndexTypeOfType(objectType, 0 /* String */); - if (stringIndexType) { - return stringIndexType; + var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */); + if (stringIndexInfo) { + getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; + return stringIndexInfo.type; } // Fall back to any. if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); + error(node, getIndexTypeOfType(objectType, 1 /* Number */) ? + ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : + ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } return anyType; } @@ -21214,7 +23066,7 @@ var ts; if (indexArgumentExpression.kind === 9 /* StringLiteral */ || indexArgumentExpression.kind === 8 /* NumericLiteral */) { return indexArgumentExpression.text; } - if (indexArgumentExpression.kind === 167 /* ElementAccessExpression */ || indexArgumentExpression.kind === 166 /* PropertyAccessExpression */) { + if (indexArgumentExpression.kind === 171 /* ElementAccessExpression */ || indexArgumentExpression.kind === 170 /* PropertyAccessExpression */) { var value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); @@ -21269,10 +23121,10 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 174 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 139 /* Decorator */) { + else if (node.kind !== 141 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -21289,7 +23141,7 @@ var ts; // so order how inherited signatures are processed is still preserved. // interface A { (x: string): void } // interface B extends A { (x: 'foo'): string } - // let b: B; + // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] function reorderCandidates(signatures, result) { var lastParent; @@ -21302,13 +23154,13 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_5 = signature.declaration && signature.declaration.parent; + var parent_6 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_5 === lastParent) { + if (lastParent && parent_6 === lastParent) { index++; } else { - lastParent = parent_5; + lastParent = parent_6; index = cutoffIndex; } } @@ -21316,7 +23168,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_5; + lastParent = parent_6; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -21338,7 +23190,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 185 /* SpreadElementExpression */) { + if (arg && arg.kind === 189 /* SpreadElementExpression */) { return i; } } @@ -21350,13 +23202,13 @@ var ts; var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments var isDecorator; var spreadArgIndex = -1; - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 174 /* 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 === 183 /* TemplateExpression */) { + if (tagExpression.template.kind === 187 /* 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; @@ -21373,7 +23225,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 139 /* Decorator */) { + else if (node.kind === 141 /* Decorator */) { isDecorator = true; typeArguments = undefined; adjustedArgCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); @@ -21382,7 +23234,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 === 169 /* NewExpression */); + ts.Debug.assert(callExpression.kind === 173 /* NewExpression */); return signature.minArgumentCount === 0; } // For IDE scenarios we may have an incomplete call, so a trailing comma is tantamount to adding another argument. @@ -21417,7 +23269,7 @@ var ts; if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && - resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) { + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { return resolved.callSignatures[0]; } } @@ -21434,7 +23286,7 @@ var ts; } function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; - var inferenceMapper = createInferenceMapper(context); + var inferenceMapper = getInferenceMapper(context); // Clear out all the inference results from the last time inferTypeArguments was called on this context for (var i = 0; i < typeParameters.length; i++) { // As an optimization, we don't have to clear (and later recompute) inferred types @@ -21461,7 +23313,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 187 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 191 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); // If the effective argument type is 'undefined', there is no synthetic type @@ -21482,7 +23334,7 @@ var ts; // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. if (excludeArgument) { for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exlusion value is always undefined + // No need to check for omitted args and template expressions, their exclusion value is always undefined if (excludeArgument[i] === false) { var arg = args[i]; var paramType = getTypeAtPosition(signature, i); @@ -21492,14 +23344,11 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; + var mapper; for (var i = 0; i < typeParameters.length; i++) { - var typeArgNode = typeArguments[i]; - var typeArgument = getTypeFromTypeNode(typeArgNode); - // Do not push on this array! It has a preallocated length - typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable /* so far */) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { @@ -21509,7 +23358,11 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); typeArgumentHeadMessage = headMessage; } - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); } } } @@ -21520,7 +23373,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 187 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 191 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); @@ -21528,7 +23381,7 @@ var ts; // for the argument. In that case, we should check the argument. if (argType === undefined) { argType = arg.kind === 9 /* StringLiteral */ && !reportErrors - ? getStringLiteralType(arg) + ? getStringLiteralTypeForText(arg.text) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } // Use argument expression as error location when reporting errors @@ -21552,16 +23405,16 @@ var ts; */ function getEffectiveCallArguments(node) { var args; - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 174 /* TaggedTemplateExpression */) { var template = node.template; args = [undefined]; - if (template.kind === 183 /* TemplateExpression */) { + if (template.kind === 187 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } - else if (node.kind === 139 /* Decorator */) { + else if (node.kind === 141 /* Decorator */) { // For a decorator, we return undefined as we will determine // the number and types of arguments for a decorator using // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. @@ -21586,19 +23439,19 @@ var ts; * Otherwise, the argument count is the length of the 'args' array. */ function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 139 /* Decorator */) { + if (node.kind === 141 /* Decorator */) { switch (node.parent.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; - case 141 /* PropertyDeclaration */: + case 143 /* PropertyDeclaration */: // A property declaration decorator will have two arguments (see // `PropertyDecorator` in core.d.ts) return 2; - case 143 /* MethodDeclaration */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts) // If we are emitting decorators for ES3, we will only pass two arguments. @@ -21608,7 +23461,7 @@ var ts; // If the method decorator signature only accepts a target and a key, we will only // type check those arguments. return signature.parameters.length >= 3 ? 3 : 2; - case 138 /* Parameter */: + case 140 /* Parameter */: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; @@ -21632,25 +23485,25 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 138 /* Parameter */) { + if (node.kind === 140 /* Parameter */) { // For a parameter decorator, the `target` is the parent type of the // parameter's containing method. node = node.parent; - if (node.kind === 144 /* Constructor */) { + if (node.kind === 146 /* Constructor */) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 141 /* PropertyDeclaration */ || - node.kind === 143 /* MethodDeclaration */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */) { + if (node.kind === 143 /* PropertyDeclaration */ || + node.kind === 145 /* MethodDeclaration */ || + node.kind === 147 /* GetAccessor */ || + node.kind === 148 /* SetAccessor */) { // For a property or method decorator, the `target` is the // "static"-side type of the parent of the member if the member is // declared "static"; otherwise, it is the "instance"-side type of the @@ -21677,21 +23530,21 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 138 /* Parameter */) { + if (node.kind === 140 /* Parameter */) { node = node.parent; - if (node.kind === 144 /* Constructor */) { + if (node.kind === 146 /* Constructor */) { // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } } - if (node.kind === 141 /* PropertyDeclaration */ || - node.kind === 143 /* MethodDeclaration */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */) { + if (node.kind === 143 /* PropertyDeclaration */ || + node.kind === 145 /* MethodDeclaration */ || + node.kind === 147 /* GetAccessor */ || + node.kind === 148 /* SetAccessor */) { // The `propertyKey` for a property or method decorator will be a // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will @@ -21701,10 +23554,10 @@ var ts; case 69 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getStringLiteralType(element.name); - case 136 /* ComputedPropertyName */: + return getStringLiteralTypeForText(element.name.text); + case 138 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (allConstituentTypesHaveKind(nameType, 16777216 /* ESSymbol */)) { + if (isTypeOfKind(nameType, 16777216 /* ESSymbol */)) { return nameType; } else { @@ -21727,22 +23580,22 @@ var ts; */ function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a paramter decorator - if (node.kind === 214 /* ClassDeclaration */) { + // or its `parameterIndex` for a parameter decorator + if (node.kind === 218 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 138 /* Parameter */) { + if (node.kind === 140 /* Parameter */) { // The `parameterIndex` for a parameter decorator is always a number return numberType; } - if (node.kind === 141 /* PropertyDeclaration */) { + if (node.kind === 143 /* PropertyDeclaration */) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 143 /* MethodDeclaration */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */) { + if (node.kind === 145 /* MethodDeclaration */ || + node.kind === 147 /* GetAccessor */ || + node.kind === 148 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. var propertyType = getTypeOfNode(node); @@ -21774,10 +23627,10 @@ var ts; // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors - if (node.kind === 139 /* Decorator */) { + if (node.kind === 141 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 174 /* TaggedTemplateExpression */) { return globalTemplateStringsArrayType; } // This is not a synthetic argument, so we return 'undefined' @@ -21789,8 +23642,8 @@ var ts; */ function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 139 /* Decorator */ || - (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */)) { + if (node.kind === 141 /* Decorator */ || + (argIndex === 0 && node.kind === 174 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -21799,11 +23652,11 @@ var ts; * Gets the error node to use when reporting errors for an effective argument. */ function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 139 /* Decorator */) { + if (node.kind === 141 /* Decorator */) { // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 174 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -21812,8 +23665,8 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 170 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 139 /* Decorator */; + var isTaggedTemplate = node.kind === 174 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 141 /* Decorator */; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; @@ -21919,7 +23772,8 @@ var ts; } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], /*reportErrors*/ true, headMessage); + var typeArguments_2 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -21977,7 +23831,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -22031,8 +23885,10 @@ var ts; // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated // with the type arguments specified in the extends clause. var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); - var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); - return resolveCall(node, baseConstructors, candidatesOutArray); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); + } } return resolveUntypedCall(node); } @@ -22056,7 +23912,7 @@ var ts; // We exclude union types because we may have a union of function types that happen to have // no common signatures. 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 + // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); @@ -22119,6 +23975,9 @@ var ts; // that the user will not add any. var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } return resolveCall(node, constructSignatures, candidatesOutArray); } // If expressionType's apparent type is an object type with no construct signatures but @@ -22136,6 +23995,30 @@ var ts; error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); return resolveErrorCall(node); } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var flags = declaration.flags; + // Public constructor is accessible. + if (!(flags & (8 /* Private */ | 16 /* Protected */))) { + return true; + } + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + // A private or protected constructor can only be instantiated within it's own class + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + if (flags & 8 /* Private */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (flags & 16 /* Protected */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -22158,16 +24041,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 138 /* Parameter */: + case 140 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 141 /* PropertyDeclaration */: + case 143 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 143 /* MethodDeclaration */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -22186,7 +24069,7 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo; + var errorInfo = void 0; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); @@ -22204,16 +24087,16 @@ var ts; // to correctly fill the candidatesOutArray. if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 168 /* CallExpression */) { + if (node.kind === 172 /* CallExpression */) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 169 /* NewExpression */) { + else if (node.kind === 173 /* NewExpression */) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 174 /* TaggedTemplateExpression */) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } - else if (node.kind === 139 /* Decorator */) { + else if (node.kind === 141 /* Decorator */) { links.resolvedSignature = resolveDecorator(node, candidatesOutArray); } else { @@ -22222,6 +24105,13 @@ var ts; } return links.resolvedSignature; } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } /** * Syntactically and semantically checks a call or new expression. * @param node The call/new expression to be checked. @@ -22234,19 +24124,30 @@ var ts; if (node.expression.kind === 95 /* SuperKeyword */) { return voidType; } - if (node.kind === 169 /* NewExpression */) { + if (node.kind === 173 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 144 /* Constructor */ && - declaration.kind !== 148 /* ConstructSignature */ && - declaration.kind !== 153 /* ConstructorType */) { - // When resolved signature is a call signature (and not a construct signature) the result type is any - if (compilerOptions.noImplicitAny) { + declaration.kind !== 146 /* Constructor */ && + declaration.kind !== 150 /* ConstructSignature */ && + declaration.kind !== 155 /* ConstructorType */ && + !ts.isJSDocConstructSignature(declaration)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + var funcSymbol = checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */)) { + return getInferredClassType(funcSymbol); + } + else if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; } } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } return getReturnTypeOfSignature(signature); } function checkTaggedTemplateExpression(node) { @@ -22257,7 +24158,10 @@ var ts; var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); - if (!(isTypeAssignableTo(targetType, widenedType))) { + // Permit 'number[] | "foo"' to be asserted to 'string'. + var bothAreStringLike = maybeTypeOfKind(targetType, 258 /* StringLike */) && + maybeTypeOfKind(widenedType, 258 /* StringLike */); + if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } } @@ -22287,7 +24191,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 191 /* OmittedExpression */) { if (element.name.kind === 69 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -22335,6 +24239,13 @@ var ts; inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); } } + function getReturnTypeFromJSDocComment(func) { + var returnTag = ts.getJSDocReturnTag(func); + if (returnTag && returnTag.typeExpression) { + return getTypeFromTypeNode(returnTag.typeExpression.type); + } + return undefined; + } function createPromiseType(promisedType) { // creates a `Promise` type where `T` is the promisedType argument var globalPromiseType = getGlobalPromiseType(); @@ -22352,7 +24263,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 192 /* Block */) { + if (func.body.kind !== 196 /* Block */) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -22363,7 +24274,7 @@ var ts; } } else { - var types; + var types = void 0; var funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); @@ -22402,7 +24313,8 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience + return getUnionType(types); } } if (funcIsGenerator) { @@ -22465,48 +24377,61 @@ var ts; }); return aggregatedTypes; } - // TypeScript Specification 1.0 (6.3) - July 2014 - // An explicitly typed function whose return type isn't the Void or the Any type - // must have at least one return statement somewhere in its body. - // An exception to this rule is if the function implementation consists of a single 'throw' statement. + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; } - // Functions that return 'void' or 'any' don't need any return expressions. - if (returnType === voidType || isTypeAny(returnType)) { + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - // also if HasImplicitReturnValue flags is not set this means that all codepaths in function body end with return of throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 /* Block */ || !(func.flags & 524288 /* HasImplicitReturn */)) { + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (ts.nodeIsMissing(func.body) || func.body.kind !== 196 /* Block */ || !(func.flags & 32768 /* HasImplicitReturn */)) { return; } - if (func.flags & 1048576 /* HasExplicitReturn */) { - if (compilerOptions.noImplicitReturns) { - error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { - // This function does not conform to the specification. + var hasExplicitReturn = func.flags & 65536 /* HasExplicitReturn */; + if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + var inferredReturnType = hasExplicitReturn + ? getReturnTypeOfSignature(getSignatureFromDeclaration(func)) + : voidType; + if (inferredReturnType === voidType || isTypeAny(inferredReturnType)) { + return; + } + } + error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 173 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 177 /* FunctionExpression */) { checkGrammarForGenerator(node); } // The identityMapper object is used to indicate that function expressions are wildcards if (contextualMapper === identityMapper && isContextSensitive(node)) { return anyFunctionType; } - var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } var links = getNodeLinks(node); var type = getTypeOfSymbol(node.symbol); var contextSensitive = isContextSensitive(node); @@ -22536,28 +24461,23 @@ var ts; } if (!contextChecked) { checkSignatureDeclaration(node); + checkNodeDeferred(node); } } } - if (produceDiagnostics && node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 145 /* MethodDeclaration */ && node.kind !== 144 /* MethodSignature */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } - function checkFunctionExpressionOrObjectLiteralMethodBody(node) { - ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 145 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } - var returnType = node.type && getTypeFromTypeNode(node.type); - var promisedType; - if (returnType && isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - if (returnType && !node.asteriskToken) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + if (!node.asteriskToken) { + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { if (!node.type) { @@ -22568,7 +24488,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 192 /* Block */) { + if (node.body.kind === 196 /* Block */) { checkSourceElement(node.body); } else { @@ -22578,16 +24498,15 @@ var ts; // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. var exprType = checkExpression(node.body); - if (returnType) { + if (returnOrPromisedType) { if (isAsync) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); - checkTypeAssignableTo(awaitedType, promisedType, node.body); + checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } else { - checkTypeAssignableTo(exprType, returnType, node.body); + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } - checkFunctionAndClassExpressionBodies(node.body); } } } @@ -22598,75 +24517,74 @@ var ts; } return true; } - function checkReferenceExpression(n, invalidReferenceMessage, constantVariableMessage) { - function findSymbol(n) { - var symbol = getNodeLinks(n).resolvedSymbol; - // Because we got the symbol from the resolvedSymbol property, it might be of kind - // SymbolFlags.ExportValue. In this case it is necessary to get the actual export - // symbol, which will have the correct flags set on it. - return symbol && getExportSymbolOfValueSymbolIfExported(symbol); + function isReadonlySymbol(symbol) { + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + return symbol.flags & 4 /* Property */ && (getDeclarationFlagsFromSymbol(symbol) & 64 /* Readonly */) !== 0 || + symbol.flags & 3 /* Variable */ && (getDeclarationFlagsFromSymbol(symbol) & 2048 /* Const */) !== 0 || + symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || + (symbol.flags & 8 /* EnumMember */) !== 0; + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & 4 /* Property */ && + (expr.kind === 170 /* PropertyAccessExpression */ || expr.kind === 171 /* ElementAccessExpression */) && + expr.expression.kind === 97 /* ThisKeyword */) { + var func = ts.getContainingFunction(expr); + return !(func && func.kind === 146 /* Constructor */ && func.parent === symbol.valueDeclaration.parent); + } + return true; } - function isReferenceOrErrorExpression(n) { - // TypeScript 1.0 spec (April 2014): - // Expressions are classified as values or references. - // References are the subset of expressions that are permitted as the target of an assignment. - // Specifically, references are combinations of identifiers(section 4.3), parentheses(section 4.7), - // and property accesses(section 4.10). - // All other expression constructs described in this chapter are classified as values. - switch (n.kind) { - case 69 /* Identifier */: { - var symbol = findSymbol(n); - // TypeScript 1.0 spec (April 2014): 4.3 - // An identifier expression that references a variable or parameter is classified as a reference. - // 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; + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 170 /* PropertyAccessExpression */ || expr.kind === 171 /* ElementAccessExpression */) { + var node = skipParenthesizedNodes(expr.expression); + if (node.kind === 69 /* Identifier */) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 8388608 /* Alias */) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return declaration && declaration.kind === 228 /* NamespaceImport */; } - case 166 /* 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 167 /* ElementAccessExpression */: - // old compiler doesn't check indexed access - return true; - case 172 /* ParenthesizedExpression */: - return isReferenceOrErrorExpression(n.expression); - default: - return false; } } - function isConstVariableReference(n) { - switch (n.kind) { - case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: { - var symbol = findSymbol(n); - return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384 /* Const */) !== 0; - } - case 167 /* ElementAccessExpression */: { - var index = n.argumentExpression; - var symbol = findSymbol(n.expression); - if (symbol && index && index.kind === 9 /* StringLiteral */) { - var name_12 = index.text; - var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_12); - return prop && (prop.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 16384 /* Const */) !== 0; - } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage, constantVariableMessage) { + // References are combinations of identifiers, parentheses, and property accesses. + var node = skipParenthesizedNodes(expr); + if (node.kind !== 69 /* Identifier */ && node.kind !== 170 /* PropertyAccessExpression */ && node.kind !== 171 /* ElementAccessExpression */) { + error(expr, invalidReferenceMessage); + return false; + } + // Because we get the symbol from the resolvedSymbol property, it might be of kind + // SymbolFlags.ExportValue. In this case it is necessary to get the actual export + // symbol, which will have the correct flags set on it. + var links = getNodeLinks(node); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol) { + if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { + // Only variables (and not functions, classes, namespaces, enum objects, or enum members) + // are considered references when referenced using a simple identifier. + if (node.kind === 69 /* Identifier */ && !(symbol.flags & 3 /* Variable */)) { + error(expr, invalidReferenceMessage); return false; } - case 172 /* ParenthesizedExpression */: - return isConstVariableReference(n.expression); - default: + if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { + error(expr, constantVariableMessage); return false; + } } } - if (!isReferenceOrErrorExpression(n)) { - error(n, invalidReferenceMessage); - return false; - } - if (isConstVariableReference(n)) { - error(n, constantVariableMessage); - return false; + else if (node.kind === 171 /* ElementAccessExpression */) { + if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { + error(expr, constantVariableMessage); + return false; + } } return true; } @@ -22685,7 +24603,7 @@ var ts; function checkAwaitExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.parserContextFlags & 8 /* Await */)) { + if (!(node.flags & 33554432 /* AwaitContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -22701,7 +24619,7 @@ var ts; case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: - if (someConstituentTypeHasKind(operandType, 16777216 /* ESSymbol */)) { + if (maybeTypeOfKind(operandType, 16777216 /* ESSymbol */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -22712,7 +24630,7 @@ var ts; var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); } return numberType; } @@ -22723,43 +24641,53 @@ var ts; var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); } return numberType; } - // Just like isTypeOfKind below, except that it returns true if *any* constituent - // has this kind. - function someConstituentTypeHasKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 49152 /* UnionOrIntersection */) { - var types = type.types; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var current = types_9[_i]; - if (current.flags & kind) { - return true; - } - } - return false; - } - return false; - } - // Return true if type has the given flags, or is a union or intersection type composed of types that all have those flags. - function allConstituentTypesHaveKind(type, kind) { + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type, kind) { if (type.flags & kind) { return true; } if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var current = types_10[_i]; - if (!(current.flags & kind)) { + var t = types_10[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + // Return true if type is of the given kind. A union type is of a given kind if all constituent types + // are of the given kind. An intersection type is of a given kind if at least one constituent type is + // of the given kind. + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 16384 /* Union */) { + var types = type.types; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + if (!isTypeOfKind(t, kind)) { return false; } } return true; } + if (type.flags & 32768 /* Intersection */) { + var types = type.types; + for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { + var t = types_12[_a]; + if (isTypeOfKind(t, kind)) { + return true; + } + } + } return false; } function isConstEnumObjectType(type) { @@ -22774,7 +24702,7 @@ 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, 16777726 /* Primitive */)) { + if (isTypeOfKind(leftType, 16777726 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported @@ -22800,24 +24728,31 @@ var ts; var properties = node.properties; for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var p = properties_3[_i]; - if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { - // TODO(andersh): Computed property support - var name_13 = p.name; + if (p.kind === 249 /* PropertyAssignment */ || p.kind === 250 /* ShorthandPropertyAssignment */) { + var name_12 = p.name; + if (name_12.kind === 138 /* ComputedPropertyName */) { + checkComputedPropertyName(name_12); + } + if (isComputedNonLiteralName(name_12)) { + continue; + } + var text = getTextOfPropertyName(name_12); var type = isTypeAny(sourceType) ? sourceType - : getTypeOfPropertyOfType(sourceType, name_13.text) || - isNumericLiteralName(name_13.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || + : getTypeOfPropertyOfType(sourceType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); if (type) { - if (p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 250 /* ShorthandPropertyAssignment */) { checkDestructuringAssignment(p, type); } else { - checkDestructuringAssignment(p.initializer || name_13, type); + // non-shorthand property assignments should always have initializers + checkDestructuringAssignment(p.initializer, type); } } else { - error(name_13, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_13)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_12)); } } else { @@ -22834,8 +24769,8 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187 /* OmittedExpression */) { - if (e.kind !== 185 /* SpreadElementExpression */) { + if (e.kind !== 191 /* OmittedExpression */) { + if (e.kind !== 189 /* SpreadElementExpression */) { var propName = "" + i; var type = isTypeAny(sourceType) ? sourceType @@ -22860,7 +24795,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 181 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { + if (restExpression.kind === 185 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -22874,7 +24809,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 246 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 250 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -22884,21 +24819,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + if (target.kind === 185 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 165 /* ObjectLiteralExpression */) { + if (target.kind === 169 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 164 /* ArrayLiteralExpression */) { + if (target.kind === 168 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); } function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant)) { + if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); } return sourceType; @@ -22908,7 +24843,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 /* EqualsToken */ && (left.kind === 165 /* ObjectLiteralExpression */ || left.kind === 164 /* ArrayLiteralExpression */)) { + if (operator === 56 /* EqualsToken */ && (left.kind === 169 /* ObjectLiteralExpression */ || left.kind === 168 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); @@ -22946,7 +24881,7 @@ var ts; leftType = rightType; if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) rightType = leftType; - var suggestedOperator; + var suggestedOperator = void 0; // if a user tries to apply a bitwise operator to 2 boolean operands // try and return them a helpful suggestion if ((leftType.flags & 8 /* Boolean */) && @@ -22973,14 +24908,14 @@ var ts; leftType = rightType; if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) rightType = leftType; - var resultType; - if (allConstituentTypesHaveKind(leftType, 132 /* NumberLike */) && allConstituentTypesHaveKind(rightType, 132 /* NumberLike */)) { + var resultType = void 0; + if (isTypeOfKind(leftType, 132 /* NumberLike */) && isTypeOfKind(rightType, 132 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } else { - if (allConstituentTypesHaveKind(leftType, 258 /* StringLike */) || allConstituentTypesHaveKind(rightType, 258 /* StringLike */)) { + if (isTypeOfKind(leftType, 258 /* StringLike */) || isTypeOfKind(rightType, 258 /* StringLike */)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -23014,6 +24949,10 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: + // Permit 'number[] | "foo"' to be asserted to 'string'. + if (maybeTypeOfKind(leftType, 258 /* StringLike */) && maybeTypeOfKind(rightType, 258 /* StringLike */)) { + return booleanType; + } if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) { reportOperatorError(); } @@ -23034,8 +24973,8 @@ var ts; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 16777216 /* ESSymbol */) ? left : - someConstituentTypeHasKind(rightType, 16777216 /* ESSymbol */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216 /* ESSymbol */) ? left : + maybeTypeOfKind(rightType, 16777216 /* ESSymbol */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -23066,7 +25005,7 @@ var ts; // requires VarExpr to be classified as a reference // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) // and the type of the non - compound operation to be assignable to the type of VarExpr. - var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); // Use default messages if (ok) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported @@ -23096,7 +25035,7 @@ var ts; function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.parserContextFlags & 2 /* Yield */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 8388608 /* YieldContext */) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -23109,7 +25048,7 @@ var ts; // we are in a yield context. if (func && func.asteriskToken) { var expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); - var expressionElementType; + var expressionElementType = void 0; var nodeIsYieldStar = !!node.asteriskToken; if (nodeIsYieldStar) { expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); @@ -23137,6 +25076,13 @@ var ts; var type2 = checkExpression(node.whenFalse, contextualMapper); return getUnionType([type1, type2]); } + function checkStringLiteralExpression(node) { + var contextualType = getContextualType(node); + if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + return getStringLiteralTypeForText(node.text); + } + return stringType; + } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with // the type of each expression, as any value may be coerced into a string. @@ -23166,7 +25112,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 === 136 /* ComputedPropertyName */) { + if (node.name.kind === 138 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpression(node.initializer, contextualMapper); @@ -23177,7 +25123,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 === 136 /* ComputedPropertyName */) { + if (node.name.kind === 138 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -23187,7 +25133,7 @@ var ts; if (isInferentialContext(contextualMapper)) { var signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); if (contextualType) { var contextualSignature = getSingleCallSignature(contextualType); if (contextualSignature && !contextualSignature.typeParameters) { @@ -23207,7 +25153,7 @@ var ts; // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, contextualMapper) { var type; - if (node.kind === 135 /* QualifiedName */) { + if (node.kind === 137 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -23219,9 +25165,9 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 167 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 170 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 171 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 69 /* Identifier */ || node.kind === 137 /* 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); } @@ -23248,65 +25194,66 @@ var ts; return booleanType; case 8 /* NumericLiteral */: return checkNumericLiteral(node); - case 183 /* TemplateExpression */: + case 187 /* TemplateExpression */: return checkTemplateExpression(node); case 9 /* StringLiteral */: + return checkStringLiteralExpression(node); case 11 /* NoSubstitutionTemplateLiteral */: return stringType; case 10 /* RegularExpressionLiteral */: return globalRegExpType; - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return checkArrayLiteral(node, contextualMapper); - case 165 /* ObjectLiteralExpression */: + case 169 /* ObjectLiteralExpression */: return checkObjectLiteral(node, contextualMapper); - case 166 /* PropertyAccessExpression */: + case 170 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 167 /* ElementAccessExpression */: + case 171 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: return checkCallExpression(node); - case 170 /* TaggedTemplateExpression */: + case 174 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return checkExpression(node.expression, contextualMapper); - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: return checkClassExpression(node); - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 176 /* TypeOfExpression */: + case 180 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 175 /* TypeAssertionExpression */: + case 193 /* AsExpression */: return checkAssertion(node); - case 175 /* DeleteExpression */: + case 179 /* DeleteExpression */: return checkDeleteExpression(node); - case 177 /* VoidExpression */: + case 181 /* VoidExpression */: return checkVoidExpression(node); - case 178 /* AwaitExpression */: + case 182 /* AwaitExpression */: return checkAwaitExpression(node); - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 180 /* PostfixUnaryExpression */: + case 184 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return checkBinaryExpression(node, contextualMapper); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 185 /* SpreadElementExpression */: + case 189 /* SpreadElementExpression */: return checkSpreadElementExpression(node, contextualMapper); - case 187 /* OmittedExpression */: + case 191 /* OmittedExpression */: return undefinedType; - case 184 /* YieldExpression */: + case 188 /* YieldExpression */: return checkYieldExpression(node); - case 240 /* JsxExpression */: + case 244 /* JsxExpression */: return checkJsxExpression(node); - case 233 /* JsxElement */: + case 237 /* JsxElement */: return checkJsxElement(node); - case 234 /* JsxSelfClosingElement */: + case 238 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node); - case 235 /* JsxOpeningElement */: + case 239 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -23318,11 +25265,10 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); + getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node))); if (produceDiagnostics) { - checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } - // TODO: Check multiple declarations are identical } function checkParameter(node) { // Grammar checking @@ -23333,9 +25279,9 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 56 /* AccessibilityModifier */) { + if (node.flags & 28 /* AccessibilityModifier */) { func = ts.getContainingFunction(node); - if (!(func.kind === 144 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 146 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -23352,9 +25298,9 @@ var ts; if (!node.asteriskToken || !node.body) { return false; } - return node.kind === 143 /* MethodDeclaration */ || - node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */; + return node.kind === 145 /* MethodDeclaration */ || + node.kind === 217 /* FunctionDeclaration */ || + node.kind === 177 /* FunctionExpression */; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { @@ -23368,91 +25314,100 @@ var ts; } return -1; } - function isInLegalTypePredicatePosition(node) { + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name_13 = _a[_i].name; + if (ts.isBindingPattern(name_13) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_13, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { switch (node.parent.kind) { - case 174 /* ArrowFunction */: - case 147 /* CallSignature */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 152 /* FunctionType */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - return node === node.parent.type; + case 178 /* ArrowFunction */: + case 149 /* CallSignature */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 154 /* FunctionType */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + var parent_7 = node.parent; + if (node === parent_7.type) { + return parent_7; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var name_14 = _a[_i].name; + if (name_14.kind === 69 /* Identifier */ && + name_14.text === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name_14.kind === 166 /* ArrayBindingPattern */ || + name_14.kind === 165 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_14, predicateVariableNode, predicateVariableName)) { + return true; + } + } } - return false; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 149 /* IndexSignature */) { + if (node.kind === 151 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 152 /* FunctionType */ || node.kind === 213 /* FunctionDeclaration */ || node.kind === 153 /* ConstructorType */ || - node.kind === 147 /* CallSignature */ || node.kind === 144 /* Constructor */ || - node.kind === 148 /* ConstructSignature */) { + else if (node.kind === 154 /* FunctionType */ || node.kind === 217 /* FunctionDeclaration */ || node.kind === 155 /* ConstructorType */ || + node.kind === 149 /* CallSignature */ || node.kind === 146 /* Constructor */ || + node.kind === 150 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { - if (node.type.kind === 150 /* 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, getTypeOfNode(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 === 161 /* ObjectBindingPattern */ || - param.name.kind === 162 /* ArrayBindingPattern */) { - (function checkBindingPattern(pattern) { - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (element.name.kind === 69 /* 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 === 162 /* ArrayBindingPattern */ || - element.name.kind === 161 /* 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); - } + checkSourceElement(node.type); } if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 148 /* ConstructSignature */: + case 150 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 147 /* CallSignature */: + case 149 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -23475,12 +25430,14 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } + else if (ts.isAsyncFunctionLike(node)) { + checkAsyncFunctionReturnType(node); + } } } - checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 215 /* InterfaceDeclaration */) { + if (node.kind === 219 /* 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 @@ -23500,7 +25457,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 130 /* StringKeyword */: + case 131 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -23508,7 +25465,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 128 /* NumberKeyword */: + case 129 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -23530,7 +25487,7 @@ var ts; // Grammar checking checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration - checkFunctionLikeDeclaration(node); + checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. if (node.flags & 128 /* Abstract */ && node.body) { @@ -23540,7 +25497,7 @@ var ts; function checkConstructorDeclaration(node) { // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. checkSignatureDeclaration(node); - // Grammar check for checking only related to constructoDeclaration + // Grammar check for checking only related to constructorDeclaration checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); var symbol = getSymbolOfNode(node); @@ -23556,14 +25513,11 @@ var ts; if (!produceDiagnostics) { return; } - function isSuperCallExpression(n) { - return n.kind === 168 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; - } function containsSuperCallAsComputedPropertyName(n) { return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (isSuperCallExpression(n)) { + if (ts.isSuperCallExpression(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -23578,13 +25532,13 @@ var ts; if (n.kind === 97 /* ThisKeyword */) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 173 /* FunctionExpression */ && n.kind !== 213 /* FunctionDeclaration */) { + else if (n.kind !== 177 /* FunctionExpression */ && n.kind !== 217 /* FunctionDeclaration */) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 141 /* PropertyDeclaration */ && - !(n.flags & 64 /* Static */) && + return n.kind === 143 /* PropertyDeclaration */ && + !(n.flags & 32 /* Static */) && !!n.initializer; } // TS 1.0 spec (April 2014): 8.3.2 @@ -23592,12 +25546,11 @@ var ts; // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { - var containingClassSymbol = getSymbolOfNode(containingClassDecl); - var containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); - var baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); - if (containsSuperCall(node.body)) { - if (baseConstructorType === nullType) { - error(node, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } // The first statement in the body of a constructor (excluding prologue directives) must be a super call // if both of the following are true: @@ -23605,15 +25558,15 @@ var ts; // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & (8 /* Public */ | 16 /* Private */ | 32 /* Protected */); }); + ts.forEach(node.parameters, function (p) { return p.flags & (4 /* Public */ | 8 /* Private */ | 16 /* Protected */); }); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { var statements = node.body.statements; - var superCallStatement; + var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 195 /* ExpressionStatement */ && isSuperCallExpression(statement.expression)) { + if (statement.kind === 199 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; } @@ -23624,13 +25577,9 @@ var ts; if (!superCallStatement) { error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); } - else { - // In such a required super call, it is a compile-time error for argument expressions to reference this. - markThisReferencesAsErrors(superCallStatement.expression); - } } } - else if (baseConstructorType !== nullType) { + else if (!classExtendsNull) { error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); } } @@ -23639,9 +25588,11 @@ var ts; if (produceDiagnostics) { // Grammar checking accessors checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (node.kind === 145 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288 /* HasImplicitReturn */)) { - if (node.flags & 1048576 /* HasExplicitReturn */) { + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 147 /* GetAccessor */) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768 /* HasImplicitReturn */)) { + if (node.flags & 65536 /* HasExplicitReturn */) { if (compilerOptions.noImplicitReturns) { error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -23651,15 +25602,24 @@ 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 === 138 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } if (!ts.hasDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 145 /* GetAccessor */ ? 146 /* SetAccessor */ : 145 /* GetAccessor */; + var otherKind = node.kind === 147 /* GetAccessor */ ? 148 /* SetAccessor */ : 147 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 56 /* AccessibilityModifier */) !== (otherAccessor.flags & 56 /* AccessibilityModifier */))) { + if (((node.flags & 28 /* AccessibilityModifier */) !== (otherAccessor.flags & 28 /* AccessibilityModifier */))) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } + if (((node.flags & 128 /* Abstract */) !== (otherAccessor.flags & 128 /* Abstract */))) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } var currentAccessorType = getAnnotatedAccessorType(node); var otherAccessorType = getAnnotatedAccessorType(otherAccessor); // TypeScript 1.0 spec (April 2014): 4.5 @@ -23673,18 +25633,32 @@ var ts; } getTypeOfAccessors(getSymbolOfNode(node)); } - checkFunctionLikeDeclaration(node); + if (node.parent.kind !== 169 /* ObjectLiteralExpression */) { + checkSourceElement(node.body); + } + else { + checkNodeDeferred(node); + } + } + function checkAccessorDeferred(node) { + checkSourceElement(node.body); } function checkMissingDeclaration(node) { checkDecorators(node); } - function checkTypeArgumentConstraints(typeParameters, typeArguments) { + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var typeArguments; + var mapper; var result = true; for (var i = 0; i < typeParameters.length; i++) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { + if (!typeArguments) { + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + mapper = createTypeMapper(typeParameters, typeArguments); + } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -23728,59 +25702,21 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 16 /* Private */) && ts.isInAmbientContext(node); - } - function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { - if (!produceDiagnostics) { - return; - } - var signature = getSignatureFromDeclaration(signatureDeclarationNode); - if (!signature.hasStringLiterals) { - return; - } - // TypeScript 1.0 spec (April 2014): 3.7.2.2 - // Specialized signatures are not permitted in conjunction with a function body - if (ts.nodeIsPresent(signatureDeclarationNode.body)) { - error(signatureDeclarationNode, ts.Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type); - return; - } - // TypeScript 1.0 spec (April 2014): 3.7.2.4 - // Every specialized call or construct signature in an object type must be assignable - // to at least one non-specialized call or construct signature in the same object type - 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 === 215 /* InterfaceDeclaration */) { - ts.Debug.assert(signatureDeclarationNode.kind === 147 /* CallSignature */ || signatureDeclarationNode.kind === 148 /* ConstructSignature */); - var signatureKind = signatureDeclarationNode.kind === 147 /* CallSignature */ ? 0 /* Call */ : 1 /* Construct */; - var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); - var containingType = getDeclaredTypeOfSymbol(containingSymbol); - signaturesToCheck = getSignaturesOfType(containingType, signatureKind); - } - else { - signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); - } - for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { - var otherSignature = signaturesToCheck_1[_i]; - if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { - return; - } - } - error(signatureDeclarationNode, ts.Diagnostics.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature); + return (node.flags & 8 /* Private */) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedNodeFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 215 /* InterfaceDeclaration */ && - n.parent.kind !== 214 /* ClassDeclaration */ && - n.parent.kind !== 186 /* ClassExpression */ && + if (n.parent.kind !== 219 /* InterfaceDeclaration */ && + n.parent.kind !== 218 /* ClassDeclaration */ && + n.parent.kind !== 190 /* ClassExpression */ && ts.isInAmbientContext(n)) { - if (!(flags & 4 /* Ambient */)) { + if (!(flags & 2 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported - flags |= 2 /* Export */; + flags |= 1 /* Export */; } - flags |= 4 /* Ambient */; + flags |= 2 /* Ambient */; } return flags & flagsToCheck; } @@ -23802,36 +25738,36 @@ var ts; // deviations, we XOR someOverloadFlags with allOverloadFlags var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; if (someButNotAllOverloadFlags !== 0) { - var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); ts.forEach(overloads, function (o) { - var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - if (deviation & 2 /* Export */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1 /* Export */) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } - else if (deviation & 4 /* Ambient */) { + else if (deviation & 2 /* Ambient */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (16 /* Private */ | 32 /* Protected */)) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + else if (deviation & (8 /* Private */ | 16 /* Protected */)) { + error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128 /* Abstract */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } } function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { if (someHaveQuestionToken !== allHaveQuestionToken) { - var canonicalHasQuestionToken = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); ts.forEach(overloads, function (o) { - var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken; + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } } - var flagsToCheck = 2 /* Export */ | 4 /* Ambient */ | 16 /* Private */ | 32 /* Protected */ | 128 /* Abstract */; + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; var someNodeFlags = 0; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; @@ -23855,16 +25791,23 @@ var ts; seen = c === node; } }); - if (subsequentNode) { + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - // 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 === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */); - ts.Debug.assert((node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* Static */)); - var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); + var reportError = (node.kind === 145 /* MethodDeclaration */ || node.kind === 144 /* MethodSignature */) && + (node.flags & 32 /* Static */) !== (subsequentNode.flags & 32 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = node.flags & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } return; } else if (ts.nodeIsPresent(subsequentNode.body)) { @@ -23897,7 +25840,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 215 /* InterfaceDeclaration */ || node.parent.kind === 155 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 219 /* InterfaceDeclaration */ || node.parent.kind === 157 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -23908,7 +25851,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 === 213 /* FunctionDeclaration */ || node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */ || node.kind === 144 /* Constructor */) { + if (node.kind === 217 /* FunctionDeclaration */ || node.kind === 145 /* MethodDeclaration */ || node.kind === 144 /* MethodSignature */ || node.kind === 146 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -23960,29 +25903,11 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - // If the implementation signature has string literals, we will have reported an error in - // checkSpecializedSignatureDeclaration - if (!bodySignature.hasStringLiterals) { - // TypeScript 1.0 spec (April 2014): 6.1 - // If a function declaration includes overloads, the overloads determine the call - // signatures of the type given to the function object - // and the function implementation signature must be assignable to that type - // - // TypeScript 1.0 spec (April 2014): 3.8.4 - // Note that specialized call and construct signatures (section 3.7.2.4) are not significant when determining assignment compatibility - // Consider checking against specialized signatures too. Not doing so creates a type hole: - // - // function g(x: "hi", y: boolean); - // function g(x: string, y: {}); - // function g(x: string, y: string) { } - // - // The implementation is completely unrelated to the specialized signature, yet we do not check this. - for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { - var signature = signatures_3[_a]; - if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { - error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); - break; - } + for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { + var signature = signatures_3[_a]; + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; } } } @@ -24015,8 +25940,8 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var d = _a[_i]; var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 2 /* Export */ | 512 /* Default */); - if (effectiveDeclarationFlags & 2 /* Export */) { + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { if (effectiveDeclarationFlags & 512 /* Default */) { defaultExportedDeclarationSpaces |= declarationSpaces; } @@ -24028,7 +25953,7 @@ var ts; nonExportedDeclarationSpaces |= declarationSpaces; } } - // Spaces for anyting not declared a 'default export'. + // Spaces for anything not declared a 'default export'. var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; @@ -24037,7 +25962,7 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); - // Only error on the declarations that conributed to the intersecting spaces. + // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); } @@ -24048,20 +25973,20 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return 2097152 /* ExportType */; - case 218 /* ModuleDeclaration */: - return d.name.kind === 9 /* StringLiteral */ || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + case 222 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ : 4194304 /* ExportNamespace */; - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 221 /* ImportEqualsDeclaration */: - var result = 0; + case 225 /* ImportEqualsDeclaration */: + var result_1 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); - return result; + ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); + return result_1; default: return 1048576 /* ExportValue */; } @@ -24218,6 +26143,33 @@ var ts; } } } + /** + * Checks that the return type provided is an instantiation of the global Promise type + * and returns the awaited type of the return type. + * + * @param returnType The return type of a FunctionLikeDeclaration + * @param location The node on which to report the error. + */ + function checkCorrectPromiseType(returnType, location) { + if (returnType === unknownType) { + // The return type already had some other error, so we ignore and return + // the unknown type. + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType === emptyGenericType + || globalPromiseType === getTargetType(returnType)) { + // Either we couldn't resolve the global promise type, which would have already + // reported an error, or we could resolve it and the return type is a valid type + // reference to the global type. In either case, we return the awaited type for + // the return type. + return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + } + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(location, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } /** * Checks the return type of an async function to ensure it is a compatible * Promise implementation. @@ -24232,6 +26184,10 @@ var ts; * callable `then` signature. */ function checkAsyncFunctionReturnType(node) { + if (languageVersion >= 2 /* ES6 */) { + var returnType = getTypeFromTypeNode(node.type); + return checkCorrectPromiseType(returnType, node.type); + } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify @@ -24278,6 +26234,8 @@ var ts; error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } + // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. + checkReturnTypeAnnotationAsExpression(node); // Validate the promise constructor type. var promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { @@ -24285,10 +26243,10 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var promiseName = ts.getEntityNameFromTypeNode(node.type); - var root = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, root.text, 107455 /* Value */); + var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); + var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455 /* Value */); if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, getFullyQualifiedName(promiseConstructor)); + error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } // Get and return the awaited type of the return type. @@ -24305,22 +26263,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 138 /* Parameter */: + case 140 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 141 /* PropertyDeclaration */: + case 143 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 143 /* MethodDeclaration */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -24333,9 +26291,9 @@ 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 === 151 /* TypeReference */) { + if (node && node.kind === 153 /* TypeReference */) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = root.parent.kind === 153 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; // Resolve type so we know which symbol is referenced var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); // Resolved symbol is alias @@ -24353,23 +26311,10 @@ var ts; * an expression if it is a type reference to a type with a value declaration. */ function checkTypeAnnotationAsExpression(node) { - switch (node.kind) { - case 141 /* PropertyDeclaration */: - checkTypeNodeAsExpression(node.type); - break; - case 138 /* Parameter */: - checkTypeNodeAsExpression(node.type); - break; - case 143 /* MethodDeclaration */: - checkTypeNodeAsExpression(node.type); - break; - case 145 /* GetAccessor */: - checkTypeNodeAsExpression(node.type); - break; - case 146 /* SetAccessor */: - checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node)); - break; - } + checkTypeNodeAsExpression(node.type); + } + function checkReturnTypeAnnotationAsExpression(node) { + checkTypeNodeAsExpression(node.type); } /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ function checkParameterTypeAnnotationsAsExpressions(node) { @@ -24390,53 +26335,48 @@ var ts; 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); + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } 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 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; - case 143 /* MethodDeclaration */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: checkParameterTypeAnnotationsAsExpressions(node); - // fall-through - case 146 /* SetAccessor */: - case 145 /* GetAccessor */: - case 141 /* PropertyDeclaration */: - case 138 /* Parameter */: + checkReturnTypeAnnotationAsExpression(node); + break; + case 143 /* PropertyDeclaration */: + case 140 /* Parameter */: checkTypeAnnotationAsExpression(node); break; } } - emitDecorate = true; - if (node.kind === 138 /* Parameter */) { - emitParam = true; - } ts.forEach(node.decorators, checkDecorator); } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); + checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkFunctionLikeDeclaration(node) { + function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } // 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 === 136 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 138 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -24447,7 +26387,13 @@ var ts; // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.forEach(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)) ? + declaration : undefined; }); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); @@ -24461,13 +26407,9 @@ var ts; } } checkSourceElement(node.body); - if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - var returnType = getTypeFromTypeNode(node.type); - var promisedType; - if (isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + if (!node.asteriskToken) { + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !node.type) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method @@ -24485,13 +26427,10 @@ var ts; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 192 /* Block */) { + if (node.kind === 196 /* Block */) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 219 /* ModuleBlock */) { - checkFunctionAndClassExpressionBodies(node); - } } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact @@ -24508,12 +26447,12 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 141 /* PropertyDeclaration */ || - node.kind === 140 /* PropertySignature */ || - node.kind === 143 /* MethodDeclaration */ || - node.kind === 142 /* MethodSignature */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */) { + if (node.kind === 143 /* PropertyDeclaration */ || + node.kind === 142 /* PropertySignature */ || + node.kind === 145 /* MethodDeclaration */ || + node.kind === 144 /* MethodSignature */ || + node.kind === 147 /* GetAccessor */ || + node.kind === 148 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -24522,7 +26461,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 138 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 140 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -24575,16 +26514,31 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 218 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 222 /* 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 === 248 /* SourceFile */ && ts.isExternalModule(parent)) { + if (parent.kind === 252 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (node.kind === 222 /* 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 === 252 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2097152 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } function checkVarDeclaredNamesNotShadowed(node) { // - ScriptBody : StatementList // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList @@ -24598,24 +26552,24 @@ var ts; // A non-initialized declaration is a no-op as the block declaration will resolve before the var // declaration. the problem is if the declaration has an initializer. this will act as a write to the // block declared value. this is fine for let, but not const. - // Only consider declarations with initializers, uninitialized let declarations will not + // Only consider declarations with initializers, uninitialized const declarations will not // step on a let/const variable. - // Do not consider let and const declarations, as duplicate block-scoped declarations + // Do not consider const and const declarations, as duplicate block-scoped declarations // are handled by the binder. - // We are only looking for let declarations that step on let\const declarations from a + // We are only looking for const declarations that step on let\const declarations from a // different scope. e.g.: // { // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration - // let x = 0; // symbol for this declaration will be 'symbol' + // const x = 0; // symbol for this declaration will be 'symbol' // } // skip block-scoped variables and parameters - if ((ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 3072 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { return; } // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 211 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 215 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -24624,25 +26578,25 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 193 /* VariableStatement */ && varDeclList.parent.parent + if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 3072 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 216 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 197 /* 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 === 192 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 219 /* ModuleBlock */ || - container.kind === 218 /* ModuleDeclaration */ || - container.kind === 248 /* SourceFile */); + (container.kind === 196 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 223 /* ModuleBlock */ || + container.kind === 222 /* ModuleDeclaration */ || + container.kind === 252 /* 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_14 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_14, name_14); + var name_15 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_15, name_15); } } } @@ -24650,7 +26604,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 !== 138 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 140 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -24661,7 +26615,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 === 138 /* Parameter */) { + if (referencedSymbol.valueDeclaration.kind === 140 /* Parameter */) { if (referencedSymbol.valueDeclaration === node) { error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); return; @@ -24687,24 +26641,31 @@ 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 === 136 /* ComputedPropertyName */) { + if (node.name.kind === 138 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } + if (node.kind === 167 /* BindingElement */) { + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 138 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { 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 === 138 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 140 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - if (node.initializer) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 204 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -24714,7 +26675,8 @@ var ts; var type = getTypeOfVariableOrParameterOrProperty(symbol); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer - if (node.initializer) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 204 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -24730,15 +26692,16 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } } - if (node.kind !== 141 /* PropertyDeclaration */ && node.kind !== 140 /* PropertySignature */) { + if (node.kind !== 143 /* PropertyDeclaration */ && node.kind !== 142 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + if (node.kind === 215 /* VariableDeclaration */ || node.kind === 167 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } function checkVariableDeclaration(node) { @@ -24756,7 +26719,7 @@ var ts; } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (node.modifiers && node.parent.kind === 169 /* ObjectLiteralExpression */) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -24777,7 +26740,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 194 /* EmptyStatement */) { + if (node.thenStatement.kind === 198 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -24797,12 +26760,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 216 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 216 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -24822,14 +26785,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 === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 216 /* 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 === 164 /* ArrayLiteralExpression */ || varExpr.kind === 165 /* ObjectLiteralExpression */) { + if (varExpr.kind === 168 /* ArrayLiteralExpression */ || varExpr.kind === 169 /* 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. @@ -24838,7 +26801,7 @@ var ts; else { var leftType = checkExpression(varExpr); checkReferenceExpression(varExpr, /*invalidReferenceMessage*/ ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, - /*constantVariableMessage*/ ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant); + /*constantVariableMessage*/ ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); // 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 @@ -24858,7 +26821,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 === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 216 /* 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); @@ -24872,7 +26835,7 @@ 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 === 164 /* ArrayLiteralExpression */ || varExpr.kind === 165 /* ObjectLiteralExpression */) { + if (varExpr.kind === 168 /* ArrayLiteralExpression */ || varExpr.kind === 169 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */)) { @@ -24880,7 +26843,7 @@ var ts; } else { // run check only former check succeeded to avoid cascading errors - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant); + checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); } } var rightType = checkExpression(node.expression); @@ -25051,7 +27014,7 @@ var ts; * This function does the following steps: * 1. Break up arrayOrStringType (possibly a union) into its string constituents and array constituents. * 2. Take the element types of the array constituents. - * 3. Return the union of the element types, and string if there was a string constitutent. + * 3. Return the union of the element types, and string if there was a string constituent. * * For example: * string -> string @@ -25068,7 +27031,13 @@ var ts; ts.Debug.assert(languageVersion < 2 /* ES6 */); // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. - var arrayType = removeTypesFromUnionType(arrayOrStringType, 258 /* StringLike */, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); + var arrayType = arrayOrStringType; + if (arrayOrStringType.flags & 16384 /* Union */) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258 /* StringLike */); })); + } + else if (arrayOrStringType.flags & 258 /* StringLike */) { + arrayType = emptyUnionType; + } var hasStringConstituent = arrayOrStringType !== arrayType; var reportedError = false; if (hasStringConstituent) { @@ -25110,8 +27079,8 @@ var ts; checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); // TODO: Check that target label is valid } - function isGetAccessorWithAnnotatatedSetAccessor(node) { - return !!(node.kind === 145 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 146 /* SetAccessor */))); + function isGetAccessorWithAnnotatedSetAccessor(node) { + return !!(node.kind === 147 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 148 /* SetAccessor */))); } function checkReturnStatement(node) { // Grammar checking @@ -25134,15 +27103,15 @@ var ts; // for generators. return; } - if (func.kind === 146 /* SetAccessor */) { + if (func.kind === 148 /* SetAccessor */) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === 144 /* Constructor */) { + else if (func.kind === 146 /* Constructor */) { if (!checkTypeAssignableTo(exprType, returnType, node.expression)) { 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) { + else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { if (ts.isAsyncFunctionLike(func)) { var promisedType = getPromisedType(returnType); var awaitedType = checkAwaitedType(exprType, node.expression, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -25163,7 +27132,7 @@ var ts; function checkWithStatement(node) { // Grammar checking for withStatement if (!checkGrammarStatementInAmbientContext(node)) { - if (node.parserContextFlags & 8 /* Await */) { + if (node.flags & 33554432 /* AwaitContext */) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -25176,9 +27145,10 @@ var ts; var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); + var expressionTypeIsStringLike = maybeTypeOfKind(expressionType, 258 /* StringLike */); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 242 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 246 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -25190,13 +27160,17 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 241 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 245 /* 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. var caseType = checkExpression(caseClause.expression); - if (!isTypeAssignableTo(expressionType, caseType)) { - // check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails + var expressionTypeIsAssignableToCaseType = + // Permit 'number[] | "foo"' to be asserted to 'string'. + (expressionTypeIsStringLike && maybeTypeOfKind(caseType, 258 /* StringLike */)) || + isTypeAssignableTo(expressionType, caseType); + if (!expressionTypeIsAssignableToCaseType) { + // 'expressionType is not assignable to caseType', try the reversed check and report errors if it fails checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); } } @@ -25211,7 +27185,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 207 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 211 /* 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; @@ -25285,7 +27259,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!(member.flags & 64 /* Static */) && ts.hasDynamicName(member)) { + if (!(member.flags & 32 /* Static */) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); @@ -25316,7 +27290,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 === 136 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 138 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { @@ -25350,7 +27324,7 @@ var ts; error(name, message, name.text); } } - // Check each type parameter and check that list has no duplicate type parameter declarations + /** Check each type parameter and check that type parameters have no duplicate type parameter declarations */ function checkTypeParameters(typeParameterDeclarations) { if (typeParameterDeclarations) { for (var i = 0, n = typeParameterDeclarations.length; i < n; i++) { @@ -25366,10 +27340,32 @@ var ts; } } } + /** Check that type parameter lists are identical across multiple declarations */ + function checkTypeParameterListsIdentical(node, symbol) { + if (symbol.declarations.length === 1) { + return; + } + var firstDecl; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 218 /* ClassDeclaration */ || declaration.kind === 219 /* InterfaceDeclaration */) { + if (!firstDecl) { + firstDecl = declaration; + } + else if (!areTypeParametersIdentical(firstDecl.typeParameters, node.typeParameters)) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, node.name.text); + } + } + } + } function checkClassExpression(node) { checkClassLikeDeclaration(node); + checkNodeDeferred(node); return getTypeOfSymbol(getSymbolOfNode(node)); } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + } function checkClassDeclaration(node) { if (!node.name && !(node.flags & 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -25384,6 +27380,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } checkTypeParameters(node.typeParameters); checkExportsOnMergedDeclarations(node); @@ -25391,13 +27388,14 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(node, symbol); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - emitExtends = emitExtends || !ts.isInAmbientContext(node); var baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { - var baseType = baseTypes[0]; + var baseType_1 = baseTypes[0]; var staticBaseType = getBaseConstructorTypeOfClass(type); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); if (baseTypeNode.typeArguments) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); @@ -25408,7 +27406,7 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (!(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 @@ -25416,11 +27414,11 @@ var ts; // 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; })) { + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } - checkKindsOfPropertyMemberOverrides(type, baseType); + checkKindsOfPropertyMemberOverrides(type, baseType_1); } } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); @@ -25450,6 +27448,18 @@ var ts; checkTypeForDuplicateIndexSignatures(node); } } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && declaration.flags & 8 /* Private */) { + var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); + } + } + } + } function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags @@ -25484,7 +27494,7 @@ var ts; var baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { - // In order to resolve whether the inherited method was overriden in the base class or not, + // In order to resolve whether the inherited method was overridden in the base class or not, // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* // type declaration, derived and base resolve to the same symbol even in the case of generic classes. if (derived === base) { @@ -25494,7 +27504,7 @@ var ts; // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 128 /* Abstract */))) { - if (derivedClassDecl.kind === 186 /* ClassExpression */) { + if (derivedClassDecl.kind === 190 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -25505,11 +27515,11 @@ var ts; else { // derived overrides base. var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); - if ((baseDeclarationFlags & 16 /* Private */) || (derivedDeclarationFlags & 16 /* Private */)) { + if ((baseDeclarationFlags & 8 /* Private */) || (derivedDeclarationFlags & 8 /* Private */)) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 64 /* Static */) !== (derivedDeclarationFlags & 64 /* Static */)) { + if ((baseDeclarationFlags & 32 /* Static */) !== (derivedDeclarationFlags & 32 /* Static */)) { // value of 'static' is not the same for properties - not override, skip it continue; } @@ -25542,7 +27552,7 @@ var ts; } } function isAccessor(kind) { - return kind === 145 /* GetAccessor */ || kind === 146 /* SetAccessor */; + return kind === 147 /* GetAccessor */ || kind === 148 /* SetAccessor */; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -25612,13 +27622,9 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 215 /* 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); - } - } + checkTypeParameterListsIdentical(node, symbol); // Only check this symbol once + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 219 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -25651,7 +27657,7 @@ var ts; } function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 8192 /* EnumValuesComputed */)) { + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { var enumSymbol = getSymbolOfNode(node); var enumType = getDeclaredTypeOfSymbol(enumSymbol); var autoValue = 0; // set to undefined when enum member is non-constant @@ -25659,11 +27665,14 @@ var ts; var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.name.kind === 136 /* ComputedPropertyName */) { + if (isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } - else if (isNumericLiteralName(member.name.text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + else { + var text = getTextOfPropertyName(member.name); + if (isNumericLiteralName(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } } var previousEnumMemberIsNonConstant = autoValue === undefined; var initializer = member.initializer; @@ -25683,10 +27692,11 @@ var ts; error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); } if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue++; + getNodeLinks(member).enumMemberValue = autoValue; + autoValue++; } } - nodeLinks.flags |= 8192 /* EnumValuesComputed */; + nodeLinks.flags |= 16384 /* EnumValuesComputed */; } function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { // Controls if error should be reported after evaluation of constant value is completed @@ -25718,7 +27728,7 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; @@ -25729,7 +27739,7 @@ var ts; case 50 /* TildeToken */: return ~value_1; } return undefined; - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -25754,15 +27764,15 @@ var ts; return undefined; case 8 /* NumericLiteral */: return +e.text; - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return evalConstant(e.expression); case 69 /* Identifier */: - case 167 /* ElementAccessExpression */: - case 166 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: + case 170 /* PropertyAccessExpression */: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; - var propertyName; + var propertyName = void 0; if (e.kind === 69 /* Identifier */) { // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. // instead pick current enum type and later try to fetch member from the type @@ -25770,8 +27780,8 @@ var ts; propertyName = e.text; } else { - var expression; - if (e.kind === 167 /* ElementAccessExpression */) { + var expression = void 0; + if (e.kind === 171 /* ElementAccessExpression */) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9 /* StringLiteral */) { return undefined; @@ -25789,7 +27799,7 @@ var ts; if (current.kind === 69 /* Identifier */) { break; } - else if (current.kind === 166 /* PropertyAccessExpression */) { + else if (current.kind === 170 /* PropertyAccessExpression */) { current = current.expression; } else { @@ -25834,6 +27844,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); @@ -25857,10 +27868,10 @@ var ts; } }); } - var seenEnumMissingInitialInitializer = false; + var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 217 /* EnumDeclaration */) { + if (declaration.kind !== 221 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -25869,11 +27880,11 @@ var ts; } var firstEnumMember = enumDeclaration.members[0]; if (!firstEnumMember.initializer) { - if (seenEnumMissingInitialInitializer) { + if (seenEnumMissingInitialInitializer_1) { error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); } else { - seenEnumMissingInitialInitializer = true; + seenEnumMissingInitialInitializer_1 = true; } } }); @@ -25883,8 +27894,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 214 /* ClassDeclaration */ || - (declaration.kind === 213 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 218 /* ClassDeclaration */ || + (declaration.kind === 217 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -25907,7 +27918,12 @@ var ts; function checkModuleDeclaration(node) { if (produceDiagnostics) { // Grammar checking - var isAmbientExternalModule = node.name.kind === 9 /* StringLiteral */; + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = ts.isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); var contextErrorMessage = isAmbientExternalModule ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; @@ -25916,18 +27932,19 @@ var ts; return; } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!ts.isInAmbientContext(node) && node.name.kind === 9 /* StringLiteral */) { + if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ && symbol.declarations.length > 1 - && !ts.isInAmbientContext(node) + && !inAmbientContext && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -25940,30 +27957,120 @@ 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, 214 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 218 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; } } - // Checks for ambient external modules. if (isAmbientExternalModule) { - if (!isGlobalSourceFile(node.parent)) { - error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + if (ts.isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Merged */); + if (checkBody) { + // body of ambient external module is always a module block + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } } - if (ts.isExternalModuleNameRelative(node.name.text)) { - error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(node.name.text)) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } } } } checkSourceElement(node.body); } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 197 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 231 /* ExportAssignment */: + case 232 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 225 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind !== 9 /* StringLiteral */) { + error(node.name, ts.Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + break; + } + // fallthrough + case 226 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 167 /* BindingElement */: + case 215 /* VariableDeclaration */: + var name_16 = node.name; + if (ts.isBindingPattern(name_16)) { + for (var _b = 0, _c = name_16.elements; _b < _c.length; _b++) { + var el = _c[_b]; + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // fallthrough + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 217 /* FunctionDeclaration */: + case 219 /* InterfaceDeclaration */: + case 222 /* ModuleDeclaration */: + case 220 /* TypeAliasDeclaration */: + var symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Merged */); + if (!reportError) { + if (isGlobalAugmentation) { + // global symbol should not have parent since it is not explicitly exported + reportError = symbol.parent !== undefined; + } + else { + // symbol should not originate in augmentation + reportError = ts.isExternalModuleAugmentation(symbol.parent.valueDeclaration); + } + } + if (reportError) { + error(node, ts.Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + } + } + break; + } + } function getFirstIdentifier(node) { while (true) { - if (node.kind === 135 /* QualifiedName */) { + if (node.kind === 137 /* QualifiedName */) { node = node.left; } - else if (node.kind === 166 /* PropertyAccessExpression */) { + else if (node.kind === 170 /* PropertyAccessExpression */) { node = node.expression; } else { @@ -25979,20 +28086,24 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 219 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; - if (node.parent.kind !== 248 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 228 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 223 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 252 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 232 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - // TypeScript 1.0 spec (April 2013): 12.1.6 - // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference - // other external modules only through top - level external module names. - // Relative external module names are not permitted. - error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); - return false; + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } } return true; } @@ -26004,7 +28115,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 === 230 /* ExportSpecifier */ ? + var message = node.kind === 234 /* 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)); @@ -26014,6 +28125,7 @@ var ts; function checkImportBinding(node) { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); } function checkImportDeclaration(node) { @@ -26021,7 +28133,7 @@ var ts; // 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 & 1022 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -26031,7 +28143,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 228 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -26049,7 +28161,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -26068,7 +28180,7 @@ var ts; } } else { - if (modulekind === 5 /* ES6 */ && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES6 && !ts.isInAmbientContext(node)) { // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } @@ -26080,7 +28192,7 @@ var ts; // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -26088,29 +28200,38 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 219 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; - if (node.parent.kind !== 248 /* SourceFile */ && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 223 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 252 /* SourceFile */ && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } else { // export * from "foo" var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && moduleSymbol.exports["export="]) { + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } } } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 248 /* SourceFile */ && node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 218 /* ModuleDeclaration */) { + if (node.parent.kind !== 252 /* SourceFile */ && node.parent.kind !== 223 /* ModuleBlock */ && node.parent.kind !== 222 /* ModuleDeclaration */) { return grammarErrorOnFirstToken(node, errorMessage); } } function checkExportSpecifier(node) { checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { - markExportAsReferenced(node); + var exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_re_export_name_that_is_not_defined_in_the_module); + } + else { + markExportAsReferenced(node); + } } } function checkExportAssignment(node) { @@ -26118,13 +28239,13 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 248 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 218 /* ModuleDeclaration */ && container.name.kind === 69 /* Identifier */) { + var container = node.parent.kind === 252 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 222 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69 /* Identifier */) { @@ -26135,25 +28256,16 @@ var ts; } checkExternalModuleExports(container); if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === 5 /* ES6 */) { + if (modulekind === ts.ModuleKind.ES6) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_export_default_or_another_module_format_instead); } - else if (modulekind === 4 /* System */) { + else if (modulekind === ts.ModuleKind.System) { // system modules does not support export assignment grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); } } } - function getModuleStatements(node) { - if (node.kind === 248 /* SourceFile */) { - return node.statements; - } - if (node.kind === 218 /* ModuleDeclaration */ && node.body.kind === 219 /* ModuleBlock */) { - return node.body.statements; - } - return emptyArray; - } function hasExportedMembers(moduleSymbol) { for (var id in moduleSymbol.exports) { if (id !== "export=") { @@ -26169,14 +28281,41 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports["export="]; if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + var exports = getExportsOfModule(moduleSymbol); + for (var id in exports) { + if (id === "__export") { + continue; + } + var _a = exports[id], declarations = _a.declarations, flags = _a.flags; + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1536 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + continue; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + continue; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); + } + } + } } 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 isNotOverload(declaration) { + return declaration.kind !== 217 /* FunctionDeclaration */ || !!declaration.body; } } function checkSourceElement(node) { @@ -26185,229 +28324,156 @@ var ts; } var kind = node.kind; if (cancellationToken) { - // Only bother checking on a few construct kinds. We don't want to be excessivly + // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 222 /* ModuleDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 217 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 137 /* TypeParameter */: + case 139 /* TypeParameter */: return checkTypeParameter(node); - case 138 /* Parameter */: + case 140 /* Parameter */: return checkParameter(node); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return checkPropertyDeclaration(node); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: return checkSignatureDeclaration(node); - case 149 /* IndexSignature */: + case 151 /* IndexSignature */: return checkSignatureDeclaration(node); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return checkMethodDeclaration(node); - case 144 /* Constructor */: + case 146 /* Constructor */: return checkConstructorDeclaration(node); - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: return checkAccessorDeclaration(node); - case 151 /* TypeReference */: + case 153 /* TypeReference */: return checkTypeReferenceNode(node); - case 150 /* TypePredicate */: + case 152 /* TypePredicate */: return checkTypePredicate(node); - case 154 /* TypeQuery */: + case 156 /* TypeQuery */: return checkTypeQuery(node); - case 155 /* TypeLiteral */: + case 157 /* TypeLiteral */: return checkTypeLiteral(node); - case 156 /* ArrayType */: + case 158 /* ArrayType */: return checkArrayType(node); - case 157 /* TupleType */: + case 159 /* TupleType */: return checkTupleType(node); - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 160 /* UnionType */: + case 161 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 160 /* ParenthesizedType */: + case 162 /* ParenthesizedType */: return checkSourceElement(node.type); - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 196 /* Block */: + case 223 /* ModuleBlock */: return checkBlock(node); - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return checkVariableStatement(node); - case 195 /* ExpressionStatement */: + case 199 /* ExpressionStatement */: return checkExpressionStatement(node); - case 196 /* IfStatement */: + case 200 /* IfStatement */: return checkIfStatement(node); - case 197 /* DoStatement */: + case 201 /* DoStatement */: return checkDoStatement(node); - case 198 /* WhileStatement */: + case 202 /* WhileStatement */: return checkWhileStatement(node); - case 199 /* ForStatement */: + case 203 /* ForStatement */: return checkForStatement(node); - case 200 /* ForInStatement */: + case 204 /* ForInStatement */: return checkForInStatement(node); - case 201 /* ForOfStatement */: + case 205 /* ForOfStatement */: return checkForOfStatement(node); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 206 /* ContinueStatement */: + case 207 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 204 /* ReturnStatement */: + case 208 /* ReturnStatement */: return checkReturnStatement(node); - case 205 /* WithStatement */: + case 209 /* WithStatement */: return checkWithStatement(node); - case 206 /* SwitchStatement */: + case 210 /* SwitchStatement */: return checkSwitchStatement(node); - case 207 /* LabeledStatement */: + case 211 /* LabeledStatement */: return checkLabeledStatement(node); - case 208 /* ThrowStatement */: + case 212 /* ThrowStatement */: return checkThrowStatement(node); - case 209 /* TryStatement */: + case 213 /* TryStatement */: return checkTryStatement(node); - case 211 /* VariableDeclaration */: + case 215 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 163 /* BindingElement */: + case 167 /* BindingElement */: return checkBindingElement(node); - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: return checkClassDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 216 /* TypeAliasDeclaration */: + case 220 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: return checkImportDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: return checkExportDeclaration(node); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return checkExportAssignment(node); - case 194 /* EmptyStatement */: + case 198 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 210 /* DebuggerStatement */: + case 214 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 231 /* MissingDeclaration */: + case 235 /* MissingDeclaration */: return checkMissingDeclaration(node); } } // Function and class expression bodies are checked after all statements in the enclosing body. This is // to ensure constructs like the following are permitted: - // let foo = function () { - // let s = foo(); + // const foo = function () { + // const s = foo(); // return "hello"; // } // Here, performing a full type check of the body of the function expression whilst in the process of // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. - function checkFunctionAndClassExpressionBodies(node) { - switch (node.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - checkFunctionExpressionOrObjectLiteralMethodBody(node); - break; - case 186 /* ClassExpression */: - ts.forEach(node.members, checkSourceElement); - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - if (ts.isObjectLiteralMethod(node)) { - checkFunctionExpressionOrObjectLiteralMethodBody(node); - } - break; - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - break; - case 205 /* WithStatement */: - checkFunctionAndClassExpressionBodies(node.expression); - break; - case 139 /* Decorator */: - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 163 /* BindingElement */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 245 /* PropertyAssignment */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 170 /* TaggedTemplateExpression */: - case 183 /* TemplateExpression */: - case 190 /* TemplateSpan */: - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: - case 172 /* ParenthesizedExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 178 /* AwaitExpression */: - case 175 /* DeleteExpression */: - case 179 /* PrefixUnaryExpression */: - case 180 /* PostfixUnaryExpression */: - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 184 /* YieldExpression */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 193 /* VariableStatement */: - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 220 /* CaseBlock */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: - case 211 /* VariableDeclaration */: - case 212 /* VariableDeclarationList */: - case 214 /* ClassDeclaration */: - case 243 /* HeritageClause */: - case 188 /* ExpressionWithTypeArguments */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 227 /* ExportAssignment */: - case 248 /* SourceFile */: - case 240 /* JsxExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - case 235 /* JsxOpeningElement */: - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + checkAccessorDeferred(node); + break; + case 190 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + } } } function checkSourceFile(node) { @@ -26421,39 +28487,27 @@ var ts; 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; + if (compilerOptions.skipDefaultLibCheck) { + // If the user specified '--noLib' and a file has a '/// ', + // then we should treat that file as a default lib. + if (node.hasNoDefaultLib) { + return; + } } // Grammar checking checkGrammarSourceFile(node); - emitExtends = false; - emitDecorate = false; - emitParam = false; potentialThisCollisions.length = 0; + deferredNodes = []; ts.forEach(node.statements, checkSourceElement); - checkFunctionAndClassExpressionBodies(node); - if (ts.isExternalModule(node)) { + checkDeferredNodes(); + deferredNodes = undefined; + if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } if (potentialThisCollisions.length) { ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); potentialThisCollisions.length = 0; } - if (emitExtends) { - links.flags |= 8 /* EmitExtends */; - } - if (emitDecorate) { - links.flags |= 16 /* EmitDecorate */; - } - if (emitParam) { - links.flags |= 32 /* EmitParam */; - } - if (emitAwaiter) { - links.flags |= 64 /* EmitAwaiter */; - } - if (emitGenerator || (emitAwaiter && languageVersion < 2 /* ES6 */)) { - links.flags |= 128 /* EmitGenerator */; - } links.flags |= 1 /* TypeChecked */; } } @@ -26491,7 +28545,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 205 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 209 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -26514,34 +28568,34 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 248 /* SourceFile */: - if (!ts.isExternalModule(location)) { + case 252 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } // fall through; this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. - if (!(memberFlags & 64 /* Static */)) { + if (!(memberFlags & 32 /* Static */)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; - case 173 /* FunctionExpression */: + case 177 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -26590,37 +28644,48 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 137 /* TypeParameter */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: + case 139 /* TypeParameter */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 221 /* 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 === 135 /* QualifiedName */) { + while (node.parent && node.parent.kind === 137 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 151 /* TypeReference */; + return node.parent && node.parent.kind === 153 /* TypeReference */; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 166 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 170 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 188 /* ExpressionWithTypeArguments */; + return node.parent && node.parent.kind === 192 /* ExpressionWithTypeArguments */; + } + function isNodeWithinClass(node, classDeclaration) { + while (true) { + node = ts.getContainingClass(node); + if (!node) { + return false; + } + if (node === classDeclaration) { + return true; + } + } } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 135 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 137 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 221 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 225 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 227 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 231 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -26632,11 +28697,23 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 227 /* ExportAssignment */) { + if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 170 /* PropertyAccessExpression */) { + var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + return getSymbolOfNode(entityName.parent.parent); + default: + } + } + if (entityName.parent.kind === 231 /* ExportAssignment */) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 166 /* PropertyAccessExpression */) { + if (entityName.kind !== 170 /* PropertyAccessExpression */) { if (isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); @@ -26648,7 +28725,7 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 188 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 192 /* ExpressionWithTypeArguments */) { meaning = 793056 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -26661,10 +28738,10 @@ var ts; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if ((entityName.parent.kind === 235 /* JsxOpeningElement */) || - (entityName.parent.kind === 234 /* JsxSelfClosingElement */) || - (entityName.parent.kind === 237 /* JsxClosingElement */)) { - return getJsxElementTagSymbol(entityName.parent); + else if ((entityName.parent.kind === 239 /* JsxOpeningElement */) || + (entityName.parent.kind === 238 /* JsxSelfClosingElement */) || + (entityName.parent.kind === 241 /* JsxClosingElement */)) { + return getJsxTagSymbol(entityName.parent); } else if (ts.isExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { @@ -26677,14 +28754,14 @@ var ts; var meaning = 107455 /* Value */ | 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 166 /* PropertyAccessExpression */) { + else if (entityName.kind === 170 /* PropertyAccessExpression */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 135 /* QualifiedName */) { + else if (entityName.kind === 137 /* QualifiedName */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -26693,16 +28770,16 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = entityName.parent.kind === 153 /* 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 */; return resolveEntityName(entityName, meaning); } - else if (entityName.parent.kind === 238 /* JsxAttribute */) { + else if (entityName.parent.kind === 242 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 150 /* TypePredicate */) { + if (entityName.parent.kind === 152 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? @@ -26719,12 +28796,12 @@ var ts; } if (node.kind === 69 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 227 /* ExportAssignment */ + return node.parent.kind === 231 /* ExportAssignment */ ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } - else if (node.parent.kind === 163 /* BindingElement */ && - node.parent.parent.kind === 161 /* ObjectBindingPattern */ && + else if (node.parent.kind === 167 /* BindingElement */ && + node.parent.parent.kind === 165 /* ObjectBindingPattern */ && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -26735,17 +28812,19 @@ var ts; } switch (node.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: - case 135 /* QualifiedName */: + case 170 /* PropertyAccessExpression */: + case 137 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; + case 163 /* ThisType */: + return getTypeFromTypeNode(node).symbol; case 121 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 144 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 146 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -26753,14 +28832,14 @@ var ts; // External module name in an import declaration if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 222 /* ImportDeclaration */ || node.parent.kind === 228 /* ExportDeclaration */) && + ((node.parent.kind === 226 /* ImportDeclaration */ || node.parent.kind === 232 /* ExportDeclaration */) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } // Fall through case 8 /* NumericLiteral */: // index access - if (node.parent.kind === 167 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + if (node.parent.kind === 171 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -26777,11 +28856,17 @@ 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 === 246 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 107455 /* Value */); + if (location && location.kind === 250 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 107455 /* Value */ | 8388608 /* Alias */); } return undefined; } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further @@ -26838,7 +28923,7 @@ var ts; */ function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 64 /* Static */ + return node.flags & 32 /* Static */ ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -26858,15 +28943,15 @@ var ts; } function getRootSymbols(symbol) { if (symbol.flags & 268435456 /* SyntheticProperty */) { - var symbols = []; - var name_15 = symbol.name; + var symbols_3 = []; + var name_17 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_15); + var symbol = getPropertyOfType(t, name_17); if (symbol) { - symbols.push(symbol); + symbols_3.push(symbol); } }); - return symbols; + return symbols_3; } else if (symbol.flags & 67108864 /* Transient */) { var target = getSymbolLinks(symbol).target; @@ -26880,6 +28965,30 @@ var ts; function isArgumentsLocalBinding(node) { return getReferencedValueSymbol(node) === argumentsSymbol; } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol) { + // module not found - be conservative + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455 /* Value */) + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455 /* Value */); + } + } // 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) { @@ -26897,11 +29006,11 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 248 /* SourceFile */) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 252 /* SourceFile */) { return parentSymbol.valueDeclaration; } for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 218 /* ModuleDeclaration */ || n.kind === 217 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { + if ((n.kind === 222 /* ModuleDeclaration */ || n.kind === 221 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { return n; } } @@ -26914,58 +29023,77 @@ var ts; var symbol = getReferencedValueSymbol(node); return symbol && symbol.flags & 8388608 /* Alias */ ? getDeclarationOfAliasSymbol(symbol) : undefined; } - function isStatementWithLocals(node) { - switch (node.kind) { - case 192 /* Block */: - case 220 /* CaseBlock */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - return true; - } - return false; - } - function isNestedRedeclarationSymbol(symbol) { + function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418 /* BlockScoped */) { var links = getSymbolLinks(symbol); - if (links.isNestedRedeclaration === undefined) { + if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - links.isNestedRedeclaration = isStatementWithLocals(container) && - !!resolveName(container.parent, symbol.name, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.name, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { + // redeclaration - always should be renamed + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 196 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } } - return links.isNestedRedeclaration; + return links.isDeclarationWithCollidingName; } return false; } // When resolved as an expression identifier, if the given node references a nested block scoped entity with - // a name that hides an existing name, return the declaration of that entity. Otherwise, return undefined. - function getReferencedNestedRedeclaration(node) { + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(node) { var symbol = getReferencedValueSymbol(node); - return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + return symbol && isSymbolOfDeclarationWithCollidingName(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)); + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(node) { + return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); } function isValueAliasDeclaration(node) { switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 225 /* ImportEqualsDeclaration */: + case 227 /* ImportClause */: + case 228 /* NamespaceImport */: + case 230 /* ImportSpecifier */: + case 234 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node)); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return node.expression && node.expression.kind === 69 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 248 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 252 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -26977,7 +29105,7 @@ var ts; if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } - // const enums and modules that contain only const enums are not considered values from the emit perespective + // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true return target !== unknownSymbol && target && @@ -27027,7 +29155,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 247 /* EnumMember */) { + if (node.kind === 251 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -27062,22 +29190,22 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (allConstituentTypesHaveKind(type, 16 /* Void */)) { + else if (isTypeOfKind(type, 16 /* Void */)) { return ts.TypeReferenceSerializationKind.VoidType; } - else if (allConstituentTypesHaveKind(type, 8 /* Boolean */)) { + else if (isTypeOfKind(type, 8 /* Boolean */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (allConstituentTypesHaveKind(type, 132 /* NumberLike */)) { + else if (isTypeOfKind(type, 132 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (allConstituentTypesHaveKind(type, 258 /* StringLike */)) { + else if (isTypeOfKind(type, 258 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (allConstituentTypesHaveKind(type, 8192 /* Tuple */)) { + else if (isTypeOfKind(type, 8192 /* Tuple */)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (allConstituentTypesHaveKind(type, 16777216 /* ESSymbol */)) { + else if (isTypeOfKind(type, 16777216 /* ESSymbol */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -27119,23 +29247,12 @@ var ts; var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } - function instantiateSingleCallFunctionType(functionType, typeArguments) { - if (functionType === unknownType) { - return unknownType; - } - var signature = getSingleCallSignature(functionType); - if (!signature) { - return unknownType; - } - var instantiatedSignature = getSignatureInstantiation(signature, typeArguments); - return getOrCreateTypeFromSignature(instantiatedSignature); - } function createResolver() { return { getReferencedExportContainer: getReferencedExportContainer, getReferencedImportDeclaration: getReferencedImportDeclaration, - getReferencedNestedRedeclaration: getReferencedNestedRedeclaration, - isNestedRedeclaration: isNestedRedeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, isValueAliasDeclaration: isValueAliasDeclaration, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: isReferencedAliasDeclaration, @@ -27153,25 +29270,50 @@ var ts; getReferencedValueDeclaration: getReferencedValueDeclaration, getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, isOptionalParameter: isOptionalParameter, - isArgumentsLocalBinding: isArgumentsLocalBinding + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration }; } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 252 /* SourceFile */); + } function initializeTypeChecker() { // Bind all source files and propagate errors ts.forEach(host.getSourceFiles(), function (file) { ts.bindSourceFile(file, compilerOptions); }); + var augmentations; // Initialize global symbol table ts.forEach(host.getSourceFiles(), function (file) { - if (!ts.isExternalModule(file)) { + if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } }); - // Initialize special symbols + if (augmentations) { + // merge module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _i = 0, augmentations_1 = augmentations; _i < augmentations_1.length; _i++) { + var list = augmentations_1[_i]; + for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { + var augmentation = list_2[_a]; + mergeModuleAugmentation(augmentation); + } + } + } + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; - globals[undefinedSymbol.name] = undefinedSymbol; // Initialize special types globalArrayType = getGlobalType("Array", /*arity*/ 1); globalObjectType = getGlobalType("Object"); @@ -27215,6 +29357,9 @@ var ts; globalIterableIteratorType = emptyGenericType; } anyArrayType = createArrayType(anyType); + var symbol = getGlobalSymbol("ReadonlyArray", 793056 /* Type */, /*diagnostic*/ undefined); + globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); @@ -27240,9 +29385,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + if (node.kind === 145 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } } - else if (node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */) { + else if (node.kind === 147 /* GetAccessor */ || node.kind === 148 /* 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); @@ -27252,38 +29402,38 @@ var ts; } function checkGrammarModifiers(node) { switch (node.kind) { - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 144 /* Constructor */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 149 /* IndexSignature */: - case 218 /* ModuleDeclaration */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: - case 227 /* ExportAssignment */: - case 138 /* Parameter */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 146 /* Constructor */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 151 /* IndexSignature */: + case 222 /* ModuleDeclaration */: + case 226 /* ImportDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 232 /* ExportDeclaration */: + case 231 /* ExportAssignment */: + case 140 /* Parameter */: break; - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118 /* AsyncKeyword */) && - node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + node.parent.kind !== 223 /* ModuleBlock */ && node.parent.kind !== 252 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 193 /* VariableStatement */: - case 216 /* TypeAliasDeclaration */: - if (node.modifiers && node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 197 /* VariableStatement */: + case 220 /* TypeAliasDeclaration */: + if (node.modifiers && node.parent.kind !== 223 /* ModuleBlock */ && node.parent.kind !== 252 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74 /* ConstKeyword */) && - node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + node.parent.kind !== 223 /* ModuleBlock */ && node.parent.kind !== 252 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; @@ -27293,37 +29443,48 @@ var ts; if (!node.modifiers) { return; } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync; + var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (modifier.kind !== 127 /* ReadonlyKeyword */) { + if (node.kind === 142 /* PropertySignature */ || node.kind === 144 /* MethodSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 151 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } switch (modifier.kind) { + case 74 /* ConstKeyword */: + if (node.kind !== 221 /* EnumDeclaration */ && node.parent.kind === 218 /* ClassDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74 /* ConstKeyword */)); + } + break; case 112 /* PublicKeyword */: case 111 /* ProtectedKeyword */: case 110 /* PrivateKeyword */: - var text = void 0; - if (modifier.kind === 112 /* PublicKeyword */) { - text = "public"; - } - else if (modifier.kind === 111 /* ProtectedKeyword */) { - text = "protected"; + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (modifier.kind === 111 /* ProtectedKeyword */) { lastProtected = modifier; } - else { - text = "private"; + else if (modifier.kind === 110 /* PrivateKeyword */) { lastPrivate = modifier; } - if (flags & 56 /* AccessibilityModifier */) { + if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & 64 /* Static */) { + else if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); + else if (node.parent.kind === 223 /* ModuleBlock */ || node.parent.kind === 252 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { if (modifier.kind === 110 /* PrivateKeyword */) { @@ -27336,29 +29497,42 @@ var ts; flags |= ts.modifierToFlag(modifier.kind); break; case 113 /* StaticKeyword */: - if (flags & 64 /* Static */) { + if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); + else if (node.parent.kind === 223 /* ModuleBlock */ || node.parent.kind === 252 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 140 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= 64 /* Static */; + flags |= 32 /* Static */; lastStatic = modifier; break; + case 127 /* ReadonlyKeyword */: + if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 143 /* PropertyDeclaration */ && node.kind !== 142 /* PropertySignature */ && node.kind !== 151 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64 /* Readonly */; + lastReadonly = modifier; + break; case 82 /* ExportKeyword */: - if (flags & 2 /* Export */) { + if (flags & 1 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & 4 /* Ambient */) { + else if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } else if (flags & 128 /* Abstract */) { @@ -27367,48 +29541,51 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 218 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 140 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= 2 /* Export */; + flags |= 1 /* Export */; break; case 122 /* DeclareKeyword */: - if (flags & 4 /* Ambient */) { + if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 218 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 140 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219 /* ModuleBlock */) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 223 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= 4 /* Ambient */; + flags |= 2 /* Ambient */; lastDeclare = modifier; break; case 115 /* AbstractKeyword */: if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 214 /* ClassDeclaration */) { - if (node.kind !== 143 /* MethodDeclaration */) { - return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); + if (node.kind !== 218 /* ClassDeclaration */) { + if (node.kind !== 145 /* MethodDeclaration */ && + node.kind !== 143 /* PropertyDeclaration */ && + node.kind !== 147 /* GetAccessor */ && + node.kind !== 148 /* SetAccessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 214 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { + if (!(node.parent.kind === 218 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & 64 /* Static */) { + if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 16 /* Private */) { + if (flags & 8 /* Private */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } @@ -27418,10 +29595,10 @@ var ts; if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 4 /* Ambient */ || ts.isInAmbientContext(node.parent)) { + else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 140 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -27429,28 +29606,25 @@ var ts; break; } } - if (node.kind === 144 /* Constructor */) { - if (flags & 64 /* Static */) { + if (node.kind === 146 /* Constructor */) { + if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & 32 /* Protected */) { - return grammarErrorOnNode(lastProtected, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); - } - else if (flags & 16 /* Private */) { - return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); - } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } return; } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && flags & 4 /* Ambient */) { + else if ((node.kind === 226 /* ImportDeclaration */ || node.kind === 225 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 138 /* Parameter */ && (flags & 56 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 140 /* Parameter */ && (flags & 28 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } if (flags & 256 /* Async */) { @@ -27462,10 +29636,10 @@ var ts; return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher); } switch (node.kind) { - case 143 /* MethodDeclaration */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: if (!node.asteriskToken) { return false; } @@ -27531,7 +29705,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 174 /* ArrowFunction */) { + if (node.kind === 178 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -27554,7 +29728,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 1022 /* Modifier */) { + if (parameter.flags & 959 /* Modifier */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -27566,21 +29740,16 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 130 /* StringKeyword */ && parameter.type.kind !== 128 /* NumberKeyword */) { + if (parameter.type.kind !== 131 /* StringKeyword */ && parameter.type.kind !== 129 /* NumberKeyword */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } } - function checkGrammarForIndexSignatureModifier(node) { - if (node.flags & 1022 /* Modifier */) { - grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); - } - } function checkGrammarIndexSignature(node) { // Prevent cascading error by short-circuit - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node) || checkGrammarForIndexSignatureModifier(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); } function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { if (typeArguments && typeArguments.length === 0) { @@ -27599,7 +29768,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { var arg = args_1[_i]; - if (arg.kind === 187 /* OmittedExpression */) { + if (arg.kind === 191 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -27673,19 +29842,19 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 136 /* ComputedPropertyName */) { + if (node.kind !== 138 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 181 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { + if (computedPropertyName.expression.kind === 185 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */ || - node.kind === 143 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 217 /* FunctionDeclaration */ || + node.kind === 177 /* FunctionExpression */ || + node.kind === 145 /* MethodDeclaration */); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -27706,23 +29875,28 @@ var ts; var seen = {}; var Property = 1; var GetAccessor = 2; - var SetAccesor = 4; - var GetOrSetAccessor = GetAccessor | SetAccesor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - var name_16 = prop.name; - if (prop.kind === 187 /* OmittedExpression */ || - name_16.kind === 136 /* ComputedPropertyName */) { + var SetAccessor = 4; + var GetOrSetAccessor = GetAccessor | SetAccessor; + var _loop_1 = function(prop) { + var name_18 = prop.name; + if (prop.kind === 191 /* OmittedExpression */ || + name_18.kind === 138 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name_16); - continue; + checkGrammarComputedPropertyName(name_18); + return "continue"; } - if (prop.kind === 246 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 250 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; } - // ECMA-262 11.1.5 Object Initialiser + // Modifiers are never allowed on properties except for 'async' on a method declaration + ts.forEach(prop.modifiers, function (mod) { + if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 145 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + }); + // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and // IsDataDescriptor(propId.descriptor) is true. @@ -27731,65 +29905,71 @@ 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 === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */) { - // Grammar checking for computedPropertName and shorthandPropertyAssignment + if (prop.kind === 249 /* PropertyAssignment */ || prop.kind === 250 /* ShorthandPropertyAssignment */) { + // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_16.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name_16); + if (name_18.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name_18); } currentKind = Property; } - else if (prop.kind === 143 /* MethodDeclaration */) { + else if (prop.kind === 145 /* MethodDeclaration */) { currentKind = Property; } - else if (prop.kind === 145 /* GetAccessor */) { + else if (prop.kind === 147 /* GetAccessor */) { currentKind = GetAccessor; } - else if (prop.kind === 146 /* SetAccessor */) { - currentKind = SetAccesor; + else if (prop.kind === 148 /* SetAccessor */) { + currentKind = SetAccessor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_16.text)) { - seen[name_16.text] = currentKind; + if (!ts.hasProperty(seen, name_18.text)) { + seen[name_18.text] = currentKind; } else { - var existingKind = seen[name_16.text]; + var existingKind = seen[name_18.text]; if (currentKind === Property && existingKind === Property) { - continue; + return "continue"; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_16.text] = currentKind | existingKind; + seen[name_18.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return { value: grammarErrorOnNode(name_18, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return { value: grammarErrorOnNode(name_18, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } + }; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_1(prop); + if (typeof state_2 === "object") return state_2.value; + if (state_2 === "continue") continue; } } function checkGrammarJsxElement(node) { var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 239 /* JsxSpreadAttribute */) { + if (attr.kind === 243 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; - var name_17 = jsxAttr.name; - if (!ts.hasProperty(seen, name_17.text)) { - seen[name_17.text] = true; + var name_19 = jsxAttr.name; + if (!ts.hasProperty(seen, name_19.text)) { + seen[name_19.text] = true; } else { - return grammarErrorOnNode(name_17, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_19, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 240 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 244 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -27798,24 +29978,35 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 212 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 216 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { - if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 204 /* 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]; + var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 204 /* 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 === 200 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 204 /* 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); @@ -27832,16 +30023,16 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined) { + else if (accessor.body === undefined && !(accessor.flags & 128 /* Abstract */)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } - else if (kind === 145 /* GetAccessor */ && accessor.parameters.length) { + else if (kind === 147 /* GetAccessor */ && accessor.parameters.length) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); } - else if (kind === 146 /* SetAccessor */) { + else if (kind === 148 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -27853,7 +30044,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); } - else if (parameter.flags & 1022 /* Modifier */) { + else if (parameter.flags & 959 /* Modifier */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } else if (parameter.questionToken) { @@ -27866,7 +30057,7 @@ var ts; } } function checkGrammarForNonSymbolComputedProperty(node, message) { - if (node.kind === 136 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(node.expression)) { + if (ts.isDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -27876,12 +30067,12 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (node.parent.kind === 169 /* ObjectLiteralExpression */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } else if (node.body === undefined) { - return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (ts.isClassLike(node.parent)) { @@ -27900,10 +30091,10 @@ 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 === 215 /* InterfaceDeclaration */) { + else if (node.parent.kind === 219 /* 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 === 155 /* TypeLiteral */) { + else if (node.parent.kind === 157 /* TypeLiteral */) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } @@ -27914,11 +30105,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 207 /* LabeledStatement */: + case 211 /* 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 === 202 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 206 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -27926,8 +30117,8 @@ var ts; return false; } break; - case 206 /* SwitchStatement */: - if (node.kind === 203 /* BreakStatement */ && !node.label) { + case 210 /* SwitchStatement */: + if (node.kind === 207 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -27942,13 +30133,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 203 /* BreakStatement */ + var message = node.kind === 207 /* 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 === 203 /* BreakStatement */ + var message = node.kind === 207 /* 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); @@ -27960,7 +30151,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 === 162 /* ArrayBindingPattern */ || node.name.kind === 161 /* ObjectBindingPattern */) { + if (node.name.kind === 166 /* ArrayBindingPattern */ || node.name.kind === 165 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -27970,7 +30161,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 200 /* ForInStatement */ && node.parent.parent.kind !== 201 /* ForOfStatement */) { + if (node.parent.parent.kind !== 204 /* ForInStatement */ && node.parent.parent.kind !== 205 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { // Error on equals token which immediate precedes the initializer @@ -27987,7 +30178,7 @@ var ts; } } } - var checkLetConstNames = languageVersion >= 2 /* ES6 */ && (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding @@ -27998,7 +30189,7 @@ var ts; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 69 /* Identifier */) { - if (name.text === "let") { + if (name.originalKeywordKind === 108 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -28006,7 +30197,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 191 /* OmittedExpression */) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -28023,15 +30214,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 200 /* IfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: + case 209 /* WithStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: return false; - case 207 /* LabeledStatement */: + case 211 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -28046,23 +30237,6 @@ var ts; } } } - function isIntegerLiteral(expression) { - if (expression.kind === 179 /* PrefixUnaryExpression */) { - var unaryExpression = expression; - if (unaryExpression.operator === 35 /* PlusToken */ || unaryExpression.operator === 36 /* MinusToken */) { - expression = unaryExpression.operand; - } - } - if (expression.kind === 8 /* NumericLiteral */) { - // Allows for scientific notation since literalExpression.text was formed by - // coercing a number to a string. Sometimes this coercion can yield a string - // in scientific notation. - // We also don't need special logic for hex because a hex integer is converted - // to decimal when it is coerced. - return /^[0-9]+([eE]\+?[0-9]+)?$/.test(expression.text); - } - return false; - } function hasParseDiagnostics(sourceFile) { return sourceFile.parseDiagnostics.length > 0; } @@ -28087,10 +30261,6 @@ var ts; return true; } } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 /* 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); @@ -28108,15 +30278,21 @@ var ts; return true; } } - else if (node.parent.kind === 215 /* InterfaceDeclaration */) { + else if (node.parent.kind === 219 /* InterfaceDeclaration */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } } - else if (node.parent.kind === 155 /* TypeLiteral */) { + else if (node.parent.kind === 157 /* TypeLiteral */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } } if (ts.isInAmbientContext(node) && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); @@ -28135,14 +30311,14 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 215 /* InterfaceDeclaration */ || - node.kind === 216 /* TypeAliasDeclaration */ || - node.kind === 222 /* ImportDeclaration */ || - node.kind === 221 /* ImportEqualsDeclaration */ || - node.kind === 228 /* ExportDeclaration */ || - node.kind === 227 /* ExportAssignment */ || - (node.flags & 4 /* Ambient */) || - (node.flags & (2 /* Export */ | 512 /* Default */))) { + if (node.kind === 219 /* InterfaceDeclaration */ || + node.kind === 220 /* TypeAliasDeclaration */ || + node.kind === 226 /* ImportDeclaration */ || + node.kind === 225 /* ImportEqualsDeclaration */ || + node.kind === 232 /* ExportDeclaration */ || + node.kind === 231 /* ExportAssignment */ || + (node.flags & 2 /* Ambient */) || + (node.flags & (1 /* Export */ | 512 /* Default */))) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -28150,7 +30326,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 === 193 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 197 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -28173,10 +30349,10 @@ var ts; } // We are either parented by another statement, or some sort of block. // If we're in a block, we only want to really report an error once - // to prevent noisyness. So use a bit on the block to indicate if + // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 192 /* Block */ || node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + if (node.parent.kind === 196 /* Block */ || node.parent.kind === 223 /* ModuleBlock */ || node.parent.kind === 252 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -28189,7 +30365,7 @@ var ts; } function checkGrammarNumericLiteral(node) { // Grammar checking - if (node.flags & 32768 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { + if (node.isOctalLiteral && languageVersion >= 1 /* ES5 */) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -28201,21 +30377,345 @@ var ts; return true; } } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); /// /* @internal */ var ts; +(function (ts) { + var nullSourceMapWriter; + // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans + var defaultLastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitStart: function (range) { }, + emitEnd: function (range, stopOverridingSpan) { }, + emitPos: function (pos) { }, + changeEmitSourcePos: function () { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; }, + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var currentSourceFile; + var sourceMapDir; // The directory in which sourcemap will be + var stopOverridingSpan = false; + var modifyLastSourcePos = false; + // Current source map file and its index in the sources list + var sourceMapSourceIndex; + // Last recorded and encoded spans + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + // Source map data + var sourceMapData; + return { + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + changeEmitSourcePos: changeEmitSourcePos, + getText: getText, + getSourceMappingURL: getSourceMappingURL, + initialize: initialize, + reset: reset + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + // Current source map file and its index in the sources list + sourceMapSourceIndex = -1; + // Last recorded and encoded spans + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; + lastEncodedNameIndex = 0; + // Initialize source map data + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, + sourceMapDecodedMappings: [] + }; + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + } + function updateLastEncodedAndRecordedSpans() { + if (modifyLastSourcePos) { + // Reset the source pos + modifyLastSourcePos = false; + // Change Last recorded Map with last encoded emit line and character + lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; + lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; + // Pop sourceMapDecodedMappings to remove last entry + sourceMapData.sourceMapDecodedMappings.pop(); + // Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan + // If the list is empty which indicates that we are at the beginning of the file, + // we have to reset it to default value (same value when we first initialize sourceMapWriter) + lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? + sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : + defaultLastEncodedSourceMapSpan; + // TODO: Update lastEncodedNameIndex + // Since we dont support this any more, lets not worry about it right now. + // When we start supporting nameIndex, we will get back to this + // Change the encoded source map + var sourceMapMappings = sourceMapData.sourceMapMappings; + var lenthToSet = sourceMapMappings.length - 1; + for (; lenthToSet >= 0; lenthToSet--) { + var currentChar = sourceMapMappings.charAt(lenthToSet); + if (currentChar === ",") { + // Separator for the entry found + break; + } + if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { + // Last line separator found + break; + } + } + sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); + } + } + // Encoding for sourcemap span + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + // Line/Comma delimiters + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + // Emit comma to separate the entry + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + // Emit line delimiters + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + // 1. Relative Column 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + // 2. Relative sourceIndex + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + // 3. Relative sourceLine 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + // 4. Relative sourceColumn 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + // 5. Relative namePosition 0 based + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this"); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (pos === -1) { + return; + } + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + // Convert the location to be one-based. + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + 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.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + // Encode the last recordedSpan before assigning new + encodeLastRecordedSourceMapSpan(); + // New span + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + sourceIndex: sourceMapSourceIndex + }; + stopOverridingSpan = false; + } + else if (!stopOverridingSpan) { + // Take the new pos instead since there is no change in emittedLine and column since last location + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + updateLastEncodedAndRecordedSpans(); + } + function getStartPos(range) { + var rangeHasDecorators = !!range.decorators; + return range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1; + } + function emitStart(range) { + emitPos(getStartPos(range)); + } + function emitEnd(range, stopOverridingEnd) { + emitPos(range.end); + stopOverridingSpan = stopOverridingEnd; + } + function changeEmitSourcePos() { + ts.Debug.assert(!modifyLastSourcePos); + modifyLastSourcePos = true; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + // Add the file to tsFilePaths + // If sourceroot option: Use the relative path corresponding to the common directory path + // otherwise source locations relative to map file location + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + // The one that can be used from program to get the actual source file + sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + ts.createSourceMapWriter = createSourceMapWriter; + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + // Encode 5 bits at a time starting from least significant bits + var encodedStr = ""; + do { + var currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } +})(ts || (ts = {})); +/// +/* @internal */ +var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var diagnostics = []; - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); - emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; + var declarationDiagnostics = ts.createDiagnosticCollection(); + ts.forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); + return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName); + function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { + var declarationFilePath = _a.declarationFilePath; + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -28223,87 +30723,109 @@ var ts; var increaseIndent; var decreaseIndent; var writeTextOfNode; - var writer = createAndSetNewTextWriterWithSymbolWriter(); + var writer; + createAndSetNewTextWriterWithSymbolWriter(); var enclosingDeclaration; - var currentSourceFile; + var resultHasExternalModuleIndicator; + var currentText; + var currentLineMap; + var currentIdentifiers; + var isCurrentFileExternalModule; var reportedDeclarationError = false; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; + var noDeclare; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. // Collecting this separately because reference paths need to be first thing in the declaration file // and we could be collecting these paths from multiple files into single one with --out option var referencePathsOutput = ""; - if (root) { - // Emitting just a single file, so emit references in this file only + // Emit references corresponding to each file + var emittedReferencedFiles = []; + var addedGlobalFileReference = false; + var allSourcesModuleElementDeclarationEmitInfo = []; + ts.forEach(sourceFiles, function (sourceFile) { + // Dont emit for javascript file + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + // Check what references need to be added if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; - ts.forEach(root.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); - // All the references that are not going to be part of same file - if (referencedFile && ((referencedFile.flags & 4096 /* DeclarationFile */) || - ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || - !addedGlobalFileReference)) { - writeReferencePath(referencedFile); - if (!ts.isExternalModuleOrDeclarationFile(referencedFile)) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + // Emit reference in dts, if the file reference was not already emitted + if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { + // Add a reference to generated dts file, + // global file reference is added only + // - if it is not bundled emit (because otherwise it would be self reference) + // - and it is not already added + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } + emittedReferencedFiles.push(referencedFile); } }); } - emitSourceFile(root); + resultHasExternalModuleIndicator = false; + if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { + noDeclare = false; + emitSourceFile(sourceFile); + } + else if (ts.isExternalModule(sourceFile)) { + noDeclare = true; + write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); + writeLine(); + increaseIndent(); + emitSourceFile(sourceFile); + decreaseIndent(); + write("}"); + writeLine(); + } // create asynchronous output for the importDeclarations if (moduleElementDeclarationEmitInfo.length) { var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222 /* ImportDeclaration */); + if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { + ts.Debug.assert(aliasEmitInfo.node.kind === 226 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0); + ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + increaseIndent(); + } writeImportDeclaration(aliasEmitInfo.node); aliasEmitInfo.asynchronousOutput = writer.getText(); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + decreaseIndent(); + } } }); setWriter(oldWriter); + allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); + moduleElementDeclarationEmitInfo = []; } - } - else { - // Emit references corresponding to this file - var emittedReferencedFiles = []; - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) { - // Check what references need to be added - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - // If the reference file is a declaration file or an external module, emit that reference - if (referencedFile && (ts.isExternalModuleOrDeclarationFile(referencedFile) && - !ts.contains(emittedReferencedFiles, referencedFile))) { - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - emitSourceFile(sourceFile); - } - }); - } + if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + // in case if we didn't write any external module specifiers in .d.ts we need to emit something + // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. + write("export {};"); + writeLine(); + } + }); return { reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: moduleElementDeclarationEmitInfo, + moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput: referencePathsOutput }; function hasInternalAnnotation(range) { - var text = currentSourceFile.text; - var comment = text.substring(range.pos, range.end); + var comment = currentText.substring(range.pos, range.end); return comment.indexOf("@internal") >= 0; } function stripInternal(node) { if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { return; } @@ -28322,7 +30844,6 @@ var ts; writer.writeParameter = writer.write; writer.writeSymbol = writer.write; setWriter(writer); - return writer; } function setWriter(newWriter) { writer = newWriter; @@ -28336,10 +30857,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 211 /* VariableDeclaration */) { + if (declaration.kind === 215 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 225 /* NamedImports */ || declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 223 /* ImportClause */) { + else if (declaration.kind === 229 /* NamedImports */ || declaration.kind === 230 /* ImportSpecifier */ || declaration.kind === 227 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -28357,7 +30878,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 === 222 /* ImportDeclaration */) { + if (moduleElementEmitInfo.node.kind === 226 /* 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; @@ -28367,12 +30888,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 222 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 222 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -28382,23 +30903,23 @@ var ts; }); setWriter(oldWriter); } - function handleSymbolAccessibilityError(symbolAccesibilityResult) { - if (symbolAccesibilityResult.accessibility === 0 /* Accessible */) { + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { // write the aliases - if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccesibilityResult.aliasesToMakeVisible); + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); } } else { // Report error reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); if (errorInfo) { if (errorInfo.typeName) { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); } else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); } } } @@ -28408,7 +30929,8 @@ var ts; } function reportInaccessibleThisError() { if (errorNameNode) { - diagnostics.push(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { @@ -28461,10 +30983,10 @@ var ts; } function writeJsDocComments(declaration) { if (declaration) { - var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile); - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); + var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -28474,64 +30996,64 @@ var ts; function emitType(type) { switch (type.kind) { case 117 /* AnyKeyword */: - case 130 /* StringKeyword */: - case 128 /* NumberKeyword */: + case 131 /* StringKeyword */: + case 129 /* NumberKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 97 /* ThisKeyword */: - case 9 /* StringLiteral */: - return writeTextOfNode(currentSourceFile, type); - case 188 /* ExpressionWithTypeArguments */: + case 163 /* ThisType */: + case 164 /* StringLiteralType */: + return writeTextOfNode(currentText, type); + case 192 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); - case 151 /* TypeReference */: + case 153 /* TypeReference */: return emitTypeReference(type); - case 154 /* TypeQuery */: + case 156 /* TypeQuery */: return emitTypeQuery(type); - case 156 /* ArrayType */: + case 158 /* ArrayType */: return emitArrayType(type); - case 157 /* TupleType */: + case 159 /* TupleType */: return emitTupleType(type); - case 158 /* UnionType */: + case 160 /* UnionType */: return emitUnionType(type); - case 159 /* IntersectionType */: + case 161 /* IntersectionType */: return emitIntersectionType(type); - case 160 /* ParenthesizedType */: + case 162 /* ParenthesizedType */: return emitParenType(type); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: return emitSignatureDeclarationWithJsDocComments(type); - case 155 /* TypeLiteral */: + case 157 /* TypeLiteral */: return emitTypeLiteral(type); case 69 /* Identifier */: return emitEntityName(type); - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: return emitEntityName(type); - case 150 /* TypePredicate */: + case 152 /* TypePredicate */: return emitTypePredicate(type); } function writeEntityName(entityName) { if (entityName.kind === 69 /* Identifier */) { - writeTextOfNode(currentSourceFile, entityName); + writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 135 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 135 /* QualifiedName */ ? entityName.right : entityName.name; + var left = entityName.kind === 137 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 137 /* QualifiedName */ ? entityName.right : entityName.name; writeEntityName(left); write("."); - writeTextOfNode(currentSourceFile, right); + writeTextOfNode(currentText, right); } } function emitEntityName(entityName) { var visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 221 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + entityName.parent.kind === 225 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 166 /* PropertyAccessExpression */); + ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 170 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -28549,7 +31071,7 @@ var ts; } } function emitTypePredicate(type) { - writeTextOfNode(currentSourceFile, type.parameterName); + writeTextOfNode(currentText, type.parameterName); write(" is "); emitType(type.type); } @@ -28590,9 +31112,12 @@ var ts; } } function emitSourceFile(node) { - currentSourceFile = node; + currentText = node.text; + currentLineMap = ts.getLineStarts(node); + currentIdentifiers = node.identifiers; + isCurrentFileExternalModule = ts.isExternalModule(node); enclosingDeclaration = node; - ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true /* remove comments */); + ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true /* remove comments */); emitLines(node.statements); } // Return a temp variable name to be used in `export default` statements. @@ -28601,21 +31126,22 @@ var ts; // do not need to keep track of created temp names. function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) { + if (!ts.hasProperty(currentIdentifiers, baseName)) { return baseName; } var count = 0; while (true) { - var name_18 = baseName + "_" + (++count); - if (!ts.hasProperty(currentSourceFile.identifiers, name_18)) { - return name_18; + count++; + var name_20 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_20)) { + return name_20; } } } function emitExportAssignment(node) { if (node.expression.kind === 69 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentSourceFile, node.expression); + writeTextOfNode(currentText, node.expression); } else { // Expression @@ -28652,10 +31178,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 221 /* ImportEqualsDeclaration */ || - (node.parent.kind === 248 /* SourceFile */ && ts.isExternalModule(currentSourceFile))) { - var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248 /* SourceFile */) { + else if (node.kind === 225 /* ImportEqualsDeclaration */ || + (node.parent.kind === 252 /* SourceFile */ && isCurrentFileExternalModule)) { + var isVisible = void 0; + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 252 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -28665,7 +31191,7 @@ var ts; }); } else { - if (node.kind === 222 /* ImportDeclaration */) { + if (node.kind === 226 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -28683,23 +31209,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return writeVariableStatement(node); - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: return writeClassDeclaration(node); - case 216 /* TypeAliasDeclaration */: + case 220 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -28707,30 +31233,33 @@ var ts; } function emitModuleElementDeclarationFlags(node) { // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent === currentSourceFile) { + if (node.parent.kind === 252 /* SourceFile */) { // If the node is exported - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { write("export "); } if (node.flags & 512 /* Default */) { write("default "); } - else if (node.kind !== 215 /* InterfaceDeclaration */) { + else if (node.kind !== 219 /* InterfaceDeclaration */ && !noDeclare) { write("declare "); } } } - function emitClassMemberDeclarationFlags(node) { - if (node.flags & 16 /* Private */) { + function emitClassMemberDeclarationFlags(flags) { + if (flags & 8 /* Private */) { write("private "); } - else if (node.flags & 32 /* Protected */) { + else if (flags & 16 /* Protected */) { write("protected "); } - if (node.flags & 64 /* Static */) { + if (flags & 32 /* Static */) { write("static "); } - if (node.flags & 128 /* Abstract */) { + if (flags & 64 /* Readonly */) { + write("readonly "); + } + if (flags & 128 /* Abstract */) { write("abstract "); } } @@ -28738,11 +31267,11 @@ var ts; // note usage of writer. methods instead of aliases created, just to make sure we are using // correct writer especially to handle asynchronous alias writing emitJsDocComments(node); - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { write("export "); } write("import "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" = "); if (ts.isInternalModuleImportEqualsDeclaration(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); @@ -28750,11 +31279,11 @@ var ts; } else { write("require("); - writeTextOfNode(currentSourceFile, ts.getExternalModuleImportEqualsDeclarationExpression(node)); + emitExternalModuleSpecifier(node); write(");"); } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccesibilityResult) { + function getImportEntityNameVisibilityError(symbolAccessibilityResult) { return { diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -28764,7 +31293,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 224 /* NamespaceImport */) { + if (namedBindings.kind === 228 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -28773,28 +31302,24 @@ var ts; } } function writeImportDeclaration(node) { - if (!node.importClause && !(node.flags & 2 /* Export */)) { - // do not write non-exported import declarations that don't have import clauses - return; - } emitJsDocComments(node); - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { write("export "); } write("import "); if (node.importClause) { var currentWriterPos = writer.getTextPos(); if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentSourceFile, node.importClause.name); + writeTextOfNode(currentText, node.importClause.name); } if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { if (currentWriterPos !== writer.getTextPos()) { // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 228 /* NamespaceImport */) { write("* as "); - writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name); + writeTextOfNode(currentText, node.importClause.namedBindings.name); } else { write("{ "); @@ -28804,16 +31329,45 @@ var ts; } write(" from "); } - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); write(";"); writer.writeLine(); } + function emitExternalModuleSpecifier(parent) { + // emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations). + // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered + // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' + // so compiler will treat them as external modules. + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 222 /* ModuleDeclaration */; + var moduleSpecifier; + if (parent.kind === 225 /* ImportEqualsDeclaration */) { + var node = parent; + moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); + } + else if (parent.kind === 222 /* ModuleDeclaration */) { + moduleSpecifier = parent.name; + } + else { + var node = parent; + moduleSpecifier = node.moduleSpecifier; + } + if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); + if (moduleName) { + write("\""); + write(moduleName); + write("\""); + return; + } + } + writeTextOfNode(currentText, moduleSpecifier); + } function emitImportOrExportSpecifier(node) { if (node.propertyName) { - writeTextOfNode(currentSourceFile, node.propertyName); + writeTextOfNode(currentText, node.propertyName); write(" as "); } - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } function emitExportSpecifier(node) { emitImportOrExportSpecifier(node); @@ -28835,7 +31389,7 @@ var ts; } if (node.moduleSpecifier) { write(" from "); - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); } write(";"); writer.writeLine(); @@ -28843,17 +31397,27 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 65536 /* Namespace */) { - write("namespace "); + if (ts.isGlobalScopeAugmentation(node)) { + write("global "); } else { - write("module "); + if (node.flags & 4096 /* Namespace */) { + write("namespace "); + } + else { + write("module "); + } + if (ts.isExternalModuleAugmentation(node)) { + emitExternalModuleSpecifier(node); + } + else { + writeTextOfNode(currentText, node.name); + } } - writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 219 /* ModuleBlock */) { + while (node.body.kind !== 223 /* ModuleBlock */) { node = node.body; write("."); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; @@ -28872,14 +31436,14 @@ var ts; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("type "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); emitTypeParameters(node.typeParameters); write(" = "); emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); write(";"); writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult) { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -28894,7 +31458,7 @@ var ts; write("const "); } write("enum "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" {"); writeLine(); increaseIndent(); @@ -28905,7 +31469,7 @@ var ts; } function emitEnumMemberDeclaration(node) { emitJsDocComments(node); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); @@ -28915,61 +31479,61 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 143 /* MethodDeclaration */ && (node.parent.flags & 16 /* Private */); + return node.parent.kind === 145 /* MethodDeclaration */ && (node.parent.flags & 8 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { increaseIndent(); emitJsDocComments(node); decreaseIndent(); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); // 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 === 152 /* FunctionType */ || - node.parent.kind === 153 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 155 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 143 /* MethodDeclaration */ || - node.parent.kind === 142 /* MethodSignature */ || - node.parent.kind === 152 /* FunctionType */ || - node.parent.kind === 153 /* ConstructorType */ || - node.parent.kind === 147 /* CallSignature */ || - node.parent.kind === 148 /* ConstructSignature */); + if (node.parent.kind === 154 /* FunctionType */ || + node.parent.kind === 155 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 157 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 145 /* MethodDeclaration */ || + node.parent.kind === 144 /* MethodSignature */ || + node.parent.kind === 154 /* FunctionType */ || + node.parent.kind === 155 /* ConstructorType */ || + node.parent.kind === 149 /* CallSignature */ || + node.parent.kind === 150 /* ConstructSignature */); emitType(node.constraint); } else { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); } } - function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { + function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult) { // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 148 /* ConstructSignature */: + case 150 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 147 /* CallSignature */: + case 149 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - if (node.parent.flags & 64 /* Static */) { + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + if (node.parent.flags & 32 /* 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 === 214 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 218 /* 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 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -29000,10 +31564,10 @@ var ts; else if (!isImplementsList && node.expression.kind === 93 /* NullKeyword */) { write("null"); } - function getHeritageClauseVisibilityError(symbolAccesibilityResult) { + function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + if (node.parent.parent.kind === 218 /* 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 : @@ -29025,7 +31589,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 56 /* AccessibilityModifier */) { + if (param.flags & 28 /* AccessibilityModifier */) { emitPropertyDeclaration(param); } }); @@ -29037,7 +31601,7 @@ var ts; write("abstract "); } write("class "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -29060,7 +31624,7 @@ var ts; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("interface "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -29079,7 +31643,7 @@ var ts; return; } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node); + emitClassMemberDeclarationFlags(node.flags); emitVariableDeclaration(node); write(";"); writeLine(); @@ -29087,7 +31651,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 !== 211 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (node.kind !== 215 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -29095,53 +31659,53 @@ var ts; // If this node is a computed name, it can only be a symbol, because we've already skipped // it if it's not a well known symbol. In that case, the text of the name will be exactly // what we want, namely the name expression enclosed in brackets. - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); // If optional property emit ? - if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && ts.hasQuestionToken(node)) { + if ((node.kind === 143 /* PropertyDeclaration */ || node.kind === 142 /* PropertySignature */) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && node.parent.kind === 155 /* TypeLiteral */) { + if ((node.kind === 143 /* PropertyDeclaration */ || node.kind === 142 /* PropertySignature */) && node.parent.kind === 157 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 16 /* Private */)) { + else if (!(node.flags & 8 /* Private */)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 211 /* VariableDeclaration */) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 215 /* VariableDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) { + else if (node.kind === 143 /* PropertyDeclaration */ || node.kind === 142 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. - if (node.flags & 64 /* Static */) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + if (node.flags & 32 /* Static */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : 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 === 214 /* ClassDeclaration */) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + else if (node.parent.kind === 218 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; } else { // Interfaces cannot have types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; } } } - function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: node, @@ -29157,15 +31721,15 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 191 /* OmittedExpression */) { elements.push(element); } } emitCommaList(elements, emitBindingElement); } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: bindingElement, @@ -29177,7 +31741,7 @@ var ts; emitBindingPattern(bindingElement.name); } else { - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError); } } @@ -29220,14 +31784,14 @@ var ts; if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node); - writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 16 /* Private */)) { + emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : 64 /* Readonly */)); + writeTextOfNode(currentText, node.name); + if (!(node.flags & 8 /* Private */)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 145 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 147 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -29240,24 +31804,24 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 145 /* GetAccessor */ + return accessor.kind === 147 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type : undefined; } } - function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 146 /* SetAccessor */) { + if (accessorWithTypeAnnotation.kind === 148 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named - if (accessorWithTypeAnnotation.parent.flags & 64 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + if (accessorWithTypeAnnotation.parent.flags & 32 /* Static */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; } @@ -29269,16 +31833,16 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 64 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + if (accessorWithTypeAnnotation.flags & 32 /* Static */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; @@ -29299,21 +31863,21 @@ var ts; // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 217 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 143 /* MethodDeclaration */) { - emitClassMemberDeclarationFlags(node); + else if (node.kind === 145 /* MethodDeclaration */ || node.kind === 146 /* Constructor */) { + emitClassMemberDeclarationFlags(node.flags); } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 217 /* FunctionDeclaration */) { write("function "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } - else if (node.kind === 144 /* Constructor */) { + else if (node.kind === 146 /* Constructor */) { write("constructor"); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); if (ts.hasQuestionToken(node)) { write("?"); } @@ -29326,37 +31890,39 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { - // Construct signature or constructor type write new Signature - if (node.kind === 148 /* ConstructSignature */ || node.kind === 153 /* ConstructorType */) { - write("new "); - } - emitTypeParameters(node.typeParameters); - if (node.kind === 149 /* IndexSignature */) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + if (node.kind === 151 /* IndexSignature */) { + // Index signature can have readonly modifier + emitClassMemberDeclarationFlags(node.flags); write("["); } else { + // Construct signature or constructor type write new Signature + if (node.kind === 150 /* ConstructSignature */ || node.kind === 155 /* ConstructorType */) { + write("new "); + } + emitTypeParameters(node.typeParameters); write("("); } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; // Parameters emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 149 /* IndexSignature */) { + if (node.kind === 151 /* IndexSignature */) { write("]"); } else { write(")"); } // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 152 /* FunctionType */ || node.kind === 153 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 155 /* TypeLiteral */) { + var isFunctionTypeOrConstructorType = node.kind === 154 /* FunctionType */ || node.kind === 155 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 157 /* TypeLiteral */) { // Emit type literal signature return type only if specified if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 144 /* Constructor */ && !(node.flags & 16 /* Private */)) { + else if (node.kind !== 146 /* Constructor */ && !(node.flags & 8 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -29364,53 +31930,53 @@ var ts; write(";"); writeLine(); } - function getReturnTypeVisibilityError(symbolAccesibilityResult) { + function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 148 /* ConstructSignature */: + case 150 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.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 147 /* CallSignature */: + case 149 /* CallSignature */: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.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 149 /* IndexSignature */: + case 151 /* IndexSignature */: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.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 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - if (node.flags & 64 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + if (node.flags & 32 /* Static */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : 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 === 214 /* ClassDeclaration */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + else if (node.parent.kind === 218 /* ClassDeclaration */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; } else { // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 213 /* FunctionDeclaration */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + case 217 /* FunctionDeclaration */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; @@ -29437,71 +32003,71 @@ var ts; emitBindingPattern(node.name); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } if (resolver.isOptionalParameter(node)) { write("?"); } decreaseIndent(); - if (node.parent.kind === 152 /* FunctionType */ || - node.parent.kind === 153 /* ConstructorType */ || - node.parent.parent.kind === 155 /* TypeLiteral */) { + if (node.parent.kind === 154 /* FunctionType */ || + node.parent.kind === 155 /* ConstructorType */ || + node.parent.parent.kind === 157 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 16 /* Private */)) { + else if (!(node.parent.flags & 8 /* Private */)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } - function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: node, typeName: node.name } : undefined; } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 144 /* Constructor */: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + case 146 /* Constructor */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 148 /* ConstructSignature */: + case 150 /* ConstructSignature */: // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.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 147 /* CallSignature */: + case 149 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.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 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - if (node.parent.flags & 64 /* Static */) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + if (node.parent.flags & 32 /* Static */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : 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 === 214 /* ClassDeclaration */) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + else if (node.parent.parent.kind === 218 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? 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 213 /* FunctionDeclaration */: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + case 217 /* FunctionDeclaration */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; @@ -29511,12 +32077,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 === 161 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 165 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 162 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 166 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -29527,15 +32093,7 @@ var ts; } } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.kind === 187 /* OmittedExpression */) { + if (bindingElement.kind === 191 /* 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) @@ -29544,7 +32102,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 163 /* BindingElement */) { + else if (bindingElement.kind === 167 /* 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" @@ -29552,7 +32110,7 @@ var ts; // Example: // original: function foo({y: [a,b,c]}) {} // emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void; - writeTextOfNode(currentSourceFile, bindingElement.propertyName); + writeTextOfNode(currentText, bindingElement.propertyName); write(": "); } if (bindingElement.name) { @@ -29575,7 +32133,7 @@ var ts; if (bindingElement.dotDotDotToken) { write("..."); } - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); } } } @@ -29583,64 +32141,86 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 218 /* ModuleDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 215 /* InterfaceDeclaration */: - case 214 /* ClassDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: + case 217 /* FunctionDeclaration */: + case 222 /* ModuleDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 219 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 221 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: return emitExportDeclaration(node); - case 144 /* Constructor */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 146 /* Constructor */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return writeFunctionDeclaration(node); - case 148 /* ConstructSignature */: - case 147 /* CallSignature */: - case 149 /* IndexSignature */: + case 150 /* ConstructSignature */: + case 149 /* CallSignature */: + case 151 /* IndexSignature */: return emitSignatureDeclarationWithJsDocComments(node); - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: return emitAccessorDeclaration(node); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return emitPropertyDeclaration(node); - case 247 /* EnumMember */: + case 251 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return emitExportAssignment(node); - case 248 /* SourceFile */: + case 252 /* SourceFile */: return emitSourceFile(node); } } - function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 4096 /* DeclarationFile */ - ? referencedFile.fileName // Declaration file, use declaration file name - : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) - ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file - : ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; // Global out file - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ false); - referencePathsOutput += "/// " + newLine; + /** + * Adds the reference to referenced file, returns true if global file reference was emitted + * @param referencedFile + * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not + */ + function writeReferencePath(referencedFile, addBundledFileReference) { + var declFileName; + var addedBundledEmitReference = false; + if (ts.isDeclarationFile(referencedFile)) { + // Declaration file, use declaration file name + declFileName = referencedFile.fileName; + } + else { + // Get the declaration file path + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + } + if (declFileName) { + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + referencePathsOutput += "/// " + newLine; + } + return addedBundledEmitReference; + function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path + if (isBundledEmit && !addBundledFileReference) { + return; + } + ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); + declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; + addedBundledEmitReference = isBundledEmit; + } } } /* @internal */ - function writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); - // TODO(shkamat): Should we not write any declaration file if any of them can produce error, - // or should we just not write this file like we are doing now - if (!emitDeclarationResult.reportedDeclarationError) { + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; + if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } + return emitSkipped; function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { var appliedSyncOutputPos = 0; var declarationOutput = ""; @@ -29659,14 +32239,23 @@ var ts; ts.writeDeclarationFile = writeDeclarationFile; })(ts || (ts = {})); /// +/// /// /* @internal */ var ts; (function (ts) { - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); + function getResolvedExternalModuleName(host, file) { + return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || ts.isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; var Jump; (function (Jump) { Jump[Jump["Break"] = 2] = "Break"; @@ -29935,6 +32524,11 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); // 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 @@ -29945,41 +32539,19 @@ var ts; 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};"; // emit output for the __param helper function var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\n return new Promise(function (resolve, reject) {\n generator = generator.call(thisArg, _arguments);\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\n function onfulfill(value) { try { step(\"next\", value); } catch (e) { reject(e); } }\n function onreject(value) { try { step(\"throw\", value); } catch (e) { reject(e); } }\n function step(verb, value) {\n var result = generator[verb](value);\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\n }\n step(\"next\", void 0);\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || 0 /* ES3 */; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - var diagnostics = []; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emitSkipped = false; var newLine = host.getNewLine(); - var jsxDesugaring = host.getCompilerOptions().jsx !== 1 /* Preserve */; - var shouldEmitJsx = function (s) { return (s.languageVariant === 1 /* JSX */ && !jsxDesugaring); }; - if (targetSourceFile === undefined) { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - if (compilerOptions.outFile || compilerOptions.out) { - emitFile(compilerOptions.outFile || compilerOptions.out); - } - } - else { - // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) - if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) { - emitFile(compilerOptions.outFile || compilerOptions.out); - } - } - // Sort and make the unique list of diagnostics - diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics); + var emitJavaScript = createFileEmitter(); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { - emitSkipped: false, - diagnostics: diagnostics, + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), sourceMaps: sourceMapDataList }; function isUniqueLocalName(name, container) { @@ -30024,10 +32596,18 @@ var ts; } } } - function emitJavaScript(jsFilePath, root) { + function createFileEmitter() { var writer = ts.createTextWriter(newLine); var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); + var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; var currentSourceFile; + var currentText; + var currentLineMap; + var currentFileIdentifiers; + var renamedDependencies; + var isEs6Module; + var isCurrentFileExternalModule; // name of an exporter function if file is a System external module // System.register([...], function () {...}) // exporting in System modules looks like: @@ -30035,81 +32615,112 @@ var ts; // => // var x;... exporter("x", x = 1) var exportFunctionForFile; - var generatedNameSet = {}; - var nodeToGeneratedName = []; + var contextObjectForFile; + var generatedNameSet; + var nodeToGeneratedName; var computedPropertyNamesToGeneratedNames; + var decoratedClassAliases; var convertedLoopState; - var extendsEmitted = false; - var decorateEmitted = false; - var paramEmitted = false; - var awaiterEmitted = false; + var extendsEmitted; + var decorateEmitted; + var paramEmitted; + var awaiterEmitted; var tempFlags = 0; var tempVariables; var tempParameters; var externalImports; var exportSpecifiers; var exportEquals; - var hasExportStars; - /** Write emitted output to disk */ - var writeEmittedFiles = writeJavaScriptFile; + var hasExportStarsToExportValues; var detachedCommentsInfo; - var writeComment = ts.writeCommentRange; - /** Emit a node */ - var emit = emitNodeWithCommentsAndWithoutSourcemap; - /** Called just before starting emit of a node */ - var emitStart = function (node) { }; - /** Called once the emit of the node is done */ - var emitEnd = function (node) { }; - /** Emit the text for the given token that comes after startPos - * This by default writes the text provided with the given tokenKind - * but if optional emitFn callback is provided the text is emitted using the callback instead of default text - * @param tokenKind the kind of the token to search and emit - * @param startPos the position in the source to start searching for the token - * @param emitFn if given will be invoked to emit the text instead of actual token emit */ - var emitToken = emitTokenText; - /** Called to before starting the lexical scopes as in function/class in the emitted code because of node - * @param scopeDeclaration node that starts the lexical scope - * @param scopeName Optional name of this scope instead of deducing one from the declaration node */ - var scopeEmitStart = function (scopeDeclaration, scopeName) { }; - /** Called after coming out of the scope */ - var scopeEmitEnd = function () { }; /** Sourcemap data that will get encoded */ var sourceMapData; + /** Is the file being emitted into its own file */ + var isOwnFileEmit; /** If removeComments is true, no leading-comments needed to be emitted **/ var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; + var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; var moduleEmitDelegates = (_a = {}, - _a[5 /* ES6 */] = emitES6Module, - _a[2 /* AMD */] = emitAMDModule, - _a[4 /* System */] = emitSystemModule, - _a[3 /* UMD */] = emitUMDModule, - _a[1 /* CommonJS */] = emitCommonJSModule, + _a[ts.ModuleKind.ES6] = emitES6Module, + _a[ts.ModuleKind.AMD] = emitAMDModule, + _a[ts.ModuleKind.System] = emitSystemModule, + _a[ts.ModuleKind.UMD] = emitUMDModule, + _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, _a ); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - initializeEmitterWithSourceMaps(); - } - if (root) { + var bundleEmitDelegates = (_b = {}, + _b[ts.ModuleKind.ES6] = function () { }, + _b[ts.ModuleKind.AMD] = emitAMDModule, + _b[ts.ModuleKind.System] = emitSystemModule, + _b[ts.ModuleKind.UMD] = function () { }, + _b[ts.ModuleKind.CommonJS] = function () { }, + _b + ); + return doEmit; + function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + generatedNameSet = {}; + nodeToGeneratedName = []; + decoratedClassAliases = []; + isOwnFileEmit = !isBundledEmit; + // Emit helpers from all the files + if (isBundledEmit && modulekind) { + ts.forEach(sourceFiles, emitEmitHelpers); + } // Do not call emit directly. It does not set the currentSourceFile. - emitSourceFile(root); + ts.forEach(sourceFiles, emitSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# sourceMappingURL=" + sourceMappingURL); + } + writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM); + // reset the state + sourceMap.reset(); + writer.reset(); + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + exportFunctionForFile = undefined; + contextObjectForFile = undefined; + generatedNameSet = undefined; + nodeToGeneratedName = undefined; + decoratedClassAliases = undefined; + computedPropertyNamesToGeneratedNames = undefined; + convertedLoopState = undefined; + extendsEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + tempFlags = 0; + tempVariables = undefined; + tempParameters = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = undefined; + detachedCommentsInfo = undefined; + sourceMapData = undefined; + isEs6Module = false; + renamedDependencies = undefined; + isCurrentFileExternalModule = false; } - else { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!isExternalModuleOrDeclarationFile(sourceFile)) { - emitSourceFile(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM); - return; function emitSourceFile(sourceFile) { currentSourceFile = sourceFile; + currentText = sourceFile.text; + currentLineMap = ts.getLineStarts(sourceFile); exportFunctionForFile = undefined; - emit(sourceFile); + contextObjectForFile = undefined; + isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"]; + renamedDependencies = sourceFile.renamedDependencies; + currentFileIdentifiers = sourceFile.identifiers; + isCurrentFileExternalModule = ts.isExternalModule(sourceFile); + setSourceFile(sourceFile); + emitNodeWithCommentsAndWithoutSourcemap(sourceFile); } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentSourceFile.identifiers, name) && + !ts.hasProperty(currentFileIdentifiers, name) && !ts.hasProperty(generatedNameSet, name); } // Return the next available name in the pattern _a ... _z, _0, _1, ... @@ -30117,10 +32728,10 @@ var ts; // Note that names generated by makeTempVariableName and makeUniqueName will never conflict. function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_19 = flags === 268435456 /* _i */ ? "_i" : "_n"; - if (isUniqueName(name_19)) { + var name_21 = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name_21)) { tempFlags |= flags; - return name_19; + return name_21; } } while (true) { @@ -30128,9 +32739,9 @@ var ts; tempFlags++; // Skip over 'i' and 'n' if (count !== 8 && count !== 13) { - var name_20 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_20)) { - return name_20; + var name_22 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); + if (isUniqueName(name_22)) { + return name_22; } } } @@ -30174,17 +32785,17 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return makeUniqueName(node.text); - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: + case 222 /* ModuleDeclaration */: + case 221 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 222 /* ImportDeclaration */: - case 228 /* ExportDeclaration */: + case 226 /* ImportDeclaration */: + case 232 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 213 /* FunctionDeclaration */: - case 214 /* ClassDeclaration */: - case 227 /* ExportAssignment */: + case 217 /* FunctionDeclaration */: + case 218 /* ClassDeclaration */: + case 231 /* ExportAssignment */: return generateNameForExportDefault(); - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: return generateNameForClassExpression(); } } @@ -30192,338 +32803,15 @@ var ts; 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 - // Current source map file and its index in the sources list - var sourceMapSourceIndex = -1; - // Names and its index map - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; + /** Write emitted output to disk */ + function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark) { + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); } - // Last recorded and encoded spans - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Line/Comma delimiters - if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - // Emit comma to separate the entry - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - // Emit line delimiters - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - // 1. Relative Column 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - // 2. Relative sourceIndex - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - // 3. Relative sourceLine 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - // 4. Relative sourceColumn 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - // 5. Relative namePosition 0 based - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - // Add a new least significant bit that has the sign of the value. - // if negative number the least significant bit that gets added to the number has value 1 - // else least significant bit value that gets added is 0 - // eg. -1 changes to binary : 01 [1] => 3 - // +1 changes to binary : 01 [0] => 2 - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - // Encode 5 bits at a time starting from least significant bits - var encodedStr = ""; - do { - var currentDigit = inValue & 31; // 11111 - inValue = inValue >> 5; - if (inValue > 0) { - // There are still more digits to decode, set the msb (6th bit) - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); } - function recordSourceMapSpan(pos) { - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); - // Convert the location to be one-based. - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - 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.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - // Encode the last recordedSpan before assigning new - encodeLastRecordedSourceMapSpan(); - // New span - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - // Take the new pos instead since there is no change in emittedLine and column since last location - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - // Get the token pos after skipping to the token (ignoring the leading trivia) - recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - // Add the file to tsFilePaths - // If sourceroot option: Use the relative path corresponding to the common directory path - // otherwise source locations relative to map file location - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(node.fileName); - if (compilerOptions.inlineSources) { - if (!sourceMapData.sourceMapSourcesContent) { - sourceMapData.sourceMapSourcesContent = []; - } - sourceMapData.sourceMapSourcesContent.push(node.text); - } - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - // 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_21 = node.name; - if (!name_21 || name_21.kind !== 136 /* ComputedPropertyName */) { - scopeName = "." + scopeName; - } - scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - // The scope was already given a name use it - recordScopeNameStart(scopeName); - } - else if (node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */ || - node.kind === 143 /* MethodDeclaration */ || - node.kind === 142 /* MethodSignature */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */ || - node.kind === 218 /* ModuleDeclaration */ || - node.kind === 214 /* ClassDeclaration */ || - node.kind === 217 /* EnumDeclaration */) { - // Declaration and has associated name use it - if (node.name) { - var name_22 = node.name; - // For computed property names, the text will include the brackets - scopeName = name_22.kind === 136 /* ComputedPropertyName */ - ? ts.getTextOfNode(name_22) - : node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - // Block just use the name from upper level scope - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - ts.writeCommentRange(currentSourceFile, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) { - if (typeof JSON !== "undefined") { - var map_1 = { - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }; - if (sourcesContent !== undefined) { - map_1.sourcesContent = sourcesContent; - } - return JSON.stringify(map_1); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\" " + (sourcesContent !== undefined ? ",\"sourcesContent\":[" + serializeStringArray(sourcesContent) + "]" : "") + "}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) { - encodeLastRecordedSourceMapSpan(); - var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent); - sourceMapDataList.push(sourceMapData); - var sourceMapUrl; - if (compilerOptions.inlineSourceMap) { - // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.convertToBase64(sourceMapText); - sourceMapUrl = "//# sourceMappingURL=data:application/json;base64," + base64SourceMapText; - } - else { - // Write source map file - ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, /*writeByteOrderMark*/ false); - sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL; - } - // Write sourcemap url to the js file and write the js file - writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark); - } - // Initialize source map data - var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: undefined, - sourceMapDecodedMappings: [] - }; - // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the - // relative paths of the sources list in the sourcemap - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - // For modules or multiple emit files the mapRoot will have directory structure like the sources - // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - // The relative paths are relative to the common directory - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath - ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap - host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithSourceMap(node) { - if (node) { - if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node); - } - if (node.kind !== 248 /* SourceFile */) { - recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node); - } - } - } - function emitNodeWithCommentsAndWithSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithCommentsAndWithSourcemap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, writeByteOrderMark) { - ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark); } // Create a temporary variable with a unique unused name. function createTempVariable(flags) { @@ -30555,7 +32843,15 @@ var ts; write(";"); } } - function emitTokenText(tokenKind, startPos, emitFn) { + /** Emit the text for the given token that comes after startPos + * This by default writes the text provided with the given tokenKind + * but if optional emitFn callback is provided the text is emitted using the callback instead of default text + * @param tokenKind the kind of the token to search and emit + * @param startPos the position in the source to start searching for the token + * @param emitFn if given will be invoked to emit the text instead of actual token emit */ + function emitToken(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentText, startPos); + emitPos(tokenStartPos); var tokenString = ts.tokenToString(tokenKind); if (emitFn) { emitFn(); @@ -30563,7 +32859,9 @@ var ts; else { write(tokenString); } - return startPos + tokenString.length; + var tokenEndPos = tokenStartPos + tokenString.length; + emitPos(tokenEndPos); + return tokenEndPos; } function emitOptional(prefix, node) { if (node) { @@ -30580,11 +32878,6 @@ var ts; write(")"); } } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { ts.Debug.assert(nodes.length > 0); increaseIndent(); @@ -30657,7 +32950,7 @@ var ts; } function emitCommaList(nodes) { if (nodes) { - emitList(nodes, 0, nodes.length, /*multiline*/ false, /*trailingComma*/ false); + emitList(nodes, 0, nodes.length, /*multiLine*/ false, /*trailingComma*/ false); } } function emitLines(nodes) { @@ -30702,7 +32995,7 @@ var ts; // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (node.parent) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + return ts.getTextOfNodeFromSourceText(currentText, node); } // If we can't reach the original source text, use the canonical form if it's a number, // or an escaped quoted form of the original text if it's string-like. @@ -30729,8 +33022,8 @@ var ts; // Find original source text, since we need to emit the raw strings of the tagged template. // The raw strings contain the (escaped) strings of what the user wrote. // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + var text = ts.getTextOfNodeFromSourceText(currentText, node); + // text contains the original source, it will also contain quotes ("`"), dollar signs and braces ("${" and "}"), // thus we need to remove those characters. // First template piece starts with "`", others with "}" // Last template piece ends with "`", others with "${" @@ -30772,10 +33065,10 @@ var ts; write("("); emit(tempVariable); // Now we emit the expressions - if (node.template.kind === 183 /* TemplateExpression */) { + if (node.template.kind === 187 /* TemplateExpression */) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 181 /* BinaryExpression */ + var needsParens = templateSpan.expression.kind === 185 /* BinaryExpression */ && templateSpan.expression.operatorToken.kind === 24 /* CommaToken */; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -30810,7 +33103,7 @@ var ts; // ("abc" + 1) << (2 + "") // rather than // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== 172 /* ParenthesizedExpression */ + var needsParens = templateSpan.expression.kind !== 176 /* 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 @@ -30852,11 +33145,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: return parent.expression === template; - case 170 /* TaggedTemplateExpression */: - case 172 /* ParenthesizedExpression */: + case 174 /* TaggedTemplateExpression */: + case 176 /* ParenthesizedExpression */: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; @@ -30877,7 +33170,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 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: switch (expression.operatorToken.kind) { case 37 /* AsteriskToken */: case 39 /* SlashToken */: @@ -30889,8 +33182,8 @@ var ts; default: return -1 /* LessThan */; } - case 184 /* YieldExpression */: - case 182 /* ConditionalExpression */: + case 188 /* YieldExpression */: + case 186 /* ConditionalExpression */: return -1 /* LessThan */; default: return 1 /* GreaterThan */; @@ -30918,13 +33211,13 @@ var ts; /// these emit into an object literal property name, we don't need to be worried /// about keywords, just non-identifier characters function emitAttributeName(name) { - if (/[A-Za-z_]+[\w*]/.test(name.text)) { - write("\""); + if (/^[A-Za-z_]\w*$/.test(name.text)) { emit(name); - write("\""); } else { + write("\""); emit(name); + write("\""); } } /// Emit an name/value pair for an attribute (e.g. "x: 3") @@ -30940,7 +33233,7 @@ var ts; } function emitJsxElement(openingNode, children) { var syntheticReactRef = ts.createSynthesizedNode(69 /* Identifier */); - syntheticReactRef.text = "React"; + syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; syntheticReactRef.parent = openingNode; // Call React.createElement(tag, ... emitLeadingComments(openingNode); @@ -30957,38 +33250,38 @@ var ts; // Either emit one big object literal (no spread attribs), or // a call to React.__spread var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 239 /* JsxSpreadAttribute */; })) { + if (ts.forEach(attrs, function (attr) { return attr.kind === 243 /* JsxSpreadAttribute */; })) { emitExpressionIdentifier(syntheticReactRef); write(".__spread("); var haveOpenedObjectLiteral = false; - for (var i_1 = 0; i_1 < attrs.length; i_1++) { - if (attrs[i_1].kind === 239 /* JsxSpreadAttribute */) { + for (var i = 0; i < attrs.length; i++) { + if (attrs[i].kind === 243 /* JsxSpreadAttribute */) { // If this is the first argument, we need to emit a {} as the first argument - if (i_1 === 0) { + if (i === 0) { write("{}, "); } if (haveOpenedObjectLiteral) { write("}"); haveOpenedObjectLiteral = false; } - if (i_1 > 0) { + if (i > 0) { write(", "); } - emit(attrs[i_1].expression); + emit(attrs[i].expression); } else { - ts.Debug.assert(attrs[i_1].kind === 238 /* JsxAttribute */); + ts.Debug.assert(attrs[i].kind === 242 /* JsxAttribute */); if (haveOpenedObjectLiteral) { write(", "); } else { haveOpenedObjectLiteral = true; - if (i_1 > 0) { + if (i > 0) { write(", "); } write("{"); } - emitJsxAttribute(attrs[i_1]); + emitJsxAttribute(attrs[i]); } } if (haveOpenedObjectLiteral) @@ -30998,7 +33291,7 @@ var ts; else { // One object literal with all the attributes in them write("{"); - for (var i = 0; i < attrs.length; i++) { + for (var i = 0, n = attrs.length; i < n; i++) { if (i > 0) { write(", "); } @@ -31009,23 +33302,45 @@ var ts; } // Children if (children) { - for (var i = 0; i < children.length; i++) { - // Don't emit empty expressions - if (children[i].kind === 240 /* JsxExpression */ && !(children[i].expression)) { - continue; - } - // Don't emit empty strings - if (children[i].kind === 236 /* JsxText */) { - var text = getTextToEmit(children[i]); - if (text !== undefined) { - write(", \""); - write(text); - write("\""); + var firstChild = void 0; + var multipleEmittableChildren = false; + for (var i = 0, n = children.length; i < n; i++) { + var jsxChild = children[i]; + if (isJsxChildEmittable(jsxChild)) { + // we need to decide whether to emit in single line or multiple lines as indented list + // store firstChild reference, if we see another emittable child, then emit accordingly + if (!firstChild) { + write(", "); + firstChild = jsxChild; + } + else { + // more than one emittable child, emit indented list + if (!multipleEmittableChildren) { + multipleEmittableChildren = true; + increaseIndent(); + writeLine(); + emit(firstChild); + } + write(", "); + writeLine(); + emit(jsxChild); } } + } + if (multipleEmittableChildren) { + decreaseIndent(); + } + else if (firstChild) { + if (firstChild.kind !== 237 /* JsxElement */ && firstChild.kind !== 238 /* JsxSelfClosingElement */) { + emit(firstChild); + } else { - write(", "); - emit(children[i]); + // If the only child is jsx element, put it on a new indented line + increaseIndent(); + writeLine(); + emit(firstChild); + writeLine(); + decreaseIndent(); } } } @@ -31033,11 +33348,11 @@ var ts; write(")"); // closes "React.createElement(" emitTrailingComments(openingNode); } - if (node.kind === 233 /* JsxElement */) { + if (node.kind === 237 /* JsxElement */) { emitJsxElement(node.openingElement, node.children); } else { - ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(node.kind === 238 /* JsxSelfClosingElement */); emitJsxElement(node); } } @@ -31059,11 +33374,11 @@ var ts; if (i > 0) { write(" "); } - if (attribs[i].kind === 239 /* JsxSpreadAttribute */) { + if (attribs[i].kind === 243 /* JsxSpreadAttribute */) { emitJsxSpreadAttribute(attribs[i]); } else { - ts.Debug.assert(attribs[i].kind === 238 /* JsxAttribute */); + ts.Debug.assert(attribs[i].kind === 242 /* JsxAttribute */); emitJsxAttribute(attribs[i]); } } @@ -31071,11 +33386,11 @@ var ts; function emitJsxOpeningOrSelfClosingElement(node) { write("<"); emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 234 /* JsxSelfClosingElement */)) { + if (node.attributes.length > 0 || (node.kind === 238 /* JsxSelfClosingElement */)) { write(" "); } emitAttributes(node.attributes); - if (node.kind === 234 /* JsxSelfClosingElement */) { + if (node.kind === 238 /* JsxSelfClosingElement */) { write("/>"); } else { @@ -31094,11 +33409,11 @@ var ts; } emitJsxClosingElement(node.closingElement); } - if (node.kind === 233 /* JsxElement */) { + if (node.kind === 237 /* JsxElement */) { emitJsxElement(node); } else { - ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(node.kind === 238 /* JsxSelfClosingElement */); emitJsxOpeningOrSelfClosingElement(node); } } @@ -31106,11 +33421,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 !== 163 /* BindingElement */); + ts.Debug.assert(node.kind !== 167 /* BindingElement */); if (node.kind === 9 /* StringLiteral */) { emitLiteral(node); } - else if (node.kind === 136 /* ComputedPropertyName */) { + else if (node.kind === 138 /* 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: @@ -31146,7 +33461,7 @@ var ts; write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } write("\""); } @@ -31154,75 +33469,72 @@ var ts; function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 164 /* ArrayLiteralExpression */: - case 189 /* AsExpression */: - case 181 /* BinaryExpression */: - case 168 /* CallExpression */: - case 241 /* CaseClause */: - case 136 /* ComputedPropertyName */: - case 182 /* ConditionalExpression */: - case 139 /* Decorator */: - case 175 /* DeleteExpression */: - case 197 /* DoStatement */: - case 167 /* ElementAccessExpression */: - case 227 /* ExportAssignment */: - case 195 /* ExpressionStatement */: - case 188 /* ExpressionWithTypeArguments */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 196 /* IfStatement */: - case 234 /* JsxSelfClosingElement */: - case 235 /* JsxOpeningElement */: - case 239 /* JsxSpreadAttribute */: - case 240 /* JsxExpression */: - case 169 /* NewExpression */: - case 172 /* ParenthesizedExpression */: - case 180 /* PostfixUnaryExpression */: - case 179 /* PrefixUnaryExpression */: - case 204 /* ReturnStatement */: - case 246 /* ShorthandPropertyAssignment */: - case 185 /* SpreadElementExpression */: - case 206 /* SwitchStatement */: - case 170 /* TaggedTemplateExpression */: - case 190 /* TemplateSpan */: - case 208 /* ThrowStatement */: - case 171 /* TypeAssertionExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 184 /* YieldExpression */: + case 168 /* ArrayLiteralExpression */: + case 193 /* AsExpression */: + case 185 /* BinaryExpression */: + case 172 /* CallExpression */: + case 245 /* CaseClause */: + case 138 /* ComputedPropertyName */: + case 186 /* ConditionalExpression */: + case 141 /* Decorator */: + case 179 /* DeleteExpression */: + case 201 /* DoStatement */: + case 171 /* ElementAccessExpression */: + case 231 /* ExportAssignment */: + case 199 /* ExpressionStatement */: + case 192 /* ExpressionWithTypeArguments */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 200 /* IfStatement */: + case 241 /* JsxClosingElement */: + case 238 /* JsxSelfClosingElement */: + case 239 /* JsxOpeningElement */: + case 243 /* JsxSpreadAttribute */: + case 244 /* JsxExpression */: + case 173 /* NewExpression */: + case 176 /* ParenthesizedExpression */: + case 184 /* PostfixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: + case 208 /* ReturnStatement */: + case 250 /* ShorthandPropertyAssignment */: + case 189 /* SpreadElementExpression */: + case 210 /* SwitchStatement */: + case 174 /* TaggedTemplateExpression */: + case 194 /* TemplateSpan */: + case 212 /* ThrowStatement */: + case 175 /* TypeAssertionExpression */: + case 180 /* TypeOfExpression */: + case 181 /* VoidExpression */: + case 202 /* WhileStatement */: + case 209 /* WithStatement */: + case 188 /* YieldExpression */: return true; - case 163 /* BindingElement */: - case 247 /* EnumMember */: - case 138 /* Parameter */: - case 245 /* PropertyAssignment */: - case 141 /* PropertyDeclaration */: - case 211 /* VariableDeclaration */: + case 167 /* BindingElement */: + case 251 /* EnumMember */: + case 140 /* Parameter */: + case 249 /* PropertyAssignment */: + case 143 /* PropertyDeclaration */: + case 215 /* VariableDeclaration */: return parent.initializer === node; - case 166 /* PropertyAccessExpression */: + case 170 /* PropertyAccessExpression */: return parent.expression === node; - case 174 /* ArrowFunction */: - case 173 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 177 /* FunctionExpression */: return parent.body === node; - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return parent.moduleReference === node; - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: return parent.left === node; } return false; } function emitExpressionIdentifier(node) { - if (resolver.getNodeCheckFlags(node) & 2048 /* LexicalArguments */) { - write("_arguments"); - return; - } var container = resolver.getReferencedExportContainer(node); if (container) { - if (container.kind === 248 /* SourceFile */) { + if (container.kind === 252 /* SourceFile */) { // Identifier references module export - if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) { + if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { write("exports."); } } @@ -31233,20 +33545,20 @@ var ts; } } else { - if (modulekind !== 5 /* ES6 */) { + if (modulekind !== ts.ModuleKind.ES6) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { - if (declaration.kind === 223 /* ImportClause */) { + if (declaration.kind === 227 /* ImportClause */) { // Identifier references default import write(getGeneratedNameForNode(declaration.parent)); write(languageVersion === 0 /* ES3 */ ? "[\"default\"]" : ".default"); return; } - else if (declaration.kind === 226 /* ImportSpecifier */) { + else if (declaration.kind === 230 /* ImportSpecifier */) { // Identifier references named import write(getGeneratedNameForNode(declaration.parent.parent.parent)); var name_23 = declaration.propertyName || declaration.name; - var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_23); + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_23); if (languageVersion === 0 /* ES3 */ && identifier === "default") { write("[\"default\"]"); } @@ -31258,30 +33570,43 @@ var ts; } } } - if (languageVersion !== 2 /* ES6 */) { - var declaration = resolver.getReferencedNestedRedeclaration(node); + if (languageVersion < 2 /* ES6 */) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration) { write(getGeneratedNameForNode(declaration.name)); return; } } + else if (resolver.getNodeCheckFlags(node) & 1048576 /* BodyScopedClassBinding */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = decoratedClassAliases[ts.getNodeId(declaration)]; + if (classAlias !== undefined) { + write(classAlias); + return; + } + } + } } if (ts.nodeIsSynthesized(node)) { write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } } - function isNameOfNestedRedeclaration(node) { + function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node) { if (languageVersion < 2 /* ES6 */) { - var parent_6 = node.parent; - switch (parent_6.kind) { - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 211 /* VariableDeclaration */: - return parent_6.name === node && resolver.isNestedRedeclaration(parent_6); + var parent_8 = node.parent; + switch (parent_8.kind) { + case 167 /* BindingElement */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 215 /* VariableDeclaration */: + return parent_8.name === node && resolver.isDeclarationWithCollidingName(parent_8); } } return false; @@ -31301,20 +33626,23 @@ var ts; else if (isExpressionIdentifier(node)) { emitExpressionIdentifier(node); } - else if (isNameOfNestedRedeclaration(node)) { + else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { write(getGeneratedNameForNode(node)); } else if (ts.nodeIsSynthesized(node)) { write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } } function emitThis(node) { if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { write("_this"); } + else if (convertedLoopState) { + write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); + } else { write("this"); } @@ -31388,10 +33716,10 @@ var ts; } } function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 181 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { + if (node.parent.kind === 185 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { return true; } - else if (node.parent.kind === 182 /* ConditionalExpression */ && node.parent.condition === node) { + else if (node.parent.kind === 186 /* ConditionalExpression */ && node.parent.condition === node) { return true; } return false; @@ -31399,11 +33727,11 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 69 /* Identifier */: - case 164 /* ArrayLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 172 /* ParenthesizedExpression */: + case 168 /* ArrayLiteralExpression */: + case 170 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: + case 172 /* CallExpression */: + case 176 /* 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; @@ -31423,17 +33751,17 @@ var ts; write(", "); } var e = elements[pos]; - if (e.kind === 185 /* SpreadElementExpression */) { + if (e.kind === 189 /* SpreadElementExpression */) { e = e.expression; emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164 /* ArrayLiteralExpression */) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 168 /* ArrayLiteralExpression */) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 185 /* SpreadElementExpression */) { + while (i < length && elements[i].kind !== 189 /* SpreadElementExpression */) { i++; } write("["); @@ -31456,7 +33784,7 @@ var ts; } } function isSpreadElementExpression(node) { - return node.kind === 185 /* SpreadElementExpression */; + return node.kind === 189 /* SpreadElementExpression */; } function emitArrayLiteral(node) { var elements = node.elements; @@ -31465,11 +33793,11 @@ var ts; } else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) { write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces:*/ false); + emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces*/ false); write("]"); } else { - emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 1024 /* MultiLine */) !== 0, + emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ node.multiLine, /*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true); } } @@ -31485,10 +33813,10 @@ var ts; // then try to preserve the original shape of the object literal. // Otherwise just try to preserve the formatting. if (numElements === properties.length) { - emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= 1 /* ES5 */, /* spacesBetweenBraces */ true); + emitLinePreservingList(node, properties, /*allowTrailingComma*/ languageVersion >= 1 /* ES5 */, /*spacesBetweenBraces*/ true); } else { - var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; + var multiLine = node.multiLine; if (!multiLine) { write(" "); } @@ -31507,7 +33835,7 @@ var ts; write("}"); } function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; + var multiLine = node.multiLine; var properties = node.properties; write("("); if (multiLine) { @@ -31526,7 +33854,7 @@ var ts; writeComma(); var property = properties[i]; emitStart(property); - if (property.kind === 145 /* GetAccessor */ || property.kind === 146 /* SetAccessor */) { + if (property.kind === 147 /* GetAccessor */ || property.kind === 148 /* SetAccessor */) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { @@ -31578,13 +33906,13 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 245 /* PropertyAssignment */) { + if (property.kind === 249 /* PropertyAssignment */) { emit(property.initializer); } - else if (property.kind === 246 /* ShorthandPropertyAssignment */) { + else if (property.kind === 250 /* ShorthandPropertyAssignment */) { emitExpressionIdentifier(property.name); } - else if (property.kind === 143 /* MethodDeclaration */) { + else if (property.kind === 145 /* MethodDeclaration */) { emitFunctionDeclaration(property); } else { @@ -31618,7 +33946,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 === 136 /* ComputedPropertyName */) { + if (properties[i].name.kind === 138 /* ComputedPropertyName */) { numInitialNonComputedProperties = i; break; } @@ -31634,21 +33962,21 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(181 /* BinaryExpression */, startsOnNewLine); + var result = ts.createSynthesizedNode(185 /* BinaryExpression */, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(166 /* PropertyAccessExpression */); + var result = ts.createSynthesizedNode(170 /* PropertyAccessExpression */); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(21 /* DotToken */); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(167 /* ElementAccessExpression */); + var result = ts.createSynthesizedNode(171 /* ElementAccessExpression */); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; @@ -31656,7 +33984,7 @@ var ts; 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 === 171 /* TypeAssertionExpression */ || expr.kind === 189 /* AsExpression */) { + while (expr.kind === 175 /* TypeAssertionExpression */ || expr.kind === 193 /* AsExpression */) { expr = expr.expression; } // isLeftHandSideExpression is almost the correct criterion for when it is not necessary @@ -31668,11 +33996,11 @@ var ts; // 1.x -> not the same as (1).x // if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 169 /* NewExpression */ && + expr.kind !== 173 /* NewExpression */ && expr.kind !== 8 /* NumericLiteral */) { return expr; } - var node = ts.createSynthesizedNode(172 /* ParenthesizedExpression */); + var node = ts.createSynthesizedNode(176 /* ParenthesizedExpression */); node.expression = expr; return node; } @@ -31707,12 +34035,12 @@ var ts; // Return true if identifier resolves to an exported member of a namespace function isNamespaceExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 248 /* SourceFile */; + return container && container.kind !== 252 /* SourceFile */; } function emitShorthandPropertyAssignment(node) { // 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); + writeTextOfNode(currentText, 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 { @@ -31722,7 +34050,7 @@ var ts; // let obj = { y }; // } // Here we need to emit obj = { y : m.y } regardless of the output target. - if (languageVersion < 2 /* ES6 */ || isNamespaceExportReference(node.name)) { + if (modulekind !== ts.ModuleKind.ES6 || isNamespaceExportReference(node.name)) { // Emit identifier as an identifier write(": "); emit(node.name); @@ -31737,7 +34065,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 166 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 170 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -31748,7 +34076,7 @@ var ts; if (compilerOptions.isolatedModules) { return undefined; } - return node.kind === 166 /* PropertyAccessExpression */ || node.kind === 167 /* ElementAccessExpression */ + return node.kind === 170 /* PropertyAccessExpression */ || node.kind === 171 /* ElementAccessExpression */ ? resolver.getConstantValue(node) : undefined; } @@ -31775,15 +34103,23 @@ var ts; if (tryEmitConstantValue(node)) { return; } + if (languageVersion === 2 /* ES6 */ && + node.expression.kind === 95 /* SuperKeyword */ && + isInAsyncMethodWithSuperInES6(node)) { + var name_25 = ts.createSynthesizedNode(9 /* StringLiteral */); + name_25.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_25); + return; + } emit(node.expression); var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); // 1 .toString is a valid property access, emit a space after the literal // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal - var shouldEmitSpace; + var shouldEmitSpace = false; if (!indentedBeforeDot) { if (node.expression.kind === 8 /* NumericLiteral */) { // check if numeric literal was originally written with a dot - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); + var text = ts.getTextOfNodeFromSourceText(currentText, node.expression); shouldEmitSpace = text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; } else { @@ -31837,25 +34173,34 @@ var ts; } emitExpressionIdentifier(node); break; - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: emitQualifiedNameAsExpression(node, useFallback); break; + default: + emitNodeWithoutSourceMap(node); + break; } } function emitIndexedAccess(node) { if (tryEmitConstantValue(node)) { return; } + if (languageVersion === 2 /* ES6 */ && + node.expression.kind === 95 /* SuperKeyword */ && + isInAsyncMethodWithSuperInES6(node)) { + emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression); + return; + } emit(node.expression); write("["); emit(node.argumentExpression); write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 185 /* SpreadElementExpression */; }); + return ts.forEach(elements, function (e) { return e.kind === 189 /* SpreadElementExpression */; }); } function skipParentheses(node) { - while (node.kind === 172 /* ParenthesizedExpression */ || node.kind === 171 /* TypeAssertionExpression */ || node.kind === 189 /* AsExpression */) { + while (node.kind === 176 /* ParenthesizedExpression */ || node.kind === 175 /* TypeAssertionExpression */ || node.kind === 193 /* AsExpression */) { node = node.expression; } return node; @@ -31876,13 +34221,13 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 166 /* PropertyAccessExpression */) { + if (expr.kind === 170 /* PropertyAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 167 /* ElementAccessExpression */) { + else if (expr.kind === 171 /* ElementAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("["); @@ -31915,23 +34260,42 @@ var ts; emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ true); write(")"); } + function isInAsyncMethodWithSuperInES6(node) { + if (languageVersion === 2 /* ES6 */) { + var container = ts.getSuperContainer(node, /*includeFunctions*/ false); + if (container && resolver.getNodeCheckFlags(container) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */)) { + return true; + } + } + return false; + } + function emitSuperAccessInAsyncMethod(superNode, argumentExpression) { + var container = ts.getSuperContainer(superNode, /*includeFunctions*/ false); + var isSuperBinding = resolver.getNodeCheckFlags(container) & 4096 /* AsyncMethodWithSuperBinding */; + write("_super("); + emit(argumentExpression); + write(isSuperBinding ? ").value" : ")"); + } function emitCallExpression(node) { if (languageVersion < 2 /* ES6 */ && hasSpreadElement(node.arguments)) { emitCallWithSpread(node); return; } + var expression = node.expression; var superCall = false; - if (node.expression.kind === 95 /* SuperKeyword */) { - emitSuper(node.expression); + var isAsyncMethodWithSuper = false; + if (expression.kind === 95 /* SuperKeyword */) { + emitSuper(expression); superCall = true; } else { - emit(node.expression); - superCall = node.expression.kind === 166 /* PropertyAccessExpression */ && node.expression.expression.kind === 95 /* SuperKeyword */; + superCall = ts.isSuperPropertyOrElementAccess(expression); + isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node); + emit(expression); } - if (superCall && languageVersion < 2 /* ES6 */) { + if (superCall && (languageVersion < 2 /* ES6 */ || isAsyncMethodWithSuper)) { write(".call("); - emitThis(node.expression); + emitThis(expression); if (node.arguments.length) { write(", "); emitCommaList(node.arguments); @@ -31969,7 +34333,7 @@ var ts; write(".bind.apply("); emit(target); write(", [void 0].concat("); - emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiline*/ false, /*trailingComma*/ false, /*useConcat*/ false); + emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ false); write(")))"); write("()"); } @@ -31996,12 +34360,12 @@ var ts; // 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 !== 174 /* ArrowFunction */) { - if (node.expression.kind === 171 /* TypeAssertionExpression */ || node.expression.kind === 189 /* AsExpression */) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 178 /* ArrowFunction */) { + if (node.expression.kind === 175 /* TypeAssertionExpression */ || node.expression.kind === 193 /* AsExpression */) { var operand = node.expression.expression; // Make sure we consider all nested cast expressions, e.g.: // (-A).x; - while (operand.kind === 171 /* TypeAssertionExpression */ || operand.kind === 189 /* AsExpression */) { + while (operand.kind === 175 /* TypeAssertionExpression */ || operand.kind === 193 /* AsExpression */) { operand = operand.expression; } // We have an expression of the form: (SubExpr) @@ -32012,15 +34376,15 @@ 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 !== 179 /* PrefixUnaryExpression */ && - operand.kind !== 177 /* VoidExpression */ && - operand.kind !== 176 /* TypeOfExpression */ && - operand.kind !== 175 /* DeleteExpression */ && - operand.kind !== 180 /* PostfixUnaryExpression */ && - operand.kind !== 169 /* NewExpression */ && - !(operand.kind === 168 /* CallExpression */ && node.parent.kind === 169 /* NewExpression */) && - !(operand.kind === 173 /* FunctionExpression */ && node.parent.kind === 168 /* CallExpression */) && - !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 166 /* PropertyAccessExpression */)) { + if (operand.kind !== 183 /* PrefixUnaryExpression */ && + operand.kind !== 181 /* VoidExpression */ && + operand.kind !== 180 /* TypeOfExpression */ && + operand.kind !== 179 /* DeleteExpression */ && + operand.kind !== 184 /* PostfixUnaryExpression */ && + operand.kind !== 173 /* NewExpression */ && + !(operand.kind === 172 /* CallExpression */ && node.parent.kind === 173 /* NewExpression */) && + !(operand.kind === 177 /* FunctionExpression */ && node.parent.kind === 172 /* CallExpression */) && + !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 170 /* PropertyAccessExpression */)) { emit(operand); return; } @@ -32049,14 +34413,15 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 /* VariableDeclaration */ || node.parent.kind === 163 /* BindingElement */); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 215 /* VariableDeclaration */ || node.parent.kind === 167 /* BindingElement */); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, /*isExported*/ true); } function emitPrefixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + var exportChanged = (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) && + isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); if (exportChanged) { // emit // ++x @@ -32079,7 +34444,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 === 179 /* PrefixUnaryExpression */) { + if (node.operand.kind === 183 /* PrefixUnaryExpression */) { var operand = node.operand; if (node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) { write(" "); @@ -32133,12 +34498,12 @@ var ts; if (!node || !isCurrentFileSystemExternalModule()) { return false; } - var current = node; + var current = ts.getRootDeclaration(node).parent; while (current) { - if (current.kind === 248 /* SourceFile */) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 2 /* Export */) !== 0); + if (current.kind === 252 /* SourceFile */) { + return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 219 /* ModuleBlock */) { + else if (ts.isDeclaration(current)) { return false; } else { @@ -32153,19 +34518,19 @@ var ts; function emitExponentiationOperator(node) { var leftHandSideExpression = node.left; if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { - var synthesizedLHS; + var synthesizedLHS = void 0; var shouldEmitParentheses = false; if (ts.isElementAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(167 /* ElementAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false); + synthesizedLHS = ts.createSynthesizedNode(171 /* ElementAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ && leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) { var tempArgumentExpression = createAndRecordTempVariable(268435456 /* _i */); synthesizedLHS.argumentExpression = tempArgumentExpression; - emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true); + emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true, leftHandSideExpression.expression); } else { synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; @@ -32175,8 +34540,8 @@ var ts; else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(166 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false); + synthesizedLHS = ts.createSynthesizedNode(170 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; @@ -32203,8 +34568,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 56 /* EqualsToken */ && - (node.left.kind === 165 /* ObjectLiteralExpression */ || node.left.kind === 164 /* ArrayLiteralExpression */)) { - emitDestructuring(node, node.parent.kind === 195 /* ExpressionStatement */); + (node.left.kind === 169 /* ObjectLiteralExpression */ || node.left.kind === 168 /* ArrayLiteralExpression */)) { + emitDestructuring(node, node.parent.kind === 199 /* ExpressionStatement */); } else { var exportChanged = node.operatorToken.kind >= 56 /* FirstAssignment */ && @@ -32269,7 +34634,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 192 /* Block */) { + if (node && node.kind === 196 /* Block */) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -32283,22 +34648,20 @@ var ts; } emitToken(15 /* OpenBraceToken */, node.pos); increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 219 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 218 /* ModuleDeclaration */); + if (node.kind === 223 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 222 /* ModuleDeclaration */); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 219 /* ModuleBlock */) { + if (node.kind === 223 /* ModuleBlock */) { emitTempDeclarations(/*newLine*/ true); } decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.statements.end); - scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 192 /* Block */) { + if (node.kind === 196 /* Block */) { write(" "); emit(node); } @@ -32310,7 +34673,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 174 /* ArrowFunction */); + emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 178 /* ArrowFunction */); write(";"); } function emitIfStatement(node) { @@ -32323,7 +34686,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(80 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 196 /* IfStatement */) { + if (node.elseStatement.kind === 200 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -32338,12 +34701,12 @@ var ts; function emitDoStatementWorker(node, loop) { write("do"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } - if (node.statement.kind === 192 /* Block */) { + if (node.statement.kind === 196 /* Block */) { write(" "); } else { @@ -32361,10 +34724,10 @@ var ts; emit(node.expression); write(")"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } /** @@ -32372,13 +34735,13 @@ var ts; * 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) { + function tryEmitStartOfVariableDeclarationList(decl) { if (shouldHoistVariable(decl, /*checkIfSourceFileLevelDecl*/ true)) { // variables in variable declaration list were already hoisted return false; } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576 /* BlockScoped */) === 0) { - // we are inside a converted loop - this can only happen in downlevel scenarios + if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 3072 /* BlockScoped */) === 0) { + // we are inside a converted loop - this can only happen in downlevel scenarios // record names for all variable declarations for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { var varDecl = _b[_a]; @@ -32386,32 +34749,23 @@ var ts; } return false; } - var tokenKind = 102 /* VarKeyword */; + emitStart(decl); if (decl && languageVersion >= 2 /* ES6 */) { if (ts.isLet(decl)) { - tokenKind = 108 /* LetKeyword */; + write("let "); } else if (ts.isConst(decl)) { - tokenKind = 74 /* ConstKeyword */; + write("const "); + } + else { + write("var "); } - } - if (startPos !== undefined) { - emitToken(tokenKind, startPos); - write(" "); } else { - switch (tokenKind) { - case 102 /* VarKeyword */: - write("var "); - break; - case 108 /* LetKeyword */: - write("let "); - break; - case 74 /* ConstKeyword */: - write("const "); - break; - } + write("var "); } + // Note here we specifically dont emit end so that if we are going to emit binding pattern + // we can alter the source map correctly return true; } function emitVariableDeclarationListSkippingUninitializedEntries(list) { @@ -32433,7 +34787,7 @@ var ts; } function shouldConvertLoopBody(node) { return languageVersion < 2 /* ES6 */ && - (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithBlockScopedBindingCapturedInFunction */) !== 0; + (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } function emitLoop(node, loopEmitter) { var shouldConvert = shouldConvertLoopBody(node); @@ -32442,7 +34796,7 @@ var ts; } else { var loop = convertLoopBody(node); - if (node.parent.kind === 207 /* LabeledStatement */) { + if (node.parent.kind === 211 /* LabeledStatement */) { // if parent of the loop was labeled statement - attach the label to loop skipping converted loop body emitLabelAndColon(node.parent); } @@ -32453,34 +34807,31 @@ var ts; var functionName = makeUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 216 /* VariableDeclarationList */) { loopInitializer = node.initializer; } break; } var loopParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 24576 /* BlockScoped */)) { + var loopOutParameters; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3072 /* BlockScoped */)) { // if loop initializer contains block scoped variables - they should be passed to converted loop body as parameters loopParameters = []; for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { var varDeclaration = _b[_a]; - collectNames(varDeclaration.name); + processVariableDeclaration(varDeclaration.name); } } - var bodyIsBlock = node.statement.kind === 192 /* Block */; + var bodyIsBlock = node.statement.kind === 196 /* Block */; var paramList = loopParameters ? loopParameters.join(", ") : ""; writeLine(); write("var " + functionName + " = function(" + paramList + ")"); - if (!bodyIsBlock) { - write(" {"); - writeLine(); - increaseIndent(); - } var convertedOuterLoopState = convertedLoopState; - convertedLoopState = {}; + convertedLoopState = { loopOutParameters: loopOutParameters }; if (convertedOuterLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through @@ -32489,20 +34840,45 @@ var ts; // use the same name in all nested loops convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; } + if (convertedOuterLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.thisName = convertedOuterLoopState.thisName; + } if (convertedOuterLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; } } - emitEmbeddedStatement(node.statement); - if (!bodyIsBlock) { - decreaseIndent(); - writeLine(); - write("}"); - } - write(";"); + write(" {"); writeLine(); + increaseIndent(); + if (bodyIsBlock) { + emitLines(node.statement.statements); + } + else { + emit(node.statement); + } + writeLine(); + // end of loop body -> copy out parameter + copyLoopOutParameters(convertedLoopState, 1 /* ToOutParameter */, /*emitAsStatements*/ true); + decreaseIndent(); + writeLine(); + write("};"); + writeLine(); + if (loopOutParameters) { + // declare variables to hold out params for loop body + write("var "); + for (var i = 0; i < loopOutParameters.length; i++) { + if (i !== 0) { + write(", "); + } + write(loopOutParameters[i].outParamName); + } + write(";"); + writeLine(); + } if (convertedLoopState.argumentsName) { // if alias for arguments is set if (convertedOuterLoopState) { @@ -32515,6 +34891,21 @@ var ts; writeLine(); } } + if (convertedLoopState.thisName) { + // if alias for this is set + if (convertedOuterLoopState) { + // pass it to outer converted loop + convertedOuterLoopState.thisName = convertedLoopState.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + write("var " + convertedLoopState.thisName + " = this;"); + writeLine(); + } + } if (convertedLoopState.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later if (convertedOuterLoopState) { @@ -32524,7 +34915,7 @@ var ts; else { // deduplicate and hoist collected variable declarations write("var "); - var seen; + var seen = void 0; for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { var id = _d[_c]; // Don't initialize seen unless we have at least one element. @@ -32547,15 +34938,21 @@ var ts; var currentLoopState = convertedLoopState; convertedLoopState = convertedOuterLoopState; return { functionName: functionName, paramList: paramList, state: currentLoopState }; - function collectNames(name) { + function processVariableDeclaration(name) { if (name.kind === 69 /* Identifier */) { - var nameText = isNameOfNestedRedeclaration(name) ? getGeneratedNameForNode(name) : name.text; + var nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(name) + ? getGeneratedNameForNode(name) + : name.text; loopParameters.push(nameText); + if (resolver.getNodeCheckFlags(name.parent) & 2097152 /* NeedsLoopOutParameter */) { + var reassignedVariable = { originalName: name, outParamName: makeUniqueName("out_" + nameText) }; + (loopOutParameters || (loopOutParameters = [])).push(reassignedVariable); + } } else { for (var _a = 0, _b = name.elements; _a < _b.length; _a++) { var element = _b[_a]; - collectNames(element.name); + processVariableDeclaration(element.name); } } } @@ -32571,7 +34968,7 @@ var ts; if (emitAsEmbeddedStatement) { emitEmbeddedStatement(node.statement); } - else if (node.statement.kind === 192 /* Block */) { + else if (node.statement.kind === 196 /* Block */) { emitLines(node.statement.statements); } else { @@ -32582,6 +34979,28 @@ var ts; convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; } } + function copyLoopOutParameters(state, copyDirection, emitAsStatements) { + if (state.loopOutParameters) { + for (var _a = 0, _b = state.loopOutParameters; _a < _b.length; _a++) { + var outParam = _b[_a]; + if (copyDirection === 0 /* ToOriginal */) { + emitIdentifier(outParam.originalName); + write(" = " + outParam.outParamName); + } + else { + write(outParam.outParamName + " = "); + emitIdentifier(outParam.originalName); + } + if (emitAsStatements) { + write(";"); + writeLine(); + } + else { + write(", "); + } + } + } + } function emitConvertedLoopCall(loop, emitAsBlock) { if (emitAsBlock) { write(" {"); @@ -32598,6 +35017,8 @@ var ts; write("var " + loopResult + " = "); } write(loop.functionName + "(" + loop.paramList + ");"); + writeLine(); + copyLoopOutParameters(loop.state, 0 /* ToOriginal */, /*emitAsStatements*/ true); if (!isSimpleLoop) { // for non simple loops we need to store result returned from converted loop function and use it to do dispatching // converted loop function can return: @@ -32615,7 +35036,7 @@ var ts; } else { // top level converted loop - return unwrapped value - write("return " + loopResult + ".value"); + write("return " + loopResult + ".value;"); } writeLine(); } @@ -32641,8 +35062,8 @@ var ts; } write("switch(" + loopResultVariable + ") {"); increaseIndent(); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /* isBreak */ true, loopResultVariable, outerLoop); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /* isBreak */ false, loopResultVariable, outerLoop); + emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /*isBreak*/ true, loopResultVariable, outerLoop); + emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /*isBreak*/ false, loopResultVariable, outerLoop); decreaseIndent(); writeLine(); write("}"); @@ -32657,7 +35078,7 @@ var ts; write("case \"" + labelMarker + "\": "); // if there are no outer converted loop or outer label in question is located inside outer converted loop // then emit labeled break\continue - // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { if (isBreak) { write("break "); @@ -32681,9 +35102,9 @@ var ts; var endPos = emitToken(86 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 216 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList); if (startIsEmitted) { emitCommaList(variableDeclarationList.declarations); } @@ -32700,14 +35121,14 @@ var ts; emitOptional(" ", node.incrementor); write(")"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 /* ES6 */ && node.kind === 201 /* ForOfStatement */) { + if (languageVersion < 2 /* ES6 */ && node.kind === 205 /* ForOfStatement */) { emitLoop(node, emitDownLevelForOfStatementWorker); } else { @@ -32718,17 +35139,17 @@ var ts; var endPos = emitToken(86 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 216 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + tryEmitStartOfVariableDeclarationList(variableDeclarationList); emit(variableDeclarationList.declarations[0]); } } else { emit(node.initializer); } - if (node.kind === 200 /* ForInStatement */) { + if (node.kind === 204 /* ForInStatement */) { write(" in "); } else { @@ -32737,15 +35158,12 @@ var ts; emit(node.expression); emitToken(18 /* CloseParenToken */, node.expression.end); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } - function emitDownLevelForOfStatement(node) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } function emitDownLevelForOfStatementWorker(node, loop) { // The following ES6 code: // @@ -32800,18 +35218,18 @@ var ts; emitEnd(node.expression); write("; "); // _i < _a.length; - emitStart(node.initializer); + emitStart(node.expression); emitNodeWithoutSourceMap(counter); write(" < "); emitNodeWithCommentsAndWithoutSourcemap(rhsReference); write(".length"); - emitEnd(node.initializer); + emitEnd(node.expression); write("; "); // _i++) - emitStart(node.initializer); + emitStart(node.expression); emitNodeWithoutSourceMap(counter); write("++"); - emitEnd(node.initializer); + emitEnd(node.expression); emitToken(18 /* CloseParenToken */, node.expression.end); // Body write(" {"); @@ -32821,7 +35239,7 @@ var ts; // let v = _a[_i]; var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 216 /* VariableDeclarationList */) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -32851,7 +35269,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, 56 /* EqualsToken */, rhsIterationValue, /*startsOnNewLine*/ false); - if (node.initializer.kind === 164 /* ArrayLiteralExpression */ || node.initializer.kind === 165 /* ObjectLiteralExpression */) { + if (node.initializer.kind === 168 /* ArrayLiteralExpression */ || node.initializer.kind === 169 /* 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, /*isAssignmentExpressionStatement*/ true, /*value*/ undefined); @@ -32864,10 +35282,10 @@ var ts; write(";"); if (loop) { writeLine(); - emitConvertedLoopCall(loop, /* emitAsBlock */ false); + emitConvertedLoopCall(loop, /*emitAsBlock*/ false); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ false); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ false); } writeLine(); decreaseIndent(); @@ -32879,36 +35297,39 @@ var ts; // it is possible if either // - break\continue is statement labeled and label is located inside the converted loop // - break\continue is non-labeled and located in non-converted loop\switch statement - var jump = node.kind === 203 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 207 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { + write("return "); + // explicit exit from loop -> copy out parameters + copyLoopOutParameters(convertedLoopState, 1 /* ToOutParameter */, /*emitAsStatements*/ false); if (!node.label) { - if (node.kind === 203 /* BreakStatement */) { + if (node.kind === 207 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; - write("return \"break\";"); + write("\"break\";"); } else { convertedLoopState.nonLocalJumps |= 4 /* Continue */; - write("return \"continue\";"); + write("\"continue\";"); } } else { - var labelMarker; - if (node.kind === 203 /* BreakStatement */) { + var labelMarker = void 0; + if (node.kind === 207 /* BreakStatement */) { labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, /* isBreak */ true, node.label.text, labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); } else { labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, /* isBreak */ false, node.label.text, labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); } - write("return \"" + labelMarker + "\";"); + write("\"" + labelMarker + "\";"); } return; } } - emitToken(node.kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); + emitToken(node.kind === 207 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); emitOptional(" ", node.label); write(";"); } @@ -32962,19 +35383,19 @@ var ts; emitToken(16 /* CloseBraceToken */, node.clauses.end); } function nodeStartPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, node2.end); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end); } function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 241 /* CaseClause */) { + if (node.kind === 245 /* CaseClause */) { write("case "); emit(node.expression); write(":"); @@ -33043,7 +35464,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 218 /* ModuleDeclaration */); + } while (node && node.kind !== 222 /* ModuleDeclaration */); return node; } function emitContainingModuleName(node) { @@ -33052,13 +35473,13 @@ var ts; } function emitModuleMemberName(node) { emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 2 /* Export */) { + if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { var container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); write("."); } - else if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) { + else if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { write("exports."); } } @@ -33068,22 +35489,22 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(8 /* NumericLiteral */); zero.text = "0"; - var result = ts.createSynthesizedNode(177 /* VoidExpression */); + var result = ts.createSynthesizedNode(181 /* VoidExpression */); result.expression = zero; return result; } function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 248 /* SourceFile */) { - ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 227 /* ExportAssignment */); + if (node.parent.kind === 252 /* SourceFile */) { + ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 231 /* ExportAssignment */); // only allow export default at a source file level - if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) { - if (!currentSourceFile.symbol.exports["___esModule"]) { - if (languageVersion === 1 /* ES5 */) { + if (modulekind === ts.ModuleKind.CommonJS || modulekind === ts.ModuleKind.AMD || modulekind === ts.ModuleKind.UMD) { + if (!isEs6Module) { + if (languageVersion !== 0 /* ES3 */) { // default value of configurable, enumerable, writable are `false`. write("Object.defineProperty(exports, \"__esModule\", { value: true });"); writeLine(); } - else if (languageVersion === 0 /* ES3 */) { + else { write("exports.__esModule = true;"); writeLine(); } @@ -33092,11 +35513,11 @@ var ts; } } function emitExportMemberAssignment(node) { - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { writeLine(); emitStart(node); // emit call to exporter only for top level nodes - if (modulekind === 4 /* System */ && node.parent === currentSourceFile) { + if (modulekind === ts.ModuleKind.System && node.parent === currentSourceFile) { // emit export default as // export("default", ) write(exportFunctionForFile + "(\""); @@ -33131,7 +35552,7 @@ var ts; } } function emitExportMemberAssignments(name) { - if (modulekind === 4 /* System */) { + if (modulekind === ts.ModuleKind.System) { return; } if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { @@ -33150,7 +35571,7 @@ var ts; } } function emitExportSpecifierInSystemModule(specifier) { - ts.Debug.assert(modulekind === 4 /* System */); + ts.Debug.assert(modulekind === ts.ModuleKind.System); if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) { return; } @@ -33170,7 +35591,7 @@ var ts; * @param value an expression as a right-hand-side operand of the assignment * @param shouldEmitCommaBeforeAssignment a boolean indicating whether to prefix an assignment with comma */ - function emitAssignment(name, value, shouldEmitCommaBeforeAssignment) { + function emitAssignment(name, value, shouldEmitCommaBeforeAssignment, nodeForSourceMap) { if (shouldEmitCommaBeforeAssignment) { write(", "); } @@ -33180,15 +35601,21 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(name); write("\", "); } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 /* VariableDeclaration */ || name.parent.kind === 163 /* BindingElement */); - if (isVariableDeclarationOrBindingElement) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 215 /* VariableDeclaration */ || name.parent.kind === 167 /* BindingElement */); + // If this is first var declaration, we need to start at var/let/const keyword instead + // otherwise use nodeForSourceMap as the start position + emitStart(isFirstVariableDeclaration(nodeForSourceMap) ? nodeForSourceMap.parent : nodeForSourceMap); + withTemporaryNoSourceMap(function () { + if (isVariableDeclarationOrBindingElement) { + emitModuleMemberName(name.parent); + } + else { + emit(name); + } + write(" = "); + emit(value); + }); + emitEnd(nodeForSourceMap, /*stopOverridingSpan*/ true); if (exportChanged) { write(")"); } @@ -33199,14 +35626,19 @@ var ts; * @param canDefineTempVariablesInPlace a boolean indicating whether you can define the temporary variable at an assignment location * @param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma */ - function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment) { + function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment, sourceMapNode) { var identifier = createTempVariable(0 /* Auto */); if (!canDefineTempVariablesInPlace) { recordTempDeclaration(identifier); } - emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment); + emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment, sourceMapNode || expression.parent); return identifier; } + function isFirstVariableDeclaration(root) { + return root.kind === 215 /* VariableDeclaration */ && + root.parent.kind === 216 /* VariableDeclarationList */ && + root.parent.declarations[0] === root; + } function emitDestructuring(root, isAssignmentExpressionStatement, value) { var emitCount = 0; // An exported declaration is actually emitted as an assignment (to a property on the module object), so @@ -33214,19 +35646,24 @@ 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 === 211 /* VariableDeclaration */) { - var isExported = ts.getCombinedNodeFlags(root) & 2 /* Export */; + if (root.kind === 215 /* VariableDeclaration */) { + var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } - else if (root.kind === 138 /* Parameter */) { + else if (root.kind === 140 /* Parameter */) { canDefineTempVariablesInPlace = true; } - if (root.kind === 181 /* BinaryExpression */) { + if (root.kind === 185 /* BinaryExpression */) { emitAssignmentExpression(root); } else { ts.Debug.assert(!isAssignmentExpressionStatement); + // If first variable declaration of variable statement correct the start location + if (isFirstVariableDeclaration(root)) { + // Use emit location of "var " as next emit start entry + sourceMap.changeEmitSourcePos(); + } emitBindingElement(root, value); } /** @@ -33238,27 +35675,28 @@ var ts; * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; * false if it is necessary to always emit an identifier. */ - function ensureIdentifier(expr, reuseIdentifierExpressions) { + function ensureIdentifier(expr, reuseIdentifierExpressions, sourceMapNode) { if (expr.kind === 69 /* Identifier */ && reuseIdentifierExpressions) { return expr; } - var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0); + var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0, sourceMapNode); emitCount++; return identifier; } - function createDefaultValueCheck(value, defaultValue) { + function createDefaultValueCheck(value, defaultValue, sourceMapNode) { // The value expression will be evaluated twice, so for anything but a simple identifier // we need to generate a temporary variable - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); + // If the temporary variable needs to be emitted use the source Map node for assignment of that statement + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); // Return the expression 'value === void 0 ? defaultValue : value' - var equals = ts.createSynthesizedNode(181 /* BinaryExpression */); + var equals = ts.createSynthesizedNode(185 /* BinaryExpression */); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(32 /* EqualsEqualsEqualsToken */); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(182 /* ConditionalExpression */); + var cond = ts.createSynthesizedNode(186 /* ConditionalExpression */); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(53 /* QuestionToken */); cond.whenTrue = whenTrue; @@ -33272,17 +35710,28 @@ var ts; return node; } function createPropertyAccessForDestructuringProperty(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 !== 69 /* Identifier */) { - return createElementAccessExpression(object, syntheticName); + var index; + var nameIsComputed = propName.kind === 138 /* ComputedPropertyName */; + if (nameIsComputed) { + // TODO to handle when we look into sourcemaps for computed properties, for now use propName + index = ensureIdentifier(propName.expression, /*reuseIdentifierExpressions*/ false, propName); } - return createPropertyAccessExpression(object, syntheticName); + else { + // We create a synthetic copy of the identifier in order to avoid the rewriting that might + // otherwise occur when the identifier is emitted. + index = ts.createSynthesizedNode(propName.kind); + // We need to unescape identifier here because when parsing an identifier prefixing with "__" + // the parser need to append "_" in order to escape colliding with magic identifiers such as "__proto__" + // Therefore, in order to correctly emit identifiers that are written in original TypeScript file, + // we will unescapeIdentifier to remove additional underscore (if no underscore is added, the function will return original input string) + index.text = ts.unescapeIdentifier(propName.text); + } + return !nameIsComputed && index.kind === 69 /* Identifier */ + ? createPropertyAccessExpression(object, index) + : createElementAccessExpression(object, index); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(168 /* CallExpression */); + var call = ts.createSynthesizedNode(172 /* CallExpression */); var sliceIdentifier = ts.createSynthesizedNode(69 /* Identifier */); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -33290,60 +35739,65 @@ var ts; call.arguments[0] = createNumericLiteral(sliceIndex); return call; } - function emitObjectLiteralAssignment(target, value) { + function emitObjectLiteralAssignment(target, value, sourceMapNode) { var properties = target.properties; if (properties.length !== 1) { // For anything but a single element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); + // When doing so we want to highlight the passed in source map node since thats the one needing this temp assignment + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); } for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { var p = properties_5[_a]; - if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 249 /* PropertyAssignment */ || p.kind === 250 /* ShorthandPropertyAssignment */) { var propName = p.name; - var target_1 = p.kind === 246 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName)); + var target_1 = p.kind === 250 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; + // Assignment for target = value.propName should highlight whole property, hence use p as source map node + emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName), p); } } } - function emitArrayLiteralAssignment(target, value) { + function emitArrayLiteralAssignment(target, value, sourceMapNode) { var elements = target.elements; if (elements.length !== 1) { // For anything but a single element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); + // When doing so we want to highlight the passed in source map node since thats the one needing this temp assignment + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187 /* OmittedExpression */) { - if (e.kind !== 185 /* SpreadElementExpression */) { - emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); + if (e.kind !== 191 /* OmittedExpression */) { + // Assignment for target = value.propName should highlight whole property, hence use e as source map node + if (e.kind !== 189 /* SpreadElementExpression */) { + emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e); } else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i)); + emitDestructuringAssignment(e.expression, createSliceCall(value, i), e); } } } } - function emitDestructuringAssignment(target, value) { - if (target.kind === 246 /* ShorthandPropertyAssignment */) { + function emitDestructuringAssignment(target, value, sourceMapNode) { + // When emitting target = value use source map node to highlight, including any temporary assignments needed for this + if (target.kind === 250 /* ShorthandPropertyAssignment */) { if (target.objectAssignmentInitializer) { - value = createDefaultValueCheck(value, target.objectAssignmentInitializer); + value = createDefaultValueCheck(value, target.objectAssignmentInitializer, sourceMapNode); } target = target.name; } - else if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { - value = createDefaultValueCheck(value, target.right); + else if (target.kind === 185 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + value = createDefaultValueCheck(value, target.right, sourceMapNode); target = target.left; } - if (target.kind === 165 /* ObjectLiteralExpression */) { - emitObjectLiteralAssignment(target, value); + if (target.kind === 169 /* ObjectLiteralExpression */) { + emitObjectLiteralAssignment(target, value, sourceMapNode); } - else if (target.kind === 164 /* ArrayLiteralExpression */) { - emitArrayLiteralAssignment(target, value); + else if (target.kind === 168 /* ArrayLiteralExpression */) { + emitArrayLiteralAssignment(target, value, sourceMapNode); } else { - emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0); + emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0, sourceMapNode); emitCount++; } } @@ -33354,25 +35808,32 @@ var ts; emit(value); } else if (isAssignmentExpressionStatement) { - emitDestructuringAssignment(target, value); + // Source map node for root.left = root.right is root + // but if root is synthetic, which could be in below case, use the target which is { a } + // for ({a} of {a: string}) { + // } + emitDestructuringAssignment(target, value, ts.nodeIsSynthesized(root) ? target : root); } else { - if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + if (root.parent.kind !== 176 /* ParenthesizedExpression */) { write("("); } - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); - emitDestructuringAssignment(target, value); + // Temporary assignment needed to emit root should highlight whole binary expression + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, root); + // Source map node for root.left = root.right is root + emitDestructuringAssignment(target, value, root); write(", "); emit(value); - if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + if (root.parent.kind !== 176 /* ParenthesizedExpression */) { write(")"); } } } function emitBindingElement(target, value) { + // Any temporary assignments needed to emit target = value should point to target if (target.initializer) { // Combine value and initializer - value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; + value = value ? createDefaultValueCheck(value, target.initializer, target) : target.initializer; } else if (!value) { // Use 'void 0' in absence of value and initializer @@ -33387,16 +35848,16 @@ var ts; // to ensure value is evaluated exactly once. Additionally, if we have zero elements // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, // so in that case, we'll intentionally create that temporary. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0); + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target); } for (var i = 0; i < numElements; i++) { var element = elements[i]; - if (pattern.kind === 161 /* ObjectBindingPattern */) { + if (pattern.kind === 165 /* 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 !== 187 /* OmittedExpression */) { + else if (element.kind !== 191 /* OmittedExpression */) { if (!element.dotDotDotToken) { // Rewrite element to a declaration that accesses array element at index i emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); @@ -33408,7 +35869,7 @@ var ts; } } else { - emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0); + emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0, target); emitCount++; } } @@ -33425,19 +35886,46 @@ var ts; } else { var initializer = node.initializer; - if (!initializer && languageVersion < 2 /* ES6 */) { - // downlevel emit for non-initialized let bindings defined in loops - // for (...) { let x; } - // should be - // for (...) { var = void 0; } - // this is necessary to preserve ES6 semantic in scenarios like - // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations - var isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & 16384 /* BlockScopedBindingInLoop */) && - (getCombinedFlagsForIdentifier(node.name) & 8192 /* Let */); - // NOTE: default initialization should not be added to let bindings in for-in\for-of statements - if (isLetDefinedInLoop && - node.parent.parent.kind !== 200 /* ForInStatement */ && - node.parent.parent.kind !== 201 /* ForOfStatement */) { + if (!initializer && + languageVersion < 2 /* ES6 */ && + // for names - binding patterns that lack initializer there is no point to emit explicit initializer + // since downlevel codegen for destructuring will fail in the absence of initializer so all binding elements will say uninitialized + node.name.kind === 69 /* Identifier */) { + var container = ts.getEnclosingBlockScopeContainer(node); + var flags = resolver.getNodeCheckFlags(node); + // nested let bindings might need to be initialized explicitly to preserve ES6 semantic + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // NOTES: + // Top level bindings never collide with anything and thus don't require explicit initialization. + // As for nested let bindings there are two cases: + // - nested let bindings that were not renamed definitely should be initialized explicitly + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // Without explicit initialization code in /*1*/ can be executed even if some-condition is evaluated to false + // - renaming introduces fresh name that should not collide with any existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding declared inside loop body (but not in loop initializer) + // let x; + // for (;;) { + // let x; + // } + // in downlevel codegen inner 'x' will be renamed so it won't collide with outer 'x' however it will should be reset on every iteration + // as if it was declared anew. + // * Why non-captured binding - because if loop contains block scoped binding captured in some function then loop body will be rewritten + // to have a fresh scope on every iteration so everything will just work. + // * Why loop initializer is excluded - since we've introduced a fresh name it already will be undefined. + var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(container) || + (isCapturedInFunction && isDeclaredInLoop && container.kind === 196 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false)); + var emittedAsNestedLetDeclaration = ts.getCombinedNodeFlags(node) & 1024 /* Let */ && + !emittedAsTopLevel; + var emitExplicitInitializer = emittedAsNestedLetDeclaration && + container.kind !== 204 /* ForInStatement */ && + container.kind !== 205 /* ForOfStatement */ && + (!resolver.isDeclarationWithCollidingName(node) || + (isDeclaredInLoop && !isCapturedInFunction && !ts.isIterationStatement(container, /*lookInLabeledStatements*/ false))); + if (emitExplicitInitializer) { initializer = createVoidZero(); } } @@ -33455,7 +35943,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 187 /* OmittedExpression */) { + if (node.kind === 191 /* OmittedExpression */) { return; } var name = node.name; @@ -33466,20 +35954,14 @@ var ts; ts.forEach(name.elements, emitExportVariableAssignments); } } - function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 211 /* VariableDeclaration */ && node.parent.kind !== 163 /* BindingElement */)) { - return 0; - } - return ts.getCombinedNodeFlags(node.parent); - } function isES6ExportedDeclaration(node) { - return !!(node.flags & 2 /* Export */) && - modulekind === 5 /* ES6 */ && - node.parent.kind === 248 /* SourceFile */; + return !!(node.flags & 1 /* Export */) && + modulekind === ts.ModuleKind.ES6 && + node.parent.kind === 252 /* SourceFile */; } function emitVariableStatement(node) { var startIsEmitted = false; - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { if (isES6ExportedDeclaration(node)) { // Exported ES6 module member write("export "); @@ -33499,14 +35981,14 @@ var ts; write(";"); } } - if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { 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 & 2 /* Export */)) { + if (!(node.flags & 1 /* Export */)) { return true; } // If we are exporting, but it's a top-level ES6 module exports, @@ -33526,12 +36008,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2 /* ES6 */) { if (ts.isBindingPattern(node.name)) { - var name_25 = createTempVariable(0 /* Auto */); + var name_26 = createTempVariable(0 /* Auto */); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_25); - emit(name_25); + tempParameters.push(name_26); + emit(name_26); } else { emit(node.name); @@ -33547,7 +36029,7 @@ var ts; } function emitDefaultValueAssignments(node) { if (languageVersion < 2 /* ES6 */) { - var tempIndex = 0; + var tempIndex_1 = 0; ts.forEach(node.parameters, function (parameter) { // A rest parameter cannot have a binding pattern or an initializer, // so let's just ignore it. @@ -33564,15 +36046,15 @@ var ts; writeLine(); write("var "); if (hasBindingElements) { - emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]); + emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex_1]); } else { - emit(tempParameters[tempIndex]); + emit(tempParameters[tempIndex_1]); write(" = "); emit(initializer); } write(";"); - tempIndex++; + tempIndex_1++; } } else if (initializer) { @@ -33636,12 +36118,12 @@ var ts; } } function emitAccessor(node) { - write(node.kind === 145 /* GetAccessor */ ? "get " : "set "); + write(node.kind === 147 /* GetAccessor */ ? "get " : "set "); emit(node.name); emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 174 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; + return node.kind === 178 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; } function emitDeclarationName(node) { if (node.name) { @@ -33652,13 +36134,13 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 173 /* FunctionExpression */) { + if (node.kind === 177 /* FunctionExpression */) { // Emit name if one is present return !!node.name; } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 217 /* 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 */; + return !!node.name || modulekind !== ts.ModuleKind.ES6; } } function emitFunctionDeclaration(node) { @@ -33667,20 +36149,29 @@ var ts; } // TODO (yuisu) : we should not have special cases to condition emitting comments // but have one place to fix check for these conditions. - if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */ && - node.parent && node.parent.kind !== 245 /* PropertyAssignment */ && - node.parent.kind !== 168 /* CallExpression */) { - // 1. Methods will emit the comments as part of emitting method declaration + var kind = node.kind, parent = node.parent; + if (kind !== 145 /* MethodDeclaration */ && + kind !== 144 /* MethodSignature */ && + parent && + parent.kind !== 249 /* PropertyAssignment */ && + parent.kind !== 172 /* CallExpression */ && + parent.kind !== 168 /* ArrayLiteralExpression */) { + // 1. Methods will emit comments at their assignment declaration sites. + // // 2. If the function is a property of object literal, emitting leading-comments - // is done by emitNodeWithoutSourceMap which then call this function. - // In particular, we would like to avoid emit comments twice in following case: - // For example: + // is done by emitNodeWithoutSourceMap which then call this function. + // In particular, we would like to avoid emit comments twice in following case: + // // var obj = { // id: // /*comment*/ () => void // } + // // 3. If the function is an argument in call expression, emitting of comments will be - // taken care of in emit list of arguments inside of emitCallexpression + // taken care of in emit list of arguments inside of 'emitCallExpression'. + // + // 4. If the function is in an array literal, 'emitLinePreservingList' will take care + // of leading comments. emitLeadingComments(node); } emitStart(node); @@ -33703,11 +36194,11 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (modulekind !== 5 /* ES6 */ && node.kind === 213 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { + if (modulekind !== ts.ModuleKind.ES6 && kind === 217 /* FunctionDeclaration */ && parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } emitEnd(node); - if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) { + if (kind !== 145 /* MethodDeclaration */ && kind !== 144 /* MethodSignature */) { emitTrailingComments(node); } } @@ -33740,9 +36231,8 @@ var ts; } function emitAsyncFunctionBodyForES6(node) { var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 174 /* ArrowFunction */; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096 /* CaptureArguments */) !== 0; - var args; + var isArrowFunction = node.kind === 178 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current // `this` and `arguments` objects to `__awaiter`. The generator function @@ -33820,29 +36310,31 @@ var ts; write(" {"); increaseIndent(); writeLine(); + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + writeLines("\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"); + writeLine(); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + write("const _super = name => super[name];"); + writeLine(); + } write("return"); } write(" __awaiter(this"); if (hasLexicalArguments) { - write(", arguments"); + write(", arguments, "); } else { - write(", void 0"); + write(", void 0, "); } - if (promiseConstructor) { - write(", "); - emitNodeWithoutSourceMap(promiseConstructor); + if (languageVersion >= 2 /* ES6 */ || !promiseConstructor) { + write("void 0"); } else { - write(", Promise"); + emitEntityNameAsExpression(promiseConstructor, /*useFallback*/ false); } // Emit the call to __awaiter. - if (hasLexicalArguments) { - write(", function* (_arguments)"); - } - else { - write(", function* ()"); - } + write(", function* ()"); // Emit the signature and body for the inner generator function. emitFunctionBody(node); write(")"); @@ -33861,7 +36353,7 @@ var ts; write(" { }"); } else { - if (node.body.kind === 192 /* Block */) { + if (node.body.kind === 196 /* Block */) { emitBlockFunctionBody(node, node.body); } else { @@ -33887,7 +36379,7 @@ var ts; emitSignatureParameters(node); } var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync && languageVersion === 2 /* ES6 */) { + if (isAsync) { emitAsyncFunctionBodyForES6(node); } else { @@ -33920,14 +36412,13 @@ var ts; write(" "); // Unwrap all type assertions. var current = body; - while (current.kind === 171 /* TypeAssertionExpression */) { + while (current.kind === 175 /* TypeAssertionExpression */) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 165 /* ObjectLiteralExpression */); + emitParenthesizedIf(body, current.kind === 169 /* ObjectLiteralExpression */); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); emitDetachedCommentsAndUpdateCommentsInfo(node.body); @@ -33950,8 +36441,10 @@ var ts; increaseIndent(); writeLine(); emitLeadingComments(node.body); + emitStart(body); write("return "); emit(body); + emitEnd(body); write(";"); emitTrailingComments(node.body); emitTempDeclarations(/*newLine*/ true); @@ -33961,11 +36454,9 @@ var ts; emitStart(node.body); write("}"); emitEnd(node.body); - scopeEmitEnd(); } function emitBlockFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); emitDetachedCommentsAndUpdateCommentsInfo(body.statements); @@ -33994,25 +36485,28 @@ var ts; decreaseIndent(); } emitToken(16 /* CloseBraceToken */, body.statements.end); - scopeEmitEnd(); } - function findInitialSuperCall(ctor) { - if (ctor.body) { - var statement = ctor.body.statements[0]; - if (statement && statement.kind === 195 /* ExpressionStatement */) { - var expr = statement.expression; - if (expr && expr.kind === 168 /* CallExpression */) { - var func = expr.expression; - if (func && func.kind === 95 /* SuperKeyword */) { - return statement; - } - } - } + /** + * Return the statement at a given index if it is a super-call statement + * @param ctor a constructor declaration + * @param index an index to constructor's body to check + */ + function getSuperCallAtGivenIndex(ctor, index) { + if (!ctor.body) { + return undefined; + } + var statements = ctor.body.statements; + if (!statements || index >= statements.length) { + return undefined; + } + var statement = statements[index]; + if (statement.kind === 199 /* ExpressionStatement */) { + return ts.isSuperCallExpression(statement.expression) ? statement : undefined; } } function emitParameterPropertyAssignments(node) { ts.forEach(node.parameters, function (param) { - if (param.flags & 56 /* AccessibilityModifier */) { + if (param.flags & 28 /* AccessibilityModifier */) { writeLine(); emitStart(param); emitStart(param.name); @@ -34035,7 +36529,7 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(memberName); write("]"); } - else if (memberName.kind === 136 /* ComputedPropertyName */) { + else if (memberName.kind === 138 /* ComputedPropertyName */) { emitComputedPropertyName(memberName); } else { @@ -34047,7 +36541,7 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 141 /* PropertyDeclaration */ && isStatic === ((member.flags & 64 /* Static */) !== 0) && member.initializer) { + if (member.kind === 143 /* PropertyDeclaration */ && isStatic === ((member.flags & 32 /* Static */) !== 0) && member.initializer) { properties.push(member); } } @@ -34068,7 +36562,7 @@ var ts; emit(receiver); } else { - if (property.flags & 64 /* Static */) { + if (property.flags & 32 /* Static */) { emitDeclarationName(node); } else { @@ -34087,11 +36581,11 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 191 /* SemicolonClassElement */) { + if (member.kind === 195 /* SemicolonClassElement */) { writeLine(); write(";"); } - else if (member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) { + else if (member.kind === 145 /* MethodDeclaration */ || node.kind === 144 /* MethodSignature */) { if (!member.body) { return emitCommentsOnNotEmittedNode(member); } @@ -34108,7 +36602,7 @@ var ts; write(";"); emitTrailingComments(member); } - else if (member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) { + else if (member.kind === 147 /* GetAccessor */ || member.kind === 148 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); @@ -34158,22 +36652,22 @@ var ts; function emitMemberFunctionsForES6AndHigher(node) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) && !member.body) { + if ((member.kind === 145 /* MethodDeclaration */ || node.kind === 144 /* MethodSignature */) && !member.body) { emitCommentsOnNotEmittedNode(member); } - else if (member.kind === 143 /* MethodDeclaration */ || - member.kind === 145 /* GetAccessor */ || - member.kind === 146 /* SetAccessor */) { + else if (member.kind === 145 /* MethodDeclaration */ || + member.kind === 147 /* GetAccessor */ || + member.kind === 148 /* SetAccessor */) { writeLine(); emitLeadingComments(member); emitStart(member); - if (member.flags & 64 /* Static */) { + if (member.flags & 32 /* Static */) { write("static "); } - if (member.kind === 145 /* GetAccessor */) { + if (member.kind === 147 /* GetAccessor */) { write("get "); } - else if (member.kind === 146 /* SetAccessor */) { + else if (member.kind === 148 /* SetAccessor */) { write("set "); } if (member.asteriskToken) { @@ -34184,7 +36678,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 191 /* SemicolonClassElement */) { + else if (member.kind === 195 /* SemicolonClassElement */) { writeLine(); write(";"); } @@ -34213,11 +36707,11 @@ var ts; var hasInstancePropertyWithInitializer = false; // Emit the constructor overload pinned comments ts.forEach(node.members, function (member) { - if (member.kind === 144 /* Constructor */ && !member.body) { + if (member.kind === 146 /* Constructor */ && !member.body) { emitCommentsOnNotEmittedNode(member); } // Check if there is any non-static property assignment - if (member.kind === 141 /* PropertyDeclaration */ && member.initializer && (member.flags & 64 /* Static */) === 0) { + if (member.kind === 143 /* PropertyDeclaration */ && member.initializer && (member.flags & 32 /* Static */) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -34258,7 +36752,6 @@ var ts; } var startIndex = 0; write(" {"); - scopeEmitStart(node, "constructor"); increaseIndent(); if (ctor) { // Emit all the directive prologues (like "use strict"). These have to come before @@ -34272,7 +36765,7 @@ var ts; emitDefaultValueAssignments(ctor); emitRestParameter(ctor); if (baseTypeElement) { - superCall = findInitialSuperCall(ctor); + superCall = getSuperCallAtGivenIndex(ctor, startIndex); if (superCall) { writeLine(); emit(superCall); @@ -34293,7 +36786,7 @@ var ts; emitEnd(baseTypeElement); } } - emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false)); + emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ false)); if (ctor) { var statements = ctor.body.statements; if (superCall) { @@ -34308,7 +36801,6 @@ var ts; } decreaseIndent(); emitToken(16 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); emitEnd(ctor || node); if (ctor) { emitTrailingComments(ctor); @@ -34327,68 +36819,108 @@ var ts; else { emitClassLikeDeclarationForES6AndHigher(node); } - if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile && node.name) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } } function emitClassLikeDeclarationForES6AndHigher(node) { + var decoratedClassAlias; var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* 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: + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. // - // * For a local class declaration: + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: // - // @dec class C { - // } + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------|------------------------------------ + // @dec | export let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // [Example 1] // - // The emit should be: + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. // - // let C = class { - // }; - // C = __decorate([dec], C); + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: // - // * For an exported class declaration: + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let C_1; + // class C { | let C = C_1 = class C { + // static x() { return C.y; } | static x() { return C_1.y; } + // static y = 1; | } + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // --------------------------------|------------------------------------ + // @dec | let C_1; + // export class C { | export let C = C_1 = class C { + // static x() { return C.y; } | static x() { return C_1.y; } + // static y = 1; | } + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // --------------------------------------------------------------------- + // [Example 2] // - // @dec export class C { - // } + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: // - // The emit should be: + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------|------------------------------------ + // @dec | let C = class C { + // export default class { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // [Example 3] // - // export let C = class { - // }; - // C = __decorate([dec], C); + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: // - // * For a default export of a class declaration with a name: - // - // @dec default export class C { - // } - // - // The emit should be: - // - // let C = class { - // } - // C = __decorate([dec], C); - // export default C; - // - // * For a default export of a class declaration without a name: - // - // @dec default export class { - // } - // - // The emit should be: - // - // let _default = class { - // } - // _default = __decorate([dec], _default); - // export default _default; + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let C_1; + // export default class C { | let C = C_1 = class C { + // static x() { return C.y; } | static x() { return C_1.y; } + // static y = 1; | } + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // [Example 4] // + if (resolver.getNodeCheckFlags(node) & 524288 /* ClassWithBodyScopedClassBinding */) { + decoratedClassAlias = ts.unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default")); + decoratedClassAliases[ts.getNodeId(node)] = decoratedClassAlias; + write("let " + decoratedClassAlias + ";"); + writeLine(); + } if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */)) { write("export "); } write("let "); emitDeclarationName(node); + if (decoratedClassAlias !== undefined) { + write(" = " + decoratedClassAlias); + } write(" = "); } else if (isES6ExportedDeclaration(node)) { @@ -34409,8 +36941,8 @@ 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, /*static:*/ true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186 /* ClassExpression */; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 190 /* ClassExpression */; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0 /* Auto */); @@ -34423,7 +36955,7 @@ var ts; // emit name if // - node has a name // - this is default export with static initializers - if ((node.name || (node.flags & 512 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if (node.name || (node.flags & 512 /* Default */ && (staticProperties.length > 0 || modulekind !== ts.ModuleKind.ES6) && !thisNodeIsDecorated)) { write(" "); emitDeclarationName(node); } @@ -34434,23 +36966,14 @@ var ts; } write(" {"); increaseIndent(); - scopeEmitStart(node); writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES6AndHigher(node); decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); - // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now. - // For a decorated class, we need to assign its name (if it has one). This is because we emit - // the class as a class expression to avoid the double-binding of the identifier: - // - // let C = class { - // } - // Object.defineProperty(C, "name", { value: "C", configurable: true }); - // if (thisNodeIsDecorated) { + decoratedClassAliases[ts.getNodeId(node)] = undefined; write(";"); } // Emit static property assignment. Because classDeclaration is lexically evaluated, @@ -34463,7 +36986,7 @@ var ts; var property = staticProperties_1[_a]; write(","); writeLine(); - emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true); + emitPropertyDeclaration(node, property, /*receiver*/ tempVariable, /*isExpression*/ true); } write(","); writeLine(); @@ -34474,29 +36997,39 @@ var ts; else { writeLine(); emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node); + emitDecoratorsOfClass(node, decoratedClassAlias); } - // If this is an exported class, but not on the top level (i.e. on an internal - // module), export it - if (!isES6ExportedDeclaration(node) && (node.flags & 2 /* Export */)) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); + if (!(node.flags & 1 /* Export */)) { + return; } - else if (isES6ExportedDeclaration(node) && (node.flags & 512 /* Default */) && thisNodeIsDecorated) { - // if this is a top level default export of decorated class, write the export after the declaration. - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); + if (modulekind !== ts.ModuleKind.ES6) { + emitExportMemberAssignment(node); + } + else { + // If this is an exported class, but not on the top level (i.e. on an internal + // module), export it + if (node.flags & 512 /* Default */) { + // if this is a top level default export of decorated class, write the export after the declaration. + if (thisNodeIsDecorated) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } + } + else if (node.parent.kind !== 252 /* SourceFile */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emitDeclarationName(node); + emitEnd(node); + write(";"); + } } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* ClassDeclaration */) { // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -34521,7 +37054,6 @@ var ts; tempParameters = undefined; computedPropertyNamesToGeneratedNames = undefined; increaseIndent(); - scopeEmitStart(node); if (baseTypeNode) { writeLine(); emitStart(baseTypeNode); @@ -34533,9 +37065,9 @@ var ts; writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ true)); + emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ true)); writeLine(); - emitDecoratorsOfClass(node); + emitDecoratorsOfClass(node, /*decoratedClassAlias*/ undefined); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end, function () { write("return "); @@ -34552,38 +37084,37 @@ var ts; decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); emitStart(node); - write(")("); + write("("); if (baseTypeNode) { emit(baseTypeNode.expression); } - write(")"); - if (node.kind === 214 /* ClassDeclaration */) { + write("))"); + if (node.kind === 218 /* ClassDeclaration */) { write(";"); } emitEnd(node); - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* ClassDeclaration */) { emitExportMemberAssignment(node); } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); - if (!(member.flags & 64 /* Static */)) { + if (!(member.flags & 32 /* Static */)) { write(".prototype"); } } - function emitDecoratorsOfClass(node) { + function emitDecoratorsOfClass(node, decoratedClassAlias) { emitDecoratorsOfMembers(node, /*staticFlag*/ 0); - emitDecoratorsOfMembers(node, 64 /* Static */); - emitDecoratorsOfConstructor(node); + emitDecoratorsOfMembers(node, 32 /* Static */); + emitDecoratorsOfConstructor(node, decoratedClassAlias); } - function emitDecoratorsOfConstructor(node) { + function emitDecoratorsOfConstructor(node, decoratedClassAlias) { var decorators = node.decorators; var constructor = ts.getFirstConstructorWithBody(node); - var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); + var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); // skip decoration of the constructor if neither it nor its parameters are decorated - if (!decorators && !hasDecoratedParameters) { + if (!decorators && !firstParameterDecorator) { return; } // Emit the call to __decorate. Given the class: @@ -34597,42 +37128,40 @@ var ts; // C = __decorate([dec], C); // writeLine(); - emitStart(node); + emitStart(node.decorators || firstParameterDecorator); emitDeclarationName(node); + if (decoratedClassAlias !== undefined) { + write(" = " + decoratedClassAlias); + } write(" = __decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); + } emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0); decreaseIndent(); writeLine(); write("], "); emitDeclarationName(node); - write(");"); - emitEnd(node); + write(")"); + emitEnd(node.decorators || firstParameterDecorator); + write(";"); writeLine(); } function emitDecoratorsOfMembers(node, staticFlag) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; // only emit members in the correct group - if ((member.flags & 64 /* Static */) !== staticFlag) { + if ((member.flags & 32 /* Static */) !== staticFlag) { continue; } // skip members that cannot be decorated (such as the constructor) if (!ts.nodeCanBeDecorated(member)) { continue; } - // skip a member if it or any of its parameters are not decorated - if (!ts.nodeOrChildIsDecorated(member)) { - continue; - } // skip an accessor declaration if it is not the first accessor var decorators = void 0; var functionLikeMember = void 0; @@ -34652,10 +37181,15 @@ var ts; else { decorators = member.decorators; // we only decorate the parameters here if this is a method - if (member.kind === 143 /* MethodDeclaration */) { + if (member.kind === 145 /* MethodDeclaration */) { functionLikeMember = member; } } + var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); + // skip a member if it or any of its parameters are not decorated + if (!decorators && !firstParameterDecorator) { + continue; + } // Emit the call to __decorate. Given the following: // // class C { @@ -34687,28 +37221,24 @@ var ts; // ], C.prototype, "prop"); // writeLine(); - emitStart(member); + emitStart(decorators || firstParameterDecorator); write("__decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + } emitSerializedTypeMetadata(member, argumentsWritten > 0); decreaseIndent(); writeLine(); write("], "); - emitStart(member.name); emitClassMemberPrefix(node, member); write(", "); emitExpressionForPropertyName(member.name); - emitEnd(member.name); if (languageVersion > 0 /* ES3 */) { - if (member.kind !== 141 /* PropertyDeclaration */) { + if (member.kind !== 143 /* PropertyDeclaration */) { // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. // We have this extra argument here so that we can inject an explicit property descriptor at a later date. write(", null"); @@ -34719,29 +37249,28 @@ var ts; write(", void 0"); } } - write(");"); - emitEnd(member); + write(")"); + emitEnd(decorators || firstParameterDecorator); + write(";"); writeLine(); } } function emitDecoratorsOfParameters(node, leadingComma) { var argumentsWritten = 0; if (node) { - var parameterIndex = 0; + var parameterIndex_1 = 0; for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) { var parameter = _b[_a]; if (ts.nodeIsDecorated(parameter)) { var decorators = parameter.decorators; argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); - write("__param(" + parameterIndex + ", "); + write("__param(" + parameterIndex_1 + ", "); emit(decorator.expression); write(")"); - emitEnd(decorator); }); leadingComma = true; } - ++parameterIndex; + parameterIndex_1++; } } return argumentsWritten; @@ -34751,10 +37280,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 143 /* MethodDeclaration */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 141 /* PropertyDeclaration */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 143 /* PropertyDeclaration */: return true; } return false; @@ -34764,7 +37293,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 143 /* MethodDeclaration */: + case 145 /* MethodDeclaration */: return true; } return false; @@ -34774,9 +37303,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 214 /* ClassDeclaration */: - case 143 /* MethodDeclaration */: - case 146 /* SetAccessor */: + case 218 /* ClassDeclaration */: + case 145 /* MethodDeclaration */: + case 148 /* SetAccessor */: return true; } return false; @@ -34794,19 +37323,19 @@ var ts; // // For rules on serializing type annotations, see `serializeTypeNode`. switch (node.kind) { - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: write("Function"); return; - case 141 /* PropertyDeclaration */: + case 143 /* PropertyDeclaration */: emitSerializedTypeNode(node.type); return; - case 138 /* Parameter */: + case 140 /* Parameter */: emitSerializedTypeNode(node.type); return; - case 145 /* GetAccessor */: + case 147 /* GetAccessor */: emitSerializedTypeNode(node.type); return; - case 146 /* SetAccessor */: + case 148 /* SetAccessor */: emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); return; } @@ -34822,39 +37351,40 @@ var ts; case 103 /* VoidKeyword */: write("void 0"); return; - case 160 /* ParenthesizedType */: + case 162 /* ParenthesizedType */: emitSerializedTypeNode(node.type); return; - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: write("Function"); return; - case 156 /* ArrayType */: - case 157 /* TupleType */: + case 158 /* ArrayType */: + case 159 /* TupleType */: write("Array"); return; - case 150 /* TypePredicate */: + case 152 /* TypePredicate */: case 120 /* BooleanKeyword */: write("Boolean"); return; - case 130 /* StringKeyword */: - case 9 /* StringLiteral */: + case 131 /* StringKeyword */: + case 164 /* StringLiteralType */: write("String"); return; - case 128 /* NumberKeyword */: + case 129 /* NumberKeyword */: write("Number"); return; - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: write("Symbol"); return; - case 151 /* TypeReference */: + case 153 /* TypeReference */: emitSerializedTypeReferenceNode(node); return; - case 154 /* TypeQuery */: - case 155 /* TypeLiteral */: - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 156 /* TypeQuery */: + case 157 /* TypeLiteral */: + case 160 /* UnionType */: + case 161 /* IntersectionType */: case 117 /* AnyKeyword */: + case 163 /* ThisType */: break; default: ts.Debug.fail("Cannot serialize unexpected type node."); @@ -34870,8 +37400,7 @@ var ts; location = location.parent; } // Clone the type name and parent it to a location outside of the current declaration. - var typeName = ts.cloneEntityName(node.typeName); - typeName.parent = location; + var typeName = ts.cloneEntityName(node.typeName, location); var result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case ts.TypeReferenceSerializationKind.Unknown: @@ -34927,8 +37456,8 @@ var ts; // // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. if (node) { - var valueDeclaration; - if (node.kind === 214 /* ClassDeclaration */) { + var valueDeclaration = void 0; + if (node.kind === 218 /* ClassDeclaration */) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -34944,10 +37473,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 156 /* ArrayType */) { + if (parameterType.kind === 158 /* ArrayType */) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 151 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType.kind === 153 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -35023,9 +37552,10 @@ var ts; } if (!shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted - if (!(node.flags & 2 /* Export */) || isES6ExportedDeclaration(node)) { + var isES6ExportedEnum = isES6ExportedDeclaration(node); + if (!(node.flags & 1 /* Export */) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 221 /* EnumDeclaration */))) { emitStart(node); - if (isES6ExportedDeclaration(node)) { + if (isES6ExportedEnum) { write("export "); } write("var "); @@ -35042,19 +37572,17 @@ var ts; emitEnd(node.name); write(") {"); increaseIndent(); - scopeEmitStart(node); emitLines(node.members); decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); write(")("); emitModuleMemberName(node); write(" || ("); emitModuleMemberName(node); write(" = {}));"); emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 2 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { + if (!isES6ExportedDeclaration(node) && node.flags & 1 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted writeLine(); emitStart(node); @@ -35065,8 +37593,8 @@ var ts; emitEnd(node); write(";"); } - if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) { - if (modulekind === 4 /* System */ && (node.flags & 2 /* Export */)) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { + if (modulekind === ts.ModuleKind.System && (node.flags & 1 /* Export */)) { // write the call to exporter for enum writeLine(); write(exportFunctionForFile + "(\""); @@ -35107,7 +37635,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 222 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -35118,6 +37646,9 @@ var ts; function isModuleMergedWithES6Class(node) { return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 32768 /* LexicalModuleMergesWithClass */); } + function isFirstDeclarationOfKind(node, declarations, kind) { + return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); + } function emitModuleDeclaration(node) { // Emit only if this module is non-ambient. var shouldEmit = shouldEmitModuleDeclaration(node); @@ -35127,15 +37658,18 @@ var ts; var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); + var isES6ExportedNamespace = isES6ExportedDeclaration(node); + if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 222 /* ModuleDeclaration */)) { + emitStart(node); + if (isES6ExportedNamespace) { + write("export "); + } + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); } emitStart(node); write("(function ("); @@ -35143,7 +37677,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 219 /* ModuleBlock */) { + if (node.body.kind === 223 /* ModuleBlock */) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; @@ -35159,7 +37693,6 @@ var ts; else { write("{"); increaseIndent(); - scopeEmitStart(node); emitCaptureThisForNodeIfNecessary(node); writeLine(); emit(node.body); @@ -35167,11 +37700,10 @@ var ts; writeLine(); var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(16 /* CloseBraceToken */, moduleBlock.statements.end); - scopeEmitEnd(); } write(")("); // write moduleDecl = containingModule.m only if it is not exported es6 module member - if ((node.flags & 2 /* Export */) && !isES6ExportedDeclaration(node)) { + if ((node.flags & 1 /* Export */) && !isES6ExportedDeclaration(node)) { emit(node.name); write(" = "); } @@ -35181,7 +37713,7 @@ var ts; write(" = {}));"); emitEnd(node); if (!isES6ExportedDeclaration(node) && node.name.kind === 69 /* Identifier */ && node.parent === currentSourceFile) { - if (modulekind === 4 /* System */ && (node.flags & 2 /* Export */)) { + if (modulekind === ts.ModuleKind.System && (node.flags & 1 /* Export */)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -35197,8 +37729,8 @@ var ts; * Here we check if alternative name was provided for a given moduleName and return it if possible. */ function tryRenameExternalModule(moduleName) { - if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) { - return "\"" + currentSourceFile.renamedDependencies[moduleName.text] + "\""; + if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { + return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; } @@ -35221,16 +37753,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 225 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 228 /* NamespaceImport */) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 222 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 226 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -35239,7 +37771,7 @@ var ts; ts.forEachChild(node, emitExportImportAssignments); } function emitImportDeclaration(node) { - if (modulekind !== 5 /* ES6 */) { + if (modulekind !== ts.ModuleKind.ES6) { return emitExternalImportDeclaration(node); } // ES6 import @@ -35258,7 +37790,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 228 /* NamespaceImport */) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -35284,16 +37816,19 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 2 /* Export */) !== 0; + var isExportedImport = node.kind === 225 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); - if (modulekind !== 2 /* AMD */) { + var varOrConst = (languageVersion <= 1 /* ES5 */) ? "var " : "const "; + if (modulekind !== ts.ModuleKind.AMD) { emitLeadingComments(node); emitStart(node); if (namespaceDeclaration && !isDefaultImport(node)) { // import x = require("foo") // import * as x from "foo" - if (!isExportedImport) - write("var "); + if (!isExportedImport) { + write(varOrConst); + } + ; emitModuleMemberName(namespaceDeclaration); write(" = "); } @@ -35303,9 +37838,9 @@ var ts; // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - var isNakedImport = 222 /* ImportDeclaration */ && !node.importClause; + var isNakedImport = 226 /* ImportDeclaration */ && !node.importClause; if (!isNakedImport) { - write("var "); + write(varOrConst); write(getGeneratedNameForNode(node)); write(" = "); } @@ -35332,7 +37867,7 @@ var ts; } else if (namespaceDeclaration && isDefaultImport(node)) { // import d, * as x from "foo" - write("var "); + write(varOrConst); emitModuleMemberName(namespaceDeclaration); write(" = "); write(getGeneratedNameForNode(node)); @@ -35351,7 +37886,7 @@ var ts; // - current file is not external module // - import declaration is top level and target is value imported by entity name if (resolver.isReferencedAliasDeclaration(node) || - (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { + (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { emitLeadingComments(node); emitStart(node); // variable declaration for import-equals declaration can be hoisted in system modules @@ -35366,7 +37901,7 @@ var ts; write("export "); write("var "); } - else if (!(node.flags & 2 /* Export */)) { + else if (!(node.flags & 1 /* Export */)) { write("var "); } } @@ -35388,14 +37923,14 @@ var ts; } } function emitExportDeclaration(node) { - ts.Debug.assert(modulekind !== 4 /* System */); - if (modulekind !== 5 /* ES6 */) { + ts.Debug.assert(modulekind !== ts.ModuleKind.System); + if (modulekind !== ts.ModuleKind.ES6) { if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { emitStart(node); var generatedName = getGeneratedNameForNode(node); if (node.exportClause) { // export { x, y, ... } from "foo" - if (modulekind !== 2 /* AMD */) { + if (modulekind !== ts.ModuleKind.AMD) { write("var "); write(generatedName); write(" = "); @@ -35421,15 +37956,17 @@ var ts; } else { // export * from "foo" - writeLine(); - write("__export("); - if (modulekind !== 2 /* AMD */) { - emitRequire(ts.getExternalModuleName(node)); + if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + writeLine(); + write("__export("); + if (modulekind !== ts.ModuleKind.AMD) { + emitRequire(ts.getExternalModuleName(node)); + } + else { + write(generatedName); + } + write(");"); } - else { - write(generatedName); - } - write(");"); } emitEnd(node); } @@ -35455,7 +37992,7 @@ var ts; } } function emitExportOrImportSpecifierList(specifiers, shouldEmit) { - ts.Debug.assert(modulekind === 5 /* ES6 */); + ts.Debug.assert(modulekind === ts.ModuleKind.ES6); var needsComma = false; for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { var specifier = specifiers_1[_a]; @@ -35474,14 +38011,14 @@ var ts; } function emitExportAssignment(node) { if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { - if (modulekind === 5 /* ES6 */) { + if (modulekind === ts.ModuleKind.ES6) { writeLine(); emitStart(node); write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 213 /* FunctionDeclaration */ && - expression.kind !== 214 /* ClassDeclaration */) { + if (expression.kind !== 217 /* FunctionDeclaration */ && + expression.kind !== 218 /* ClassDeclaration */) { write(";"); } emitEnd(node); @@ -35489,7 +38026,7 @@ var ts; else { writeLine(); emitStart(node); - if (modulekind === 4 /* System */) { + if (modulekind === ts.ModuleKind.System) { write(exportFunctionForFile + "(\"default\","); emit(node.expression); write(")"); @@ -35514,11 +38051,11 @@ var ts; externalImports = []; exportSpecifiers = {}; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { // import "mod" @@ -35528,18 +38065,20 @@ var ts; externalImports.push(node); } break; - case 221 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 232 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { + case 225 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 236 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { // import x = require("mod") where x is referenced externalImports.push(node); } break; - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" - externalImports.push(node); - hasExportStars = true; + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } } else if (resolver.isValueAliasDeclaration(node)) { // export { x, y } from "mod" where at least one export is a value symbol @@ -35550,12 +38089,12 @@ var ts; // export { x, y } for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_26 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_26] || (exportSpecifiers[name_26] = [])).push(specifier); + var name_27 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_27] || (exportSpecifiers[name_27] = [])).push(specifier); } } break; - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; @@ -35565,7 +38104,7 @@ var ts; } } function emitExportStarHelper() { - if (hasExportStars) { + if (hasExportStarsToExportValues) { writeLine(); write("function __export(m) {"); increaseIndent(); @@ -35579,16 +38118,22 @@ var ts; function getLocalNameForExternalImport(node) { var namespaceDeclaration = getNamespaceDeclarationNode(node); if (namespaceDeclaration && !isDefaultImport(node)) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); + return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); } - if (node.kind === 222 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 226 /* ImportDeclaration */ && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 228 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 232 /* ExportDeclaration */ && node.moduleSpecifier) { return getGeneratedNameForNode(node); } } - function getExternalModuleNameText(importNode) { + function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { + if (emitRelativePathAsModuleName) { + var name_28 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_28) { + return "\"" + name_28 + "\""; + } + } var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); @@ -35604,8 +38149,8 @@ var ts; for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { var importNode = externalImports_1[_a]; // do not create variable declaration for exports and imports that lack import clause - var skipNode = importNode.kind === 228 /* ExportDeclaration */ || - (importNode.kind === 222 /* ImportDeclaration */ && !importNode.importClause); + var skipNode = importNode.kind === 232 /* ExportDeclaration */ || + (importNode.kind === 226 /* ImportDeclaration */ && !importNode.importClause); if (skipNode) { continue; } @@ -35626,8 +38171,8 @@ var ts; // when resolving exports local exported entries/indirect exported entries in the module // should always win over entries with similar names that were added via star exports // to support this we store names of local/indirect exported entries in a set. - // this set is used to filter names brought by star expors. - if (!hasExportStars) { + // this set is used to filter names brought by star exports. + if (!hasExportStarsToExportValues) { // local names set is needed only in presence of star exports return undefined; } @@ -35638,7 +38183,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; - if (externalImport.kind === 228 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 232 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -35654,7 +38199,7 @@ var ts; increaseIndent(); var started = false; if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; ++i) { + for (var i = 0; i < exportedDeclarations.length; i++) { // write name of exported declaration, i.e 'export var x...' writeExportedName(exportedDeclarations[i]); } @@ -35670,7 +38215,7 @@ var ts; } for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 228 /* ExportDeclaration */) { + if (externalImport.kind !== 232 /* ExportDeclaration */) { continue; } var exportDecl = externalImport; @@ -35756,14 +38301,14 @@ var ts; writeLine(); write("var "); var seen = {}; - for (var i = 0; i < hoistedVars.length; ++i) { + for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_27 = local.kind === 69 /* Identifier */ + var name_29 = local.kind === 69 /* Identifier */ ? local : local.name; - if (name_27) { + if (name_29) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - var text = ts.unescapeIdentifier(name_27.text); + var text = ts.unescapeIdentifier(name_29.text); if (ts.hasProperty(seen, text)) { continue; } @@ -35774,14 +38319,14 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 214 /* ClassDeclaration */ || local.kind === 218 /* ModuleDeclaration */ || local.kind === 217 /* EnumDeclaration */) { + if (local.kind === 218 /* ClassDeclaration */ || local.kind === 222 /* ModuleDeclaration */ || local.kind === 221 /* EnumDeclaration */) { emitDeclarationName(local); } else { emit(local); } var flags = ts.getCombinedNodeFlags(local.kind === 69 /* Identifier */ ? local.parent : local); - if (flags & 2 /* Export */) { + if (flags & 1 /* Export */) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -35795,7 +38340,7 @@ var ts; var f = hoistedFunctionDeclarations_1[_a]; writeLine(); emit(f); - if (f.flags & 2 /* Export */) { + if (f.flags & 1 /* Export */) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -35805,24 +38350,24 @@ var ts; } return exportedDeclarations; function visit(node) { - if (node.flags & 4 /* Ambient */) { + if (node.flags & 2 /* Ambient */) { return; } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 217 /* FunctionDeclaration */) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* ClassDeclaration */) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 217 /* EnumDeclaration */) { + if (node.kind === 221 /* EnumDeclaration */) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -35831,7 +38376,7 @@ var ts; } return; } - if (node.kind === 218 /* ModuleDeclaration */) { + if (node.kind === 222 /* ModuleDeclaration */) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -35840,17 +38385,17 @@ var ts; } return; } - if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + if (node.kind === 215 /* VariableDeclaration */ || node.kind === 167 /* BindingElement */) { if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) { - var name_28 = node.name; - if (name_28.kind === 69 /* Identifier */) { + var name_30 = node.name; + if (name_30.kind === 69 /* Identifier */) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_28); + hoistedVars.push(name_30); } else { - ts.forEachChild(name_28, visit); + ts.forEachChild(name_30, visit); } } return; @@ -35880,11 +38425,11 @@ var ts; // - it is top level block scoped // 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) & 24576 /* BlockScoped */) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */; + return (ts.getCombinedNodeFlags(node) & 3072 /* BlockScoped */) === 0 || + ts.getEnclosingBlockScopeContainer(node).kind === 252 /* SourceFile */; } function isCurrentFileSystemExternalModule() { - return modulekind === 4 /* System */ && ts.isExternalModule(currentSourceFile); + return modulekind === ts.ModuleKind.System && isCurrentFileExternalModule; } function emitSystemModuleBody(node, dependencyGroups, startIndex) { // shape of the body in system modules: @@ -35941,7 +38486,7 @@ var ts; } function emitSetters(exportStarFunction, dependencyGroups) { write("setters:["); - for (var i = 0; i < dependencyGroups.length; ++i) { + for (var i = 0; i < dependencyGroups.length; i++) { if (i !== 0) { write(","); } @@ -35956,21 +38501,21 @@ var ts; var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // fall-through - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== ""); writeLine(); // save import into the local write(importVariableName + " = " + parameterName + ";"); writeLine(); break; - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== ""); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -35983,12 +38528,12 @@ var ts; write(exportFunctionForFile + "({"); writeLine(); increaseIndent(); - for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) { - if (i_2 !== 0) { + for (var i_1 = 0, len = entry.exportClause.elements.length; i_1 < len; i_1++) { + if (i_1 !== 0) { write(","); writeLine(); } - var e = entry.exportClause.elements[i_2]; + var e = entry.exportClause.elements[i_1]; write("\""); emitNodeWithCommentsAndWithoutSourcemap(e.name); write("\": " + parameterName + "[\""); @@ -36000,6 +38545,8 @@ var ts; write("});"); } else { + // collectExternalModuleInfo prefilters star exports to keep only ones that export values + // this means that check 'resolver.moduleExportsSomeValue' is redundant and can be omitted here writeLine(); // export * from 'foo' // emit as: @@ -36020,17 +38567,17 @@ var ts; write("execute: function() {"); increaseIndent(); writeLine(); - for (var i = startIndex; i < node.statements.length; ++i) { + for (var i = startIndex; i < node.statements.length; i++) { var statement = node.statements[i]; switch (statement.kind) { // - function declarations are not emitted because they were already hoisted // - import declarations are not emitted since they are already handled in setters // - export declarations with module specifiers are not emitted since they were already written in setters // - export declarations without module specifiers are emitted preserving the order - case 213 /* FunctionDeclaration */: - case 222 /* ImportDeclaration */: + case 217 /* FunctionDeclaration */: + case 226 /* ImportDeclaration */: continue; - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: if (!statement.moduleSpecifier) { for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { var element = _b[_a]; @@ -36039,7 +38586,7 @@ var ts; } } continue; - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { // - import equals declarations that import external modules are not emitted continue; @@ -36054,7 +38601,13 @@ var ts; writeLine(); write("}"); // execute } - function emitSystemModule(node) { + function writeModuleName(node, emitRelativePathAsModuleName) { + var moduleName = node.moduleName; + if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) { + write("\"" + moduleName + "\", "); + } + } + function emitSystemModule(node, emitRelativePathAsModuleName) { collectExternalModuleInfo(node); // System modules has the following shape // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) @@ -36067,24 +38620,29 @@ var ts; ts.Debug.assert(!exportFunctionForFile); // make sure that name of 'exports' function does not conflict with existing identifiers exportFunctionForFile = makeUniqueName("exports"); + contextObjectForFile = makeUniqueName("context"); writeLine(); write("System.register("); - if (node.moduleName) { - write("\"" + node.moduleName + "\", "); - } + writeModuleName(node, emitRelativePathAsModuleName); write("["); var groupIndices = {}; var dependencyGroups = []; - for (var i = 0; i < externalImports.length; ++i) { - var text = getExternalModuleNameText(externalImports[i]); - if (ts.hasProperty(groupIndices, text)) { + for (var i = 0; i < externalImports.length; i++) { + var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); + if (text === undefined) { + continue; + } + // text should be quoted string + // for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same + var key = text.substr(1, text.length - 2); + if (ts.hasProperty(groupIndices, key)) { // deduplicate/group entries in dependency list by the dependency name - var groupIndex = groupIndices[text]; + var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; } else { - groupIndices[text] = dependencyGroups.length; + groupIndices[key] = dependencyGroups.length; dependencyGroups.push([externalImports[i]]); } if (i !== 0) { @@ -36092,10 +38650,13 @@ var ts; } write(text); } - write("], function(" + exportFunctionForFile + ") {"); + write("], function(" + exportFunctionForFile + ", " + contextObjectForFile + ") {"); writeLine(); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); + writeLine(); + write("var __moduleName = " + contextObjectForFile + " && " + contextObjectForFile + ".id;"); + writeLine(); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -36103,7 +38664,7 @@ var ts; writeLine(); write("});"); } - function getAMDDependencyNames(node, includeNonAmdDependencies) { + function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { // names of modules with corresponding parameter in the factory function var aliasedModuleNames = []; // names of modules with no corresponding parameters in factory function @@ -36125,7 +38686,7 @@ var ts; for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { var importNode = externalImports_4[_c]; // Find the name of the external module - var externalModuleName = getExternalModuleNameText(importNode); + var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); // Find the name of the module alias, if there is one var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { @@ -36138,7 +38699,7 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } - function emitAMDDependencies(node, includeNonAmdDependencies) { + function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { // An AMD define function has the following shape: // define(id?, dependencies?, factory); // @@ -36150,7 +38711,7 @@ var ts; // To ensure this is true in cases of modules with no aliases, e.g.: // `import "module"` or `` // we need to add modules without alias names to the end of the dependencies list - var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies); + var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName); emitAMDDependencyList(dependencyNames); write(", "); emitAMDFactoryHeader(dependencyNames); @@ -36177,17 +38738,15 @@ var ts; } write(") {"); } - function emitAMDModule(node) { + function emitAMDModule(node, emitRelativePathAsModuleName) { emitEmitHelpers(node); collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.moduleName) { - write("\"" + node.moduleName + "\", "); - } - emitAMDDependencies(node, /*includeNonAmdDependencies*/ true); + writeModuleName(node, emitRelativePathAsModuleName); + emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36198,7 +38757,7 @@ var ts; write("});"); } function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -36218,7 +38777,7 @@ var ts; writeLines(" }\n})("); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36232,7 +38791,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); @@ -36295,7 +38854,9 @@ var ts; // Replace entities like   result = result.replace(/&(\w+);/g, function (s, m) { if (entities[m] !== undefined) { - return String.fromCharCode(entities[m]); + var ch = String.fromCharCode(entities[m]); + // " needs to be escaped + return ch === "\"" ? "\\\"" : ch; } else { return s; @@ -36304,6 +38865,18 @@ var ts; } return result; } + function isJsxChildEmittable(child) { + if (child.kind === 244 /* JsxExpression */) { + // Don't emit empty expressions + return !!child.expression; + } + else if (child.kind === 240 /* JsxText */) { + // Don't emit empty strings + return !!getTextToEmit(child); + } + return true; + } + ; function getTextToEmit(node) { switch (compilerOptions.jsx) { case 2 /* React */: @@ -36347,24 +38920,41 @@ var ts; } } } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { + function isUseStrictPrologue(node) { + return !!node.expression.text.match(/use strict/); + } + function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { + if (writeUseStrict) { + if (startWithNewLine) { + writeLine(); + } + write("\"use strict\";"); + } + } + function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { + var foundUseStrict = false; + for (var i = 0; i < statements.length; i++) { if (ts.isPrologueDirective(statements[i])) { + if (isUseStrictPrologue(statements[i])) { + foundUseStrict = true; + } if (startWithNewLine || i > 0) { writeLine(); } emit(statements[i]); } else { + ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); // return index of the first non prologue directive return i; } } + ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); return statements.length; } function writeLines(text) { var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; ++i) { + for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line.length) { writeLine(); @@ -36377,22 +38967,22 @@ var ts; if (!compilerOptions.noEmitHelpers) { // Only Emit __extends function when target ES5. // For target ES6 and above, we can emit classDeclaration as is. - if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */)) { + if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && node.flags & 262144 /* HasClassExtends */)) { writeLines(extendsHelper); extendsEmitted = true; } - if (!decorateEmitted && resolver.getNodeCheckFlags(node) & 16 /* EmitDecorate */) { + if (!decorateEmitted && node.flags & 524288 /* HasDecorators */) { writeLines(decorateHelper); if (compilerOptions.emitDecoratorMetadata) { writeLines(metadataHelper); } decorateEmitted = true; } - if (!paramEmitted && resolver.getNodeCheckFlags(node) & 32 /* EmitParam */) { + if (!paramEmitted && node.flags & 1048576 /* HasParamDecorators */) { writeLines(paramHelper); paramEmitted = true; } - if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & 64 /* EmitAwaiter */) { + if (!awaiterEmitted && node.flags & 2097152 /* HasAsyncFunctions */) { writeLines(awaiterHelper); awaiterEmitted = true; } @@ -36404,8 +38994,13 @@ var ts; emitShebang(); emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */]; - emitModule(node); + if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { + var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ts.ModuleKind.CommonJS]; + emitModule(node); + } + else { + bundleEmitDelegates[modulekind](node, /*emitRelativePathAsModuleName*/ true); + } } else { // emit prologue directives prior to __extends @@ -36413,7 +39008,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36421,12 +39016,15 @@ var ts; } emitLeadingComments(node.endOfFileToken); } + function emit(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + } function emitNodeWithCommentsAndWithoutSourcemap(node) { emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); } function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { if (node) { - if (node.flags & 4 /* Ambient */) { + if (node.flags & 2 /* Ambient */) { return emitCommentsOnNotEmittedNode(node); } if (isSpecializedCommentHandling(node)) { @@ -36443,33 +39041,53 @@ var ts; } } } + function emitNodeWithSourceMap(node) { + if (node) { + emitStart(node); + emitNodeWithoutSourceMap(node); + emitEnd(node); + } + } function emitNodeWithoutSourceMap(node) { if (node) { emitJavaScriptWorker(node); } } + function changeSourceMapEmit(writer) { + sourceMap = writer; + emitStart = writer.emitStart; + emitEnd = writer.emitEnd; + emitPos = writer.emitPos; + setSourceFile = writer.setSourceFile; + } + function withTemporaryNoSourceMap(callback) { + var prevSourceMap = sourceMap; + setSourceMapWriterEmit(ts.getNullSourceMapWriter()); + callback(); + setSourceMapWriterEmit(prevSourceMap); + } function isSpecializedCommentHandling(node) { 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 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 227 /* ExportAssignment */: + case 219 /* InterfaceDeclaration */: + case 217 /* FunctionDeclaration */: + case 226 /* ImportDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 231 /* ExportAssignment */: return true; } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: // Only emit the leading/trailing comments for a module if we're actually // emitting the module as well. return shouldEmitModuleDeclaration(node); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: // Only emit the leading/trailing comments for an enum if we're actually // emitting the module as well. return shouldEmitEnumDeclaration(node); @@ -36481,9 +39099,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 !== 192 /* Block */ && + if (node.kind !== 196 /* Block */ && node.parent && - node.parent.kind === 174 /* ArrowFunction */ && + node.parent.kind === 178 /* ArrowFunction */ && node.parent.body === node && compilerOptions.target <= 1 /* ES5 */) { return false; @@ -36496,13 +39114,13 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return emitIdentifier(node); - case 138 /* Parameter */: + case 140 /* Parameter */: return emitParameter(node); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return emitMethod(node); - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: return emitAccessor(node); case 97 /* ThisKeyword */: return emitThis(node); @@ -36522,142 +39140,142 @@ var ts; case 13 /* TemplateMiddle */: case 14 /* TemplateTail */: return emitLiteral(node); - case 183 /* TemplateExpression */: + case 187 /* TemplateExpression */: return emitTemplateExpression(node); - case 190 /* TemplateSpan */: + case 194 /* TemplateSpan */: return emitTemplateSpan(node); - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: + case 237 /* JsxElement */: + case 238 /* JsxSelfClosingElement */: return emitJsxElement(node); - case 236 /* JsxText */: + case 240 /* JsxText */: return emitJsxText(node); - case 240 /* JsxExpression */: + case 244 /* JsxExpression */: return emitJsxExpression(node); - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: return emitQualifiedName(node); - case 161 /* ObjectBindingPattern */: + case 165 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 162 /* ArrayBindingPattern */: + case 166 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 163 /* BindingElement */: + case 167 /* BindingElement */: return emitBindingElement(node); - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return emitArrayLiteral(node); - case 165 /* ObjectLiteralExpression */: + case 169 /* ObjectLiteralExpression */: return emitObjectLiteral(node); - case 245 /* PropertyAssignment */: + case 249 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 246 /* ShorthandPropertyAssignment */: + case 250 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 136 /* ComputedPropertyName */: + case 138 /* ComputedPropertyName */: return emitComputedPropertyName(node); - case 166 /* PropertyAccessExpression */: + case 170 /* PropertyAccessExpression */: return emitPropertyAccess(node); - case 167 /* ElementAccessExpression */: + case 171 /* ElementAccessExpression */: return emitIndexedAccess(node); - case 168 /* CallExpression */: + case 172 /* CallExpression */: return emitCallExpression(node); - case 169 /* NewExpression */: + case 173 /* NewExpression */: return emitNewExpression(node); - case 170 /* TaggedTemplateExpression */: + case 174 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 171 /* TypeAssertionExpression */: + case 175 /* TypeAssertionExpression */: return emit(node.expression); - case 189 /* AsExpression */: + case 193 /* AsExpression */: return emit(node.expression); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return emitParenExpression(node); - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return emitFunctionDeclaration(node); - case 175 /* DeleteExpression */: + case 179 /* DeleteExpression */: return emitDeleteExpression(node); - case 176 /* TypeOfExpression */: + case 180 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 177 /* VoidExpression */: + case 181 /* VoidExpression */: return emitVoidExpression(node); - case 178 /* AwaitExpression */: + case 182 /* AwaitExpression */: return emitAwaitExpression(node); - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 180 /* PostfixUnaryExpression */: + case 184 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return emitBinaryExpression(node); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return emitConditionalExpression(node); - case 185 /* SpreadElementExpression */: + case 189 /* SpreadElementExpression */: return emitSpreadElementExpression(node); - case 184 /* YieldExpression */: + case 188 /* YieldExpression */: return emitYieldExpression(node); - case 187 /* OmittedExpression */: + case 191 /* OmittedExpression */: return; - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 196 /* Block */: + case 223 /* ModuleBlock */: return emitBlock(node); - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return emitVariableStatement(node); - case 194 /* EmptyStatement */: + case 198 /* EmptyStatement */: return write(";"); - case 195 /* ExpressionStatement */: + case 199 /* ExpressionStatement */: return emitExpressionStatement(node); - case 196 /* IfStatement */: + case 200 /* IfStatement */: return emitIfStatement(node); - case 197 /* DoStatement */: + case 201 /* DoStatement */: return emitDoStatement(node); - case 198 /* WhileStatement */: + case 202 /* WhileStatement */: return emitWhileStatement(node); - case 199 /* ForStatement */: + case 203 /* ForStatement */: return emitForStatement(node); - case 201 /* ForOfStatement */: - case 200 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 204 /* ForInStatement */: return emitForInOrForOfStatement(node); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 206 /* ContinueStatement */: + case 207 /* BreakStatement */: return emitBreakOrContinueStatement(node); - case 204 /* ReturnStatement */: + case 208 /* ReturnStatement */: return emitReturnStatement(node); - case 205 /* WithStatement */: + case 209 /* WithStatement */: return emitWithStatement(node); - case 206 /* SwitchStatement */: + case 210 /* SwitchStatement */: return emitSwitchStatement(node); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 245 /* CaseClause */: + case 246 /* DefaultClause */: return emitCaseOrDefaultClause(node); - case 207 /* LabeledStatement */: + case 211 /* LabeledStatement */: return emitLabeledStatement(node); - case 208 /* ThrowStatement */: + case 212 /* ThrowStatement */: return emitThrowStatement(node); - case 209 /* TryStatement */: + case 213 /* TryStatement */: return emitTryStatement(node); - case 244 /* CatchClause */: + case 248 /* CatchClause */: return emitCatchClause(node); - case 210 /* DebuggerStatement */: + case 214 /* DebuggerStatement */: return emitDebuggerStatement(node); - case 211 /* VariableDeclaration */: + case 215 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: return emitClassExpression(node); - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: return emitClassDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 247 /* EnumMember */: + case 251 /* EnumMember */: return emitEnumMember(node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: return emitImportDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: return emitExportDeclaration(node); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return emitExportAssignment(node); - case 248 /* SourceFile */: + case 252 /* SourceFile */: return emitSourceFileNode(node); } } @@ -36666,7 +39284,7 @@ var ts; } function getLeadingCommentsWithoutDetachedComments() { // get the leading comments from detachedPos - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); + var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -36683,10 +39301,10 @@ var ts; function isTripleSlashComment(comment) { // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text // so that we don't end up computing comment string and doing match for all // comments - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ && + if (currentText.charCodeAt(comment.pos + 1) === 47 /* slash */ && comment.pos + 2 < comment.end && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */) { - var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end); + currentText.charCodeAt(comment.pos + 2) === 47 /* slash */) { + var textSubStr = currentText.substring(comment.pos, comment.end); return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? true : false; @@ -36696,14 +39314,14 @@ 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 === 248 /* SourceFile */ || node.pos !== node.parent.pos) { + if (node.parent.kind === 252 /* SourceFile */ || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { // get comments without detached comments return getLeadingCommentsWithoutDetachedComments(); } else { // get the leading comments from the node - return ts.getLeadingCommentRangesOfNode(node, currentSourceFile); + return ts.getLeadingCommentRangesOfNodeFromText(node, currentText); } } } @@ -36711,8 +39329,8 @@ 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 === 248 /* SourceFile */ || node.end !== node.parent.end) { - return ts.getTrailingCommentRanges(currentSourceFile.text, node.end); + if (node.parent.kind === 252 /* SourceFile */ || node.end !== node.parent.end) { + return ts.getTrailingCommentRanges(currentText, node.end); } } } @@ -36720,10 +39338,10 @@ var ts; * Emit comments associated with node that will not be emitted into JS file */ function emitCommentsOnNotEmittedNode(node) { - emitLeadingCommentsWorker(node, /*isEmittedNode:*/ false); + emitLeadingCommentsWorker(node, /*isEmittedNode*/ false); } function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, /*isEmittedNode:*/ true); + return emitLeadingCommentsWorker(node, /*isEmittedNode*/ true); } function emitLeadingCommentsWorker(node, isEmittedNode) { if (compilerOptions.removeComments) { @@ -36741,14 +39359,14 @@ var ts; // declare var x; // /// // interface F {} - // The first /// will NOT be removed while the second one will be removed eventhough both node will not be emitted + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted if (node.pos === 0) { leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); } } - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); } function emitTrailingComments(node) { if (compilerOptions.removeComments) { @@ -36757,7 +39375,7 @@ var ts; // Emit the trailing comments only if the parent's end doesn't match var trailingComments = getTrailingCommentsToEmit(node); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ - ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); } /** * Emit trailing comments at the position. The term trailing comment is used here to describe following comment: @@ -36768,9 +39386,9 @@ var ts; if (compilerOptions.removeComments) { return; } - var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos); + var trailingComments = ts.getTrailingCommentRanges(currentText, pos); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ - ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); } function emitLeadingCommentsOfPositionWorker(pos) { if (compilerOptions.removeComments) { @@ -36783,14 +39401,14 @@ var ts; } else { // get the leading comments from the node - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); + leadingComments = ts.getLeadingCommentRanges(currentText, pos); } - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments); // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); } function emitDetachedCommentsAndUpdateCommentsInfo(node) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); + var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments); if (currentDetachedCommentInfo) { if (detachedCommentsInfo) { detachedCommentsInfo.push(currentDetachedCommentInfo); @@ -36800,18 +39418,31 @@ var ts; } } } + function writeComment(text, lineMap, writer, comment, newLine) { + emitPos(comment.pos); + ts.writeCommentRange(text, lineMap, writer, comment, newLine); + emitPos(comment.end); + } function emitShebang() { - var shebang = ts.getShebang(currentSourceFile.text); + var shebang = ts.getShebang(currentText); if (shebang) { write(shebang); + writeLine(); } } - var _a; + var _a, _b; } - function emitFile(jsFilePath, sourceFile) { - emitJavaScript(jsFilePath, sourceFile); - if (compilerOptions.declaration) { - ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); + function emitFile(_a, sourceFiles, isBundledEmit) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + // Make sure not to write js File and source map file if any of them cannot be written + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; + } + if (declarationFilePath) { + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } } } @@ -36828,11 +39459,11 @@ var ts; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ var emptyArray = []; - ts.version = "1.8.0"; - function findConfigFile(searchPath) { + ts.version = "1.9.0"; + function findConfigFile(searchPath, fileExists) { var fileName = "tsconfig.json"; while (true) { - if (ts.sys.fileExists(fileName)) { + if (fileExists(fileName)) { return fileName; } var parentPath = ts.getDirectoryPath(searchPath); @@ -36851,88 +39482,409 @@ var ts; return ts.normalizePath(referencedFileName); } ts.resolveTripleslashReference = resolveTripleslashReference; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var moduleResolution = compilerOptions.moduleResolution !== undefined - ? compilerOptions.moduleResolution - : compilerOptions.module === 1 /* CommonJS */ ? 2 /* NodeJs */ : 1 /* Classic */; - switch (moduleResolution) { - case 2 /* NodeJs */: return nodeModuleNameResolver(moduleName, containingFile, host); - case 1 /* Classic */: return classicNameResolver(moduleName, containingFile, compilerOptions, host); - } + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); } - ts.resolveModuleName = resolveModuleName; - function nodeModuleNameResolver(moduleName, containingFile, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { - var failedLookupLocations = []; - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host); - if (resolvedFileName) { - return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceModuleResolution && host.trace !== undefined; + } + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return str.indexOf(suffix, expectedPos) === expectedPos; + } + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + if (ts.isRootedDiskPath(moduleName)) { + return false; + } + var i = moduleName.lastIndexOf("./", 1); + var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */); + return !startsWithDotSlashOrDotDotSlash; + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); } - resolvedFileName = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); - return resolvedFileName - ? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } else { - return loadModuleFromNodeModules(moduleName, containingDirectory, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); } } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var longestMatchPrefixLength = -1; + var matchedPattern; + var matchedStar; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + for (var key in state.compilerOptions.paths) { + var pattern = key; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (moduleName.length >= prefix.length + suffix.length && + startsWith(moduleName, prefix) && + endsWith(moduleName, suffix)) { + // use length of prefix as betterness criteria + if (prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = prefix.length; + matchedPattern = pattern; + matchedStar = moduleName.substr(prefix.length, moduleName.length - suffix.length); + } + } + } + else if (pattern === moduleName) { + // pattern was matched as is - no need to search further + matchedPattern = pattern; + matchedStar = undefined; + break; + } + } + } + if (matchedPattern) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPattern); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPattern]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("\*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); + } + var isExternalLibraryImport = false; + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function loadNodeModuleFromFile(candidate, failedLookupLocation, host) { - return ts.forEach(ts.moduleFileExtensions, tryLoad); + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + return ts.forEach(extensions, tryLoad); function tryLoad(ext) { + if (ext === ".tsx" && state.skipTsx) { + return undefined; + } var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (host.fileExists(fileName)) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName); + } return fileName; } else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } failedLookupLocation.push(fileName); return undefined; } } } - function loadNodeModuleFromDirectory(candidate, failedLookupLocation, host) { + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { var packageJsonPath = ts.combinePaths(candidate, "package.json"); - if (host.fileExists(packageJsonPath)) { - var jsonContent; + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var jsonContent = void 0; try { - var jsonText = host.readFile(packageJsonPath); + var jsonText = state.host.readFile(packageJsonPath); jsonContent = jsonText ? JSON.parse(jsonText) : { typings: undefined }; } catch (e) { - // gracefully handle if readFile fails or returns not JSON + // gracefully handle if readFile fails or returns not JSON jsonContent = { typings: undefined }; } if (jsonContent.typings) { - var result = loadNodeModuleFromFile(ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); - if (result) { - return result; + if (typeof jsonContent.typings === "string") { + var typingsFile = ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile); + } + var result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typingsFile), state.host), state); + if (result) { + return result; + } + } + else if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings); + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_typings_field); } } } else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocation.push(packageJsonPath); } - return loadNodeModuleFromFile(ts.combinePaths(candidate, "index"), failedLookupLocation, host); + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } - function loadModuleFromNodeModules(moduleName, directory, host) { - var failedLookupLocations = []; + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { directory = ts.normalizeSlashes(directory); while (true) { var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var result = loadNodeModuleFromFile(candidate, failedLookupLocations, host); + // Load only typescript files irrespective of allowJs option if loading from node modules + var result = loadModuleFromFile(candidate, ts.supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { - return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; + return result; } - result = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); + result = loadNodeModuleFromDirectory(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { - return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; + return result; } } var parentPath = ts.getDirectoryPath(directory); @@ -36941,45 +39893,36 @@ var ts; } directory = parentPath; } - return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - function nameStartsWithDotSlashOrDotDotSlash(name) { - var i = name.lastIndexOf("./", 1); - return i === 0 || (i === 1 && name.charCodeAt(0) === 46 /* dot */); + return undefined; } function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - // module names that contain '!' are used to reference resources and are not resolved to actual files on disk - if (moduleName.indexOf("!") != -1) { - return { resolvedModule: undefined, failedLookupLocations: [] }; - } - var searchPath = ts.getDirectoryPath(containingFile); - var searchName; + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); + } var referencedSourceFile; - while (true) { - searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - referencedSourceFile = ts.forEach(ts.supportedExtensions, function (extension) { - if (extension === ".tsx" && !compilerOptions.jsx) { - // resolve .tsx files only if jsx support is enabled - // 'logical not' handles both undefined and None cases - return undefined; + if (moduleHasNonRelativeName(moduleName)) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + if (referencedSourceFile) { + break; } - var candidate = searchName + extension; - if (host.fileExists(candidate)) { - return candidate; + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + break; } - else { - failedLookupLocations.push(candidate); - } - }); - if (referencedSourceFile) { - break; + containingDirectory = parentPath; } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); } return referencedSourceFile ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } @@ -36988,11 +39931,9 @@ var ts; ts.classicNameResolver = classicNameResolver; /* @internal */ ts.defaultInitCompilerOptions = { - module: 1 /* CommonJS */, - target: 0 /* ES3 */, + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, noImplicitAny: false, - outDir: "built", - rootDir: ".", sourceMap: false }; function createCompilerHost(options, setParentNodes) { @@ -37061,14 +40002,16 @@ var ts; getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); } + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + trace: function (s) { return ts.sys.write(s + newLine); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); } }; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -37106,15 +40049,36 @@ var ts; var noDiagnosticsTypeChecker; var classifiableNames; var skipDefaultLib = options.noLib; + var supportedExtensions = ts.getSupportedExtensions(options); var start = new Date().getTime(); host = host || createCompilerHost(options); + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var currentDirectory = host.getCurrentDirectory(); var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) - : (function (moduleNames, containingFile) { return ts.map(moduleNames, function (moduleName) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }); }); + : (function (moduleNames, containingFile) { + var resolvedModuleNames = []; + // resolveModuleName does not store any results between calls. + // lookup is a local cache to avoid resolving the same module name several times + var lookup = {}; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedName = void 0; + if (ts.hasProperty(lookup, moduleName)) { + resolvedName = lookup[moduleName]; + } + else { + resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule; + lookup[moduleName] = resolvedName; + } + resolvedModuleNames.push(resolvedName); + } + return resolvedModuleNames; + }); var filesByName = ts.createFileMap(); // stores 'filename -> file association' ignoring case - // used to track cases when two file names differ only in casing + // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (oldProgram) { // check properties that can affect structure of the program or module resolution strategy @@ -37124,24 +40088,23 @@ var ts; (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx)) { + (oldOptions.jsx !== options.jsx) || + (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } if (!tryReuseStructureFromOldProgram()) { - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + ts.forEach(rootNames, function (name) { return 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), true); + processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true); } } - verifyCompilerOptions(); // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; - ts.programTime += new Date().getTime() - start; program = { getRootFileNames: function () { return rootNames; }, getSourceFile: getSourceFile, @@ -37155,7 +40118,7 @@ var ts; getTypeChecker: getTypeChecker, getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: function () { return commonSourceDirectory; }, + getCommonSourceDirectory: getCommonSourceDirectory, emit: emit, getCurrentDirectory: function () { return currentDirectory; }, getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, @@ -37164,7 +40127,27 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; } }; + verifyCompilerOptions(); + ts.programTime += new Date().getTime() - start; return program; + function getCommonSourceDirectory() { + if (typeof commonSourceDirectory === "undefined") { + if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + // If a rootDir is specified and is valid use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(files); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } function getClassifiableNames() { if (!classifiableNames) { // Initialize a checker so that all our files are bound. @@ -37210,17 +40193,21 @@ var ts; // tripleslash references has changed return false; } - // check imports + // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed return false; } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + return false; + } if (resolveModuleNamesWorker) { - var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); + var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct - for (var i = 0; i < moduleNames.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); var resolutionChanged = oldResolution @@ -37245,7 +40232,7 @@ var ts; newSourceFiles.push(newSourceFile); } // update fileName -> file mapping - for (var i = 0, len = newSourceFiles.length; i < len; ++i) { + for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; @@ -37266,7 +40253,8 @@ var ts; getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, - writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }) + writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }), + isEmitBlocked: isEmitBlocked }; } function getDiagnosticsProducingTypeChecker() { @@ -37279,12 +40267,25 @@ var ts; var _this = this; return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + var declarationDiagnostics = []; + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emitSkipped: true }; + } // If the noEmitOnError flag is set, then check if we have any errors so far. If so, // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError && getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken).length > 0) { - return { diagnostics: [], sourceMaps: undefined, emitSkipped: true }; + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { diagnostics: diagnostics, sourceMaps: undefined, emitSkipped: true }; + } } // Create the emit resolver outside of the "emitTime" tracking code below. That way // any cost associated with it (like type checking) are appropriate associated with @@ -37337,7 +40338,7 @@ var ts; // We were canceled while performing the operation. Because our type checker // might be a bad state, we need to throw it away. // - // Note: we are overly agressive here. We do not actually *have* to throw away + // Note: we are overly aggressive here. We do not actually *have* to throw away // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep // the lifetimes of these two TypeCheckers the same. Also, we generally only // cancel when the user has made a change anyways. And, in that case, we (the @@ -37354,12 +40355,170 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + // For JavaScript files, we don't want to report the normal typescript semantic errors. + // Instead, we just report errors for using TypeScript-only constructs from within a + // JavaScript file. + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? + getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : + typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } + function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var diagnostics = []; + walk(sourceFile); + return diagnostics; + function walk(node) { + if (!node) { + return false; + } + switch (node.kind) { + case 225 /* ImportEqualsDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return true; + case 231 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 218 /* ClassDeclaration */: + var classDeclaration = node; + if (checkModifiers(classDeclaration.modifiers) || + checkTypeParameters(classDeclaration.typeParameters)) { + return true; + } + break; + case 247 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 106 /* ImplementsKeyword */) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 219 /* InterfaceDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 222 /* ModuleDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 220 /* TypeAliasDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return true; + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 177 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: + case 178 /* ArrowFunction */: + case 217 /* FunctionDeclaration */: + var functionDeclaration = node; + if (checkModifiers(functionDeclaration.modifiers) || + checkTypeParameters(functionDeclaration.typeParameters) || + checkTypeAnnotation(functionDeclaration.type)) { + return true; + } + break; + case 197 /* VariableStatement */: + var variableStatement = node; + if (checkModifiers(variableStatement.modifiers)) { + return true; + } + break; + case 215 /* VariableDeclaration */: + var variableDeclaration = node; + if (checkTypeAnnotation(variableDeclaration.type)) { + return true; + } + break; + case 172 /* CallExpression */: + case 173 /* NewExpression */: + var expression = node; + if (expression.typeArguments && expression.typeArguments.length > 0) { + var start_2 = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 140 /* Parameter */: + var parameter = node; + if (parameter.modifiers) { + var start_3 = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return true; + } + if (parameter.questionToken) { + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return true; + } + if (parameter.type) { + diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 143 /* PropertyDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 221 /* EnumDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 175 /* 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 141 /* Decorator */: + if (!options.experimentalDecorators) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + return true; + } + return ts.forEachChild(node, walk); + } + function checkTypeParameters(typeParameters) { + if (typeParameters) { + var start_4 = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkTypeAnnotation(type) { + if (type) { + diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkModifiers(modifiers) { + if (modifiers) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 127 /* ReadonlyKeyword */: + case 122 /* DeclareKeyword */: + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + // These are all legal modifiers. + case 113 /* StaticKeyword */: + case 82 /* ExportKeyword */: + case 74 /* ConstKeyword */: + case 77 /* DefaultKeyword */: + case 115 /* AbstractKeyword */: + } + } + } + return false; + } + }); + } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (!ts.isDeclarationFile(sourceFile)) { @@ -37393,21 +40552,32 @@ var ts; function moduleNameIsEqualTo(a, b) { return a.text === b.text; } + function getTextOfLiteral(literal) { + return literal.text; + } function collectExternalModuleReferences(file) { if (file.imports) { return; } + var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isExternalModuleFile = ts.isExternalModule(file); var imports; + var moduleAugmentations; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; - collect(node, /* allowRelativeModuleNames */ true); + collectModuleReferences(node, /*inAmbientModule*/ false); + if (isJavaScriptFile) { + collectRequireCalls(node); + } } file.imports = imports || emptyArray; - function collect(node, allowRelativeModuleNames) { + file.moduleAugmentations = moduleAugmentations || emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: + case 226 /* ImportDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 232 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) { break; @@ -37415,25 +40585,44 @@ var ts; if (!moduleNameExpr.text) { break; } - if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + if (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { (imports || (imports = [])).push(moduleNameExpr); } break; - case 218 /* ModuleDeclaration */: - if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* 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. - // The StringLiteral must specify a top - level external module name. - // Relative external module names are not permitted - ts.forEachChild(node.body, function (node) { - // TypeScript 1.0 spec (April 2014): 12.1.6 - // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules - // only through top - level external module names. Relative external module names are not permitted. - collect(node, /* allowRelativeModuleNames */ false); - }); + case 222 /* ModuleDeclaration */: + if (ts.isAmbientModule(node) && (inAmbientModule || node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + var moduleName = node.name; + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { + (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); + } + else if (!inAmbientModule) { + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + // NOTE: body of ambient module is always a module block + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } + } } - break; + } + } + function collectRequireCalls(node) { + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + (imports || (imports = [])).push(node.arguments[0]); + } + else { + ts.forEachChild(node, collectRequireCalls); } } } @@ -37441,9 +40630,9 @@ var ts; var diagnosticArgument; var diagnostic; if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; + diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; @@ -37461,7 +40650,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -37486,12 +40675,12 @@ var ts; } } // Get source file from normalized fileName - function findSourceFile(fileName, normalizedAbsolutePath, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(normalizedAbsolutePath)) { - var file_1 = filesByName.get(normalizedAbsolutePath); + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + if (filesByName.contains(path)) { + var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== normalizedAbsolutePath) { + if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } return file_1; @@ -37505,17 +40694,17 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); - filesByName.set(normalizedAbsolutePath, file); + filesByName.set(path, file); if (file) { - file.path = normalizedAbsolutePath; + file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case - var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); + var existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(normalizedAbsolutePath, file); + filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -37526,7 +40715,6 @@ var ts; // always process imported modules to record module name resolutions processImportedModules(file, basePath); if (isDefaultLib) { - file.isDefaultLib = true; files.unshift(file); } else { @@ -37538,7 +40726,7 @@ var ts; function processReferencedFiles(file, basePath) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end); + processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end); }); } function getCanonicalFileName(fileName) { @@ -37546,19 +40734,28 @@ var ts; } function processImportedModules(file, basePath) { collectExternalModuleReferences(file); - if (file.imports.length) { + if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = {}; - var moduleNames = ts.map(file.imports, function (name) { return name.text; }); + var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); - for (var i = 0; i < file.imports.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - if (resolution && !options.noResolve) { - var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + // add file to program only if: + // - resolution was successful + // - noResolve is falsy + // - module name come from the list fo imports + var shouldAddFile = resolution && + !options.noResolve && + i < file.imports.length; + if (shouldAddFile) { + var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { - if (!ts.isExternalModule(importedFile)) { - var start_2 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); + // Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files, + // this check is ok. Otherwise this would be never true for javascript file + if (!ts.isExternalModule(importedFile) && importedFile.statements.length) { + var start_5 = ts.getTokenPosOfNode(file.imports[i], file); + fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { var firstRef = importedFile.referencedFiles[0]; @@ -37576,7 +40773,7 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var commonPathComponents; - ts.forEach(files, function (sourceFile) { + var failed = ts.forEach(files, function (sourceFile) { // Each file contributes into common source file path if (ts.isDeclarationFile(sourceFile)) { return; @@ -37589,10 +40786,10 @@ var ts; return; } for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; + // Failed to find any common path component + return true; } // New common path found that is 0 -> i-1 commonPathComponents.length = i; @@ -37604,14 +40801,21 @@ var ts; commonPathComponents.length = sourcePathComponents.length; } }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } + if (!commonPathComponents) { + return currentDirectory; + } return ts.getNormalizedPathFromPathComponents(commonPathComponents); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -37645,14 +40849,33 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } - if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap")); + } + if (options.paths && options.baseUrl === undefined) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!hasZeroOrOneAsteriskCharacter(key)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); + } + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var subst = _a[_i]; + if (!hasZeroOrOneAsteriskCharacter(subst)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); + } + } } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } + if (options.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); + } } if (options.out && options.outFile) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); @@ -37662,16 +40885,15 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } - if (options.sourceRoot) { + if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } - return; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); if (options.isolatedModules) { - if (!options.module && languageVersion < 2 /* ES6 */) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES6 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -37680,34 +40902,29 @@ var ts; programDiagnostics.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) { + else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } // Cannot specify module gen target of es6 when below es6 - if (options.module === 5 /* ES6 */ && languageVersion < 2 /* ES6 */) { + if (options.module === ts.ModuleKind.ES6 && languageVersion < 2 /* ES6 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } + // Cannot specify module gen that isn't amd or system with --out + if (outFile && options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || options.sourceRoot || - (options.mapRoot && - (!outFile || firstExternalModuleSourceFile !== undefined))) { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { - // If a rootDir is specified and is valid use it as the commonSourceDirectory - commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); - } - else { - // Compute the commonSourceDirectory from the input files - commonSourceDirectory = computeCommonSourceDirectory(files); - } - if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { - // Make sure directory path ends with directory separator so this string can directly - // used to replace with "" to get the relative path of the source file and the relative path doesn't - // start with / making it rooted path - commonSourceDirectory += ts.directorySeparator; + options.mapRoot) { + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { @@ -37724,10 +40941,47 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } + else if (options.allowJs && options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } + if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + // Report error if the output overwrites input file + if (filesByName.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + } + // Report error if multiple files write into same file + if (emitFilesSeen.contains(emitFilePath)) { + // Already seen the same emit file - report error + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + } + else { + emitFilesSeen.set(emitFilePath, true); + } + } + } + } + function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); } } ts.createProgram = createProgram; @@ -37788,6 +41042,11 @@ var ts; description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, error: ts.Diagnostics.Argument_for_jsx_must_be_preserve_or_react }, + { + name: "reactNamespace", + type: "string", + description: ts.Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit + }, { name: "listFiles", type: "boolean" @@ -37807,16 +41066,17 @@ var ts; name: "module", shortName: "m", type: { - "commonjs": 1 /* CommonJS */, - "amd": 2 /* AMD */, - "system": 4 /* System */, - "umd": 3 /* UMD */, - "es6": 5 /* ES6 */, - "es2015": 5 /* ES2015 */ + "none": ts.ModuleKind.None, + "commonjs": ts.ModuleKind.CommonJS, + "amd": ts.ModuleKind.AMD, + "system": ts.ModuleKind.System, + "umd": ts.ModuleKind.UMD, + "es6": ts.ModuleKind.ES6, + "es2015": ts.ModuleKind.ES2015 }, description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND, - error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015 + error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none }, { name: "newLine", @@ -37983,8 +41243,8 @@ var ts; { name: "moduleResolution", type: { - "node": 2 /* NodeJs */, - "classic": 1 /* Classic */ + "node": ts.ModuleResolutionKind.NodeJs, + "classic": ts.ModuleResolutionKind.Classic }, description: ts.Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, error: ts.Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic @@ -38013,6 +41273,47 @@ var ts; name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "baseUrl", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + isTSConfigOnly: true + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "object", + isTSConfigOnly: true, + isFilePath: true + }, + { + name: "traceModuleResolution", + type: "boolean", + description: ts.Diagnostics.Enable_tracing_of_the_module_resolution_process + }, + { + name: "allowJs", + type: "boolean", + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "noImplicitUseStrict", + type: "boolean", + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output } ]; var optionNameMapCache; @@ -38047,7 +41348,8 @@ var ts; function parseStrings(args) { var i = 0; while (i < args.length) { - var s = args[i++]; + var s = args[i]; + i++; if (s.charCodeAt(0) === 64 /* at */) { parseResponseFile(s.slice(1)); } @@ -38059,30 +41361,38 @@ var ts; } if (ts.hasProperty(optionNameMap, s)) { var opt = optionNameMap[s]; - // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). - if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); } - switch (opt.type) { - case "number": - options[opt.name] = parseInt(args[i++]); - break; - case "boolean": - options[opt.name] = true; - break; - case "string": - options[opt.name] = args[i++] || ""; - break; - // If not a primitive, the possible types are specified in what is effectively a map of options. - default: - var map_2 = opt.type; - var key = (args[i++] || "").toLowerCase(); - if (ts.hasProperty(map_2, key)) { - options[opt.name] = map_2[key]; - } - else { - errors.push(ts.createCompilerDiagnostic(opt.error)); - } + else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + options[opt.name] = true; + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + var map_1 = opt.type; + var key = (args[i] || "").toLowerCase(); + i++; + if (ts.hasProperty(map_1, key)) { + options[opt.name] = map_1[key]; + } + else { + errors.push(ts.createCompilerDiagnostic(opt.error)); + } + } } } else { @@ -38191,8 +41501,10 @@ var ts; * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json, host, basePath) { - var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors; + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { + if (existingOptions === void 0) { existingOptions = {}; } + var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath, configFileName), optionsFromJsonConfigFile = _a.options, errors = _a.errors; + var options = ts.extend(existingOptions, optionsFromJsonConfigFile); return { options: options, fileNames: getFileNames(), @@ -38209,23 +41521,47 @@ var ts; } } else { - var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; - var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); - for (var i = 0; i < sysFiles.length; i++) { - var name_29 = sysFiles[i]; - if (ts.fileExtensionIs(name_29, ".d.ts")) { - var baseName = name_29.substr(0, name_29.length - ".d.ts".length); - if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) { - fileNames.push(name_29); - } + var filesSeen = {}; + var exclude = []; + if (json["exclude"] instanceof Array) { + exclude = json["exclude"]; + } + else { + // by default exclude node_modules, and any specificied output directory + exclude = ["node_modules"]; + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + exclude.push(outDir); } - else if (ts.fileExtensionIs(name_29, ".ts")) { - if (!ts.contains(sysFiles, name_29 + "x")) { - fileNames.push(name_29); + } + exclude = ts.map(exclude, ts.normalizeSlashes); + var supportedExtensions = ts.getSupportedExtensions(options); + ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); + // Get files of supported extensions in their order of resolution + for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; + var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); + for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { + var fileName = filesInDirWithExtension_1[_a]; + // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension, + // lets pick them when its turn comes up + if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { + continue; } - } - else { - fileNames.push(name_29); + // Skip over any minified JavaScript files (ending in ".min.js") + if (/\.min\.js$/.test(fileName)) { + continue; + } + // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) + // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation + if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { + var baseName = fileName.substr(0, fileName.length - extension.length); + if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { + continue; + } + } + filesSeen[fileName] = true; + fileNames.push(fileName); } } } @@ -38233,9 +41569,12 @@ var ts; } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function convertCompilerOptionsFromJson(jsonOptions, basePath) { + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var options = {}; var errors = []; + if (configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json") { + options.allowJs = true; + } if (!jsonOptions) { return { options: options, errors: errors }; } @@ -38258,7 +41597,37 @@ var ts; } } if (opt.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + switch (typeof value) { + case "string": + value = ts.normalizePath(ts.combinePaths(basePath, value)); + break; + case "object": + // "object" options with 'isFilePath' = true expected to be string arrays + var paths = []; + var invalidOptionType = false; + if (!ts.isArray(value)) { + invalidOptionType = true; + } + else { + for (var _i = 0, _a = value; _i < _a.length; _i++) { + var element = _a[_i]; + if (typeof element === "string") { + paths.push(ts.normalizePath(ts.combinePaths(basePath, element))); + } + else { + invalidOptionType = true; + break; + } + } + } + if (invalidOptionType) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_should_have_array_of_strings_as_a_value, opt.name)); + } + else { + value = paths; + } + break; + } if (value === "") { value = "."; } @@ -38349,7 +41718,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 174 /* ArrowFunction */; + return ts.isFunctionBlock(node) && node.parent.kind !== 178 /* ArrowFunction */; } var depth = 0; var maxDepth = 20; @@ -38361,30 +41730,30 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 192 /* Block */: + case 196 /* Block */: if (!ts.isFunctionBlock(n)) { - var parent_7 = n.parent; + var parent_9 = n.parent; var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* 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_7.kind === 197 /* DoStatement */ || - parent_7.kind === 200 /* ForInStatement */ || - parent_7.kind === 201 /* ForOfStatement */ || - parent_7.kind === 199 /* ForStatement */ || - parent_7.kind === 196 /* IfStatement */ || - parent_7.kind === 198 /* WhileStatement */ || - parent_7.kind === 205 /* WithStatement */ || - parent_7.kind === 244 /* CatchClause */) { - addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); + if (parent_9.kind === 201 /* DoStatement */ || + parent_9.kind === 204 /* ForInStatement */ || + parent_9.kind === 205 /* ForOfStatement */ || + parent_9.kind === 203 /* ForStatement */ || + parent_9.kind === 200 /* IfStatement */ || + parent_9.kind === 202 /* WhileStatement */ || + parent_9.kind === 209 /* WithStatement */ || + parent_9.kind === 248 /* CatchClause */) { + addOutliningSpan(parent_9, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_7.kind === 209 /* TryStatement */) { + if (parent_9.kind === 213 /* TryStatement */) { // Could be the try-block, or the finally-block. - var tryStatement = parent_7; + var tryStatement = parent_9; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_9, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -38407,23 +41776,23 @@ var ts; break; } // Fallthrough. - case 219 /* ModuleBlock */: { + case 223 /* ModuleBlock */: { var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 165 /* ObjectLiteralExpression */: - case 220 /* CaseBlock */: { + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 169 /* ObjectLiteralExpression */: + case 224 /* CaseBlock */: { var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); @@ -38453,17 +41822,17 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_30 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_30); + for (var name_31 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_31); 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_30); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_31); if (!matches) { continue; } - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. if (patternMatcher.patternContainsDots) { @@ -38471,14 +41840,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_30); + matches = patternMatcher.getMatches(containers, name_31); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_30, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_31, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -38516,8 +41885,8 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 136 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ true); + else if (declaration.name.kind === 138 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); } else { // Don't know how to add this. @@ -38537,12 +41906,12 @@ var ts; } return true; } - if (expression.kind === 166 /* PropertyAccessExpression */) { + if (expression.kind === 170 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); } - return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion:*/ true); + return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); } return false; } @@ -38550,8 +41919,8 @@ 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 === 136 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ false)) { + if (declaration.name.kind === 138 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -38612,7 +41981,7 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile) { + function getNavigationBarItems(sourceFile, compilerOptions) { // If the source file has any child items, then it included in the tree // and takes lexical ownership of all other top-level items. var hasGlobalNode = false; @@ -38624,17 +41993,17 @@ var ts; var current = node.parent; while (current) { switch (current.kind) { - case 218 /* ModuleDeclaration */: + case 222 /* 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 === 218 /* ModuleDeclaration */); + } while (current.kind === 222 /* ModuleDeclaration */); // fall through - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 219 /* InterfaceDeclaration */: + case 217 /* FunctionDeclaration */: indent++; } current = current.parent; @@ -38645,21 +42014,21 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: ts.forEach(node.declarationList.declarations, visit); break; - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: + case 165 /* ObjectBindingPattern */: + case 166 /* ArrayBindingPattern */: ts.forEach(node.elements, visit); break; - case 228 /* ExportDeclaration */: + case 232 /* 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 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -38671,7 +42040,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 228 /* NamespaceImport */) { childNodes.push(importClause.namedBindings); } else { @@ -38680,21 +42049,21 @@ var ts; } } break; - case 163 /* BindingElement */: - case 211 /* VariableDeclaration */: + case 167 /* BindingElement */: + case 215 /* VariableDeclaration */: if (ts.isBindingPattern(node.name)) { visit(node.name); break; } // Fall through - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 213 /* FunctionDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 219 /* InterfaceDeclaration */: + case 222 /* ModuleDeclaration */: + case 217 /* FunctionDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 230 /* ImportSpecifier */: + case 234 /* ExportSpecifier */: childNodes.push(node); break; } @@ -38742,17 +42111,17 @@ var ts; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { var node = nodes_4[_i]; switch (node.kind) { - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 219 /* InterfaceDeclaration */: topLevelNodes.push(node); break; - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: var moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); break; - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: var functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); @@ -38763,12 +42132,12 @@ var ts; } } function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 213 /* FunctionDeclaration */) { + if (functionDeclaration.kind === 217 /* FunctionDeclaration */) { // A function declaration is 'top level' if it contains any function declarations // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 192 /* Block */) { + if (functionDeclaration.body && functionDeclaration.body.kind === 196 /* Block */) { // Proper function declarations can only have identifier names - if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 213 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 217 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { return true; } // Or if it is not parented by another function. i.e all functions @@ -38828,44 +42197,44 @@ var ts; } function createChildItem(node) { switch (node.kind) { - case 138 /* Parameter */: + case 140 /* Parameter */: if (ts.isBindingPattern(node.name)) { break; } - if ((node.flags & 1022 /* Modifier */) === 0) { + if ((node.flags & 959 /* Modifier */) === 0) { return undefined; } return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 145 /* GetAccessor */: + case 147 /* GetAccessor */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 146 /* SetAccessor */: + case 148 /* SetAccessor */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 149 /* IndexSignature */: + case 151 /* IndexSignature */: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 247 /* EnumMember */: + case 251 /* EnumMember */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147 /* CallSignature */: + case 149 /* CallSignature */: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 148 /* ConstructSignature */: + case 150 /* ConstructSignature */: return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: - var variableDeclarationNode; - var name_31; - if (node.kind === 163 /* BindingElement */) { - name_31 = node.name; + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: + var variableDeclarationNode = void 0; + var name_32; + if (node.kind === 167 /* BindingElement */) { + name_32 = node.name; variableDeclarationNode = node; // binding elements are added only for variable declarations // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 211 /* VariableDeclaration */) { + while (variableDeclarationNode && variableDeclarationNode.kind !== 215 /* VariableDeclaration */) { variableDeclarationNode = variableDeclarationNode.parent; } ts.Debug.assert(variableDeclarationNode !== undefined); @@ -38873,24 +42242,24 @@ var ts; else { ts.Debug.assert(!ts.isBindingPattern(node.name)); variableDeclarationNode = node; - name_31 = node.name; + name_32 = node.name; } if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.constElement); + return createItem(node, getTextOfNode(name_32), ts.ScriptElementKind.constElement); } else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.letElement); + return createItem(node, getTextOfNode(name_32), ts.ScriptElementKind.letElement); } else { - return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.variableElement); + return createItem(node, getTextOfNode(name_32), ts.ScriptElementKind.variableElement); } - case 144 /* Constructor */: + case 146 /* Constructor */: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 230 /* ExportSpecifier */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: + case 234 /* ExportSpecifier */: + case 230 /* ImportSpecifier */: + case 225 /* ImportEqualsDeclaration */: + case 227 /* ImportClause */: + case 228 /* NamespaceImport */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); } return undefined; @@ -38920,29 +42289,29 @@ var ts; } function createTopLevelItem(node) { switch (node.kind) { - case 248 /* SourceFile */: + case 252 /* SourceFile */: return createSourceFileItem(node); - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: return createClassItem(node); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: return createEnumItem(node); - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return createIterfaceItem(node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return createModuleItem(node); - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: return createFunctionItem(node); } return undefined; function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. - if (moduleDeclaration.name.kind === 9 /* StringLiteral */) { + if (ts.isAmbientModule(moduleDeclaration)) { return getTextOfNode(moduleDeclaration.name); } // 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 === 218 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 222 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -38954,7 +42323,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 === 192 /* Block */) { + if (node.body && node.body.kind === 196 /* 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)); } @@ -38975,7 +42344,7 @@ var ts; var childItems; if (node.members) { var constructor = ts.forEach(node.members, function (member) { - return member.kind === 144 /* Constructor */ && member; + return member.kind === 146 /* 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 @@ -38999,7 +42368,7 @@ var ts; } } function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 136 /* ComputedPropertyName */; }); + return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 138 /* ComputedPropertyName */; }); } /** * Like removeComputedProperties, but retains the properties with well known symbol names @@ -39008,13 +42377,13 @@ var ts; return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); } function getInnermostModule(node) { - while (node.body.kind === 218 /* ModuleDeclaration */) { + while (node.body.kind === 222 /* ModuleDeclaration */) { node = node.body; } return node; } function getNodeSpan(node) { - return node.kind === 248 /* SourceFile */ + return node.kind === 252 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } @@ -39046,12 +42415,11 @@ var ts; } function createPatternMatcher(pattern) { // We'll often see the same candidate string many times when searching (For example, when - // we see the name of a module that is used everywhere, or the name of an overload). As - // such, we cache the information we compute about the candidate for the life of this + // we see the name of a module that is used everywhere, or the name of an overload). As + // such, we cache the information we compute about the candidate for the life of this // pattern matcher so we don't have to compute it multiple times. var stringToWordSpans = {}; pattern = pattern.trim(); - var fullPatternSegment = createSegment(pattern); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); return { @@ -39091,7 +42459,7 @@ var ts; // So far so good. Now break up the container for the candidate and check if all // the dotted parts match up correctly. var totalMatch = candidateMatch; - for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i--, j--) { + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { var segment = dotSeparatedSegments[i]; var containerName = candidateContainers[j]; var containerMatch = matchSegment(containerName, segment); @@ -39130,7 +42498,7 @@ var ts; if (index > 0) { // c) If the part is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring - // match. + // match. // // Note: We only have a substring match if the lowercase part is prefix match of some // word part. That way we don't match something like 'Class' when the user types 'a'. @@ -39170,8 +42538,8 @@ var ts; if (isLowercase) { // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? // We could check every character boundary start of the candidate for the pattern. However, that's - // an m * n operation in the wost case. Instead, find the first instance of the pattern - // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to // filter the list based on a substring that starts on a capital letter and also with a lowercase one. // (Pattern: fogbar, Candidate: quuxfogbarFogBar). if (chunk.text.length < candidate.length) { @@ -39223,7 +42591,7 @@ var ts; // // c) If the word is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring - // match. + // match. // // Note: We only have a substring match if the lowercase part is prefix match of // some word part. That way we don't match something like 'Class' when the user @@ -39237,7 +42605,7 @@ var ts; // e) If the word was not entirely lowercase, then attempt a camel cased match as // well. // - // f) The word is all lower case. Is it a case insensitive substring of the candidate starting + // f) The word is all lower case. Is it a case insensitive substring of the candidate starting // on a part boundary of the candidate? // // Only if all words have some sort of match is the pattern considered matched. @@ -39287,7 +42655,7 @@ var ts; // Note: we may have more pattern parts than candidate parts. This is because multiple // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U - // and I will both match in UI. + // and I will both match in UI. var currentCandidate = 0; var currentChunkSpan = 0; var firstMatch = undefined; @@ -39316,13 +42684,13 @@ var ts; // Consider the case of matching SiUI against SimpleUIElement. The candidate parts // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to - // still keep matching pattern parts against that candidate part. + // still keep matching pattern parts against that candidate part. for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; if (gotOneMatchThisCandidate) { // We've already gotten one pattern part match in this candidate. We will // only continue trying to consumer pattern parts if the last part and this - // part are both upper case. + // part are both upper case. if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { break; @@ -39352,42 +42720,6 @@ var ts; } } ts.createPatternMatcher = createPatternMatcher; - // Helper function to compare two matches to determine which is better. Matches are first - // ordered by kind (so all prefix matches always beat all substring matches). Then, if the - // match is a camel case match, the relative weights of the match are used to determine - // which is better (with a greater weight being better). Then if the match is of the same - // type, then a case sensitive match is considered better than an insensitive one. - function patternMatchCompareTo(match1, match2) { - return compareType(match1, match2) || - compareCamelCase(match1, match2) || - compareCase(match1, match2) || - comparePunctuation(match1, match2); - } - function comparePunctuation(result1, result2) { - // Consider a match to be better if it was successful without stripping punctuation - // versus a match that had to strip punctuation to succeed. - if (result1.punctuationStripped !== result2.punctuationStripped) { - return result1.punctuationStripped ? 1 : -1; - } - return 0; - } - function compareCase(result1, result2) { - if (result1.isCaseSensitive !== result2.isCaseSensitive) { - return result1.isCaseSensitive ? -1 : 1; - } - return 0; - } - function compareType(result1, result2) { - return result1.kind - result2.kind; - } - function compareCamelCase(result1, result2) { - if (result1.kind === PatternMatchKind.camelCase && result2.kind === PatternMatchKind.camelCase) { - // Swap the values here. If result1 has a higher weight, then we want it to come - // first. - return result2.camelCaseWeight - result1.camelCaseWeight; - } - return 0; - } function createSegment(text) { return { totalTextChunk: createTextChunk(text), @@ -39406,7 +42738,7 @@ var ts; if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { return false; } - // TODO: find a way to determine this for any unicode characters in a + // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. var str = String.fromCharCode(ch); return str === str.toUpperCase(); @@ -39419,19 +42751,11 @@ var ts; if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { return false; } - // TODO: find a way to determine this for any unicode characters in a + // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function containsUpperCaseLetter(string) { - for (var i = 0, n = string.length; i < n; i++) { - if (isUpperCaseLetter(string.charCodeAt(i))) { - return true; - } - } - return false; - } function startsWith(string, search) { for (var i = 0, n = search.length; i < n; i++) { if (string.charCodeAt(i) !== search.charCodeAt(i)) { @@ -39468,7 +42792,7 @@ var ts; if (ch < 127 /* maxAsciiCharacter */) { return ch; } - // TODO: find a way to compute this for any unicode characters in a + // TODO: find a way to compute this for any unicode characters in a // non-allocating manner. return String.fromCharCode(ch).toLowerCase().charCodeAt(0); } @@ -39486,9 +42810,10 @@ var ts; for (var i = 0; i < pattern.length; i++) { var ch = pattern.charCodeAt(i); if (isWordChar(ch)) { - if (wordLength++ === 0) { + if (wordLength === 0) { wordStart = i; } + wordLength++; } else { if (wordLength > 0) { @@ -39619,7 +42944,7 @@ var ts; var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); // See if the casing indicates we're starting a new word. Note: if we're breaking on // words, then just seeing an upper case character isn't enough. Instead, it has to - // be uppercase and the previous character can't be uppercase. + // be uppercase and the previous character can't be uppercase. // // For example, breaking "AddMetadata" on words would make: Add Metadata // @@ -39802,14 +43127,14 @@ var ts; if (!candidates.length) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - if (ts.isJavaScript(sourceFile.fileName)) { + if (ts.isSourceFileJavaScript(sourceFile)) { return createJavaScriptSignatureHelpItems(argumentInfo); } return undefined; } return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo); function createJavaScriptSignatureHelpItems(argumentInfo) { - if (argumentInfo.invocation.kind !== 168 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 172 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. @@ -39817,7 +43142,7 @@ var ts; var expression = callExpression.expression; var name = expression.kind === 69 /* Identifier */ ? expression - : expression.kind === 166 /* PropertyAccessExpression */ + : expression.kind === 170 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.text) { @@ -39829,8 +43154,8 @@ var ts; var nameToDeclarations = sourceFile_1.getNamedDeclarations(); var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { - for (var _b = 0, declarations_7 = declarations; _b < declarations_7.length; _b++) { - var declaration = declarations_7[_b]; + for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { + var declaration = declarations_8[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -39850,7 +43175,7 @@ var ts; * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node) { - if (node.parent.kind === 168 /* CallExpression */ || node.parent.kind === 169 /* NewExpression */) { + if (node.parent.kind === 172 /* CallExpression */ || node.parent.kind === 173 /* NewExpression */) { var callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session @@ -39903,25 +43228,25 @@ var ts; }; } } - else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 174 /* 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, /*argumentIndex*/ 0); } } - else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 174 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 187 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - else if (node.parent.kind === 190 /* TemplateSpan */ && node.parent.parent.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 194 /* TemplateSpan */ && node.parent.parent.parent.kind === 174 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 187 /* TemplateExpression */); // If we're just after a template tail, don't show signature help. if (node.kind === 14 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; @@ -40039,7 +43364,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 === 183 /* TemplateExpression */) { + if (template.kind === 187 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -40048,7 +43373,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { - for (var n = node; n.kind !== 248 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 252 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -40248,40 +43573,40 @@ var ts; return false; } switch (n.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 165 /* ObjectLiteralExpression */: - case 161 /* ObjectBindingPattern */: - case 155 /* TypeLiteral */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 220 /* CaseBlock */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 169 /* ObjectLiteralExpression */: + case 165 /* ObjectBindingPattern */: + case 157 /* TypeLiteral */: + case 196 /* Block */: + case 223 /* ModuleBlock */: + case 224 /* CaseBlock */: return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); - case 244 /* CatchClause */: + case 248 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 169 /* NewExpression */: + case 173 /* NewExpression */: if (!n.arguments) { return true; } // fall through - case 168 /* CallExpression */: - case 172 /* ParenthesizedExpression */: - case 160 /* ParenthesizedType */: + case 172 /* CallExpression */: + case 176 /* ParenthesizedExpression */: + case 162 /* ParenthesizedType */: return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 148 /* ConstructSignature */: - case 147 /* CallSignature */: - case 174 /* ArrowFunction */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 150 /* ConstructSignature */: + case 149 /* CallSignature */: + case 178 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -40291,64 +43616,64 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 196 /* IfStatement */: + case 200 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 195 /* ExpressionStatement */: + case 199 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 23 /* SemicolonToken */); - case 164 /* ArrayLiteralExpression */: - case 162 /* ArrayBindingPattern */: - case 167 /* ElementAccessExpression */: - case 136 /* ComputedPropertyName */: - case 157 /* TupleType */: + case 168 /* ArrayLiteralExpression */: + case 166 /* ArrayBindingPattern */: + case 171 /* ElementAccessExpression */: + case 138 /* ComputedPropertyName */: + case 159 /* TupleType */: return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); - case 149 /* IndexSignature */: + case 151 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 245 /* CaseClause */: + case 246 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicitly always consider them non-completed return false; - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 202 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 197 /* DoStatement */: + case 201 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 154 /* TypeQuery */: + case 156 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 176 /* TypeOfExpression */: - case 175 /* DeleteExpression */: - case 177 /* VoidExpression */: - case 184 /* YieldExpression */: - case 185 /* SpreadElementExpression */: + case 180 /* TypeOfExpression */: + case 179 /* DeleteExpression */: + case 181 /* VoidExpression */: + case 188 /* YieldExpression */: + case 189 /* SpreadElementExpression */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 170 /* TaggedTemplateExpression */: + case 174 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 183 /* TemplateExpression */: + case 187 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 190 /* TemplateSpan */: + case 194 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -40404,7 +43729,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 === 271 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 275 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -40510,7 +43835,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 236 /* JsxText */) { + if (isToken(n) || n.kind === 240 /* JsxText */) { return n; } var children = n.getChildren(); @@ -40518,7 +43843,7 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 236 /* JsxText */) { + if (isToken(n) || n.kind === 240 /* JsxText */) { return n; } var children = n.getChildren(); @@ -40532,10 +43857,10 @@ var ts; // if no - position is in the node itself so we should recurse in it. // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). // if this is the case - then we should assume that token in question is located in previous child. - if (position < child.end && (nodeHasTokens(child) || child.kind === 236 /* JsxText */)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 240 /* JsxText */)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 236 /* JsxText */ && start === child.end); // whitespace only JsxText + (child.kind === 240 /* JsxText */ && start === child.end); // whitespace only JsxText if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); @@ -40547,8 +43872,8 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 248 /* SourceFile */); - // Here we know that none of child token nodes embrace the position, + ts.Debug.assert(startNode !== undefined || n.kind === 252 /* 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. // Namely we are skipping the check: 'position < node.end' @@ -40569,7 +43894,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); - return token && token.kind === 9 /* StringLiteral */ && position > token.getStart(); + return token && (token.kind === 9 /* StringLiteral */ || token.kind === 164 /* StringLiteralType */) && position > token.getStart(); } ts.isInString = isInString; function isInComment(sourceFile, position) { @@ -40655,17 +43980,17 @@ var ts; function getNodeModifiers(node) { var flags = ts.getCombinedNodeFlags(node); var result = []; - if (flags & 16 /* Private */) + if (flags & 8 /* Private */) result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 32 /* Protected */) + if (flags & 16 /* Protected */) result.push(ts.ScriptElementKindModifier.protectedMemberModifier); - if (flags & 8 /* Public */) + if (flags & 4 /* Public */) result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 64 /* Static */) + if (flags & 32 /* Static */) result.push(ts.ScriptElementKindModifier.staticModifier); if (flags & 128 /* Abstract */) result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 2 /* Export */) + if (flags & 1 /* Export */) result.push(ts.ScriptElementKindModifier.exportedModifier); if (ts.isInAmbientContext(node)) result.push(ts.ScriptElementKindModifier.ambientModifier); @@ -40673,17 +43998,17 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 151 /* TypeReference */ || node.kind === 168 /* CallExpression */) { + if (node.kind === 153 /* TypeReference */ || node.kind === 172 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 214 /* ClassDeclaration */ || node.kind === 215 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 218 /* ClassDeclaration */ || node.kind === 219 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 134 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 136 /* LastToken */; } ts.isToken = isToken; function isWord(kind) { @@ -40699,6 +44024,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ + || kind === 164 /* StringLiteralType */ || kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; @@ -40741,13 +44067,40 @@ var ts; return true; } ts.compareDataObjects = compareDataObjects; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 168 /* ArrayLiteralExpression */ || + node.kind === 169 /* ObjectLiteralExpression */) { + // [a,b,c] from: + // [a, b, c] = someExpression; + if (node.parent.kind === 185 /* BinaryExpression */ && + node.parent.left === node && + node.parent.operatorToken.kind === 56 /* EqualsToken */) { + return true; + } + // [a, b, c] from: + // for([a, b, c] of expression) + if (node.parent.kind === 205 /* ForOfStatement */ && + node.parent.initializer === node) { + return true; + } + // [a, b, c] of + // [x, [a, b, c] ] = someExpression + // or + // {x, a: {a, b, c} } = someExpression + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 249 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 138 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 140 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -40935,7 +44288,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 226 /* ImportSpecifier */ || location.parent.kind === 230 /* ExportSpecifier */) && + (location.parent.kind === 230 /* ImportSpecifier */ || location.parent.kind === 234 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -40992,6 +44345,7 @@ var ts; advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, close: function () { ts.Debug.assert(scanner !== undefined); @@ -41057,10 +44411,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 238 /* JsxAttribute */: - case 235 /* JsxOpeningElement */: - case 237 /* JsxClosingElement */: - case 234 /* JsxSelfClosingElement */: + case 242 /* JsxAttribute */: + case 239 /* JsxOpeningElement */: + case 241 /* JsxClosingElement */: + case 238 /* JsxSelfClosingElement */: return node.kind === 69 /* Identifier */; } } @@ -41267,7 +44621,7 @@ var ts; return false; }; return FormattingContext; - })(); + }()); formatting.FormattingContext = FormattingContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41306,7 +44660,7 @@ var ts; "flag=" + this.Flag + "]"; }; return Rule; - })(); + }()); formatting.Rule = Rule; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41353,7 +44707,7 @@ var ts; return new RuleDescriptor(left, right); }; return RuleDescriptor; - })(); + }()); formatting.RuleDescriptor = RuleDescriptor; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41395,7 +44749,7 @@ var ts; return result; }; return RuleOperation; - })(); + }()); formatting.RuleOperation = RuleOperation; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41430,7 +44784,7 @@ var ts; }; RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; - })(); + }()); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41449,25 +44803,25 @@ var ts; this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */)); this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */)); // Space after keyword but not before ; or : or ? - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); + this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); + this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Space after }. - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); + this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 80 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 104 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 20 /* CloseBracketToken */, 24 /* CommaToken */, 23 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 80 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 104 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 20 /* CloseBracketToken */, 24 /* CommaToken */, 23 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // No space for dot - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // No space before and after indexer - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); // Place a space before open brace in a function declaration this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); @@ -41480,7 +44834,7 @@ var ts; // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); + this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); // Insert new line after { and before } in multi-line contexts. this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); // For functions and control block place } on a new line [multi-line rule] @@ -41488,149 +44842,146 @@ var ts; // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. - this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // More unary operator special-casing. // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: // 1 - -2 --X--> 1--2 // a + ++b --X--> a+++b - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41 /* PlusPlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42 /* MinusMinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102 /* VarKeyword */, 98 /* ThrowKeyword */, 92 /* NewKeyword */, 78 /* DeleteKeyword */, 94 /* ReturnKeyword */, 101 /* TypeOfKeyword */, 119 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108 /* LetKeyword */, 74 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); + this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41 /* PlusPlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42 /* MinusMinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102 /* VarKeyword */, 98 /* ThrowKeyword */, 92 /* NewKeyword */, 78 /* DeleteKeyword */, 94 /* ReturnKeyword */, 101 /* TypeOfKeyword */, 119 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108 /* LetKeyword */, 74 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); + this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(87 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); + this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); + this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotForContext), 2 /* Space */)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotForContext), 2 /* Space */)); // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // get x() {} // set x(val) {} - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123 /* GetKeyword */, 129 /* SetKeyword */]), 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123 /* GetKeyword */, 130 /* SetKeyword */]), 69 /* 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 */)); + this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); // TypeScript-specific higher priority rules // 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(121 /* ConstructorKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(121 /* ConstructorKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 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([125 /* ModuleKeyword */, 127 /* RequireKeyword */]), 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125 /* ModuleKeyword */, 128 /* RequireKeyword */]), 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 73 /* ClassKeyword */, 122 /* DeclareKeyword */, 77 /* DefaultKeyword */, 81 /* EnumKeyword */, 82 /* ExportKeyword */, 83 /* ExtendsKeyword */, 123 /* GetKeyword */, 106 /* ImplementsKeyword */, 89 /* ImportKeyword */, 107 /* InterfaceKeyword */, 125 /* ModuleKeyword */, 126 /* NamespaceKeyword */, 110 /* PrivateKeyword */, 112 /* PublicKeyword */, 111 /* ProtectedKeyword */, 129 /* SetKeyword */, 113 /* StaticKeyword */, 132 /* TypeKeyword */]), 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([83 /* ExtendsKeyword */, 106 /* ImplementsKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 73 /* ClassKeyword */, 122 /* DeclareKeyword */, 77 /* DefaultKeyword */, 81 /* EnumKeyword */, 82 /* ExportKeyword */, 83 /* ExtendsKeyword */, 123 /* GetKeyword */, 106 /* ImplementsKeyword */, 89 /* ImportKeyword */, 107 /* InterfaceKeyword */, 125 /* ModuleKeyword */, 126 /* NamespaceKeyword */, 110 /* PrivateKeyword */, 112 /* PublicKeyword */, 111 /* ProtectedKeyword */, 130 /* SetKeyword */, 113 /* StaticKeyword */, 133 /* TypeKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([83 /* ExtendsKeyword */, 106 /* ImplementsKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 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(9 /* StringLiteral */, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); // Lambda expressions - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Optional parameters and let args - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22 /* DotDotDotToken */, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22 /* DotDotDotToken */, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); // generics and type assertions - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseParenToken */, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([17 /* OpenParenToken */, 19 /* OpenBracketToken */, 27 /* GreaterThanToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); + this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseParenToken */, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([17 /* OpenParenToken */, 19 /* OpenBracketToken */, 27 /* GreaterThanToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); // Remove spaces in empty interface literals. e.g.: x: {} - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); + this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); // decorators - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* 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([115 /* AbstractKeyword */, 69 /* Identifier */, 82 /* ExportKeyword */, 77 /* DefaultKeyword */, 73 /* ClassKeyword */, 113 /* StaticKeyword */, 112 /* PublicKeyword */, 110 /* PrivateKeyword */, 111 /* ProtectedKeyword */, 123 /* GetKeyword */, 129 /* SetKeyword */, 19 /* OpenBracketToken */, 37 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); + this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 69 /* Identifier */, 82 /* ExportKeyword */, 77 /* DefaultKeyword */, 73 /* ClassKeyword */, 113 /* StaticKeyword */, 112 /* PublicKeyword */, 110 /* PrivateKeyword */, 111 /* ProtectedKeyword */, 123 /* GetKeyword */, 130 /* SetKeyword */, 19 /* OpenBracketToken */, 37 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(37 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114 /* YieldKeyword */, 37 /* 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([114 /* YieldKeyword */, 37 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114 /* YieldKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114 /* YieldKeyword */, 37 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); // Async-await - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // template string - this.SpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. - this.HighPriorityCommonRules = - [ - this.IgnoreBeforeComment, this.IgnoreAfterLineComment, - this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, - this.NoSpaceAfterQuestionMark, - this.NoSpaceBeforeDot, this.NoSpaceAfterDot, - this.NoSpaceAfterUnaryPrefixOperator, - this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, - this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, - this.SpaceAfterPostincrementWhenFollowedByAdd, - this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, - this.SpaceAfterPostdecrementWhenFollowedBySubtract, - this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, - 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, - this.NoSpaceBeforeOpenParenInFuncCall, - this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, - this.SpaceAfterVoidOperator, - this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, - this.SpaceBetweenTagAndTemplateString, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, - // TypeScript-specific rules - this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, - this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, - this.SpaceAfterModuleName, - this.SpaceAfterArrow, - this.NoSpaceAfterEllipsis, - this.NoSpaceAfterOptionalParameters, - this.NoSpaceBetweenEmptyInterfaceBraceBrackets, - this.NoSpaceBeforeOpenAngularBracket, - this.NoSpaceBetweenCloseParenAndAngularBracket, - this.NoSpaceAfterOpenAngularBracket, - this.NoSpaceBeforeCloseAngularBracket, - this.NoSpaceAfterCloseAngularBracket, - this.NoSpaceAfterTypeAssertion, - this.SpaceBeforeAt, - this.NoSpaceAfterAt, - this.SpaceAfterDecorator, - ]; + this.HighPriorityCommonRules = [ + this.IgnoreBeforeComment, this.IgnoreAfterLineComment, + this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, + this.NoSpaceAfterQuestionMark, + this.NoSpaceBeforeDot, this.NoSpaceAfterDot, + this.NoSpaceAfterUnaryPrefixOperator, + this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, + this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, + this.SpaceAfterPostincrementWhenFollowedByAdd, + this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, + this.SpaceAfterPostdecrementWhenFollowedBySubtract, + this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, + 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, + this.NoSpaceBeforeOpenParenInFuncCall, + this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, + this.SpaceAfterVoidOperator, + this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, + this.NoSpaceBetweenTagAndTemplateString, + // TypeScript-specific rules + this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, + this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, + this.SpaceAfterModuleName, + this.SpaceBeforeArrow, this.SpaceAfterArrow, + this.NoSpaceAfterEllipsis, + this.NoSpaceAfterOptionalParameters, + this.NoSpaceBetweenEmptyInterfaceBraceBrackets, + this.NoSpaceBeforeOpenAngularBracket, + this.NoSpaceBetweenCloseParenAndAngularBracket, + this.NoSpaceAfterOpenAngularBracket, + this.NoSpaceBeforeCloseAngularBracket, + this.NoSpaceAfterCloseAngularBracket, + this.NoSpaceAfterTypeAssertion, + this.SpaceBeforeAt, + this.NoSpaceAfterAt, + this.SpaceAfterDecorator, + ]; // These rules are lower in priority than user-configurable rules. - this.LowPriorityCommonRules = - [ - this.NoSpaceBeforeSemicolon, - this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, - this.NoSpaceBeforeComma, - this.NoSpaceBeforeOpenBracket, - this.NoSpaceAfterCloseBracket, - this.SpaceAfterSemicolon, - this.NoSpaceBeforeOpenParenInFuncDecl, - this.SpaceBetweenStatements, this.SpaceAfterTryFinally - ]; + this.LowPriorityCommonRules = [ + this.NoSpaceBeforeSemicolon, + this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, + this.NoSpaceBeforeComma, + this.NoSpaceBeforeOpenBracket, + this.NoSpaceAfterCloseBracket, + this.SpaceAfterSemicolon, + this.NoSpaceBeforeOpenParenInFuncDecl, + this.SpaceBetweenStatements, this.SpaceAfterTryFinally + ]; /// /// Rules controlled by user options /// // Insert space after comma delimiter - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Insert space before and after binary operators - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); + this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); + this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); // Insert space after keywords in control flow statements this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2 /* Space */)); this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8 /* Delete */)); @@ -41642,29 +44993,34 @@ var ts; // Open Brace braces after control block this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Insert space after semicolon in for statement - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); // Insert space after opening and before closing nonempty parenthesis - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenParenToken */, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenParenToken */, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Insert space after opening and before closing nonempty brackets - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenBracketToken */, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* 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, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenBracketToken */, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + // Insert space after opening and before closing template string braces + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Insert space after function keyword for anonymous functions this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_32 in o) { - if (o[name_32] === rule) { - return name_32; + for (var name_33 in o) { + if (o[name_33] === rule) { + return name_33; } } throw new Error("Unknown rule"); @@ -41673,40 +45029,40 @@ var ts; /// Contexts /// Rules.IsForContext = function (context) { - return context.contextNode.kind === 199 /* ForStatement */; + return context.contextNode.kind === 203 /* ForStatement */; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 189 /* AsExpression */: - case 150 /* TypePredicate */: - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 185 /* BinaryExpression */: + case 186 /* ConditionalExpression */: + case 193 /* AsExpression */: + case 152 /* TypePredicate */: + case 160 /* UnionType */: + case 161 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 163 /* BindingElement */: + case 167 /* BindingElement */: // equals in type X = ... - case 216 /* TypeAliasDeclaration */: + case 220 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 211 /* VariableDeclaration */: + case 215 /* VariableDeclaration */: // equal in p = 0; - case 138 /* Parameter */: - case 247 /* EnumMember */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 140 /* Parameter */: + case 251 /* EnumMember */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return context.currentTokenSpan.kind === 56 /* EqualsToken */ || context.nextTokenSpan.kind === 56 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 200 /* ForInStatement */: + case 204 /* ForInStatement */: return context.currentTokenSpan.kind === 90 /* InKeyword */ || context.nextTokenSpan.kind === 90 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 201 /* ForOfStatement */: - return context.currentTokenSpan.kind === 134 /* OfKeyword */ || context.nextTokenSpan.kind === 134 /* OfKeyword */; + case 205 /* ForOfStatement */: + return context.currentTokenSpan.kind === 136 /* OfKeyword */ || context.nextTokenSpan.kind === 136 /* OfKeyword */; } return false; }; @@ -41714,7 +45070,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 182 /* ConditionalExpression */; + return context.contextNode.kind === 186 /* ConditionalExpression */; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. @@ -41758,93 +45114,93 @@ var ts; return true; } switch (node.kind) { - case 192 /* Block */: - case 220 /* CaseBlock */: - case 165 /* ObjectLiteralExpression */: - case 219 /* ModuleBlock */: + case 196 /* Block */: + case 224 /* CaseBlock */: + case 169 /* ObjectLiteralExpression */: + case 223 /* ModuleBlock */: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: //case SyntaxKind.MemberFunctionDeclaration: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: ///case SyntaxKind.MethodSignature: - case 147 /* CallSignature */: - case 173 /* FunctionExpression */: - case 144 /* Constructor */: - case 174 /* ArrowFunction */: + case 149 /* CallSignature */: + case 177 /* FunctionExpression */: + case 146 /* Constructor */: + case 178 /* ArrowFunction */: //case SyntaxKind.ConstructorDeclaration: //case SyntaxKind.SimpleArrowFunctionExpression: //case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 213 /* FunctionDeclaration */ || context.contextNode.kind === 173 /* FunctionExpression */; + return context.contextNode.kind === 217 /* FunctionDeclaration */ || context.contextNode.kind === 177 /* FunctionExpression */; }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 155 /* TypeLiteral */: - case 218 /* ModuleDeclaration */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 157 /* TypeLiteral */: + case 222 /* ModuleDeclaration */: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 214 /* ClassDeclaration */: - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: - case 192 /* Block */: - case 244 /* CatchClause */: - case 219 /* ModuleBlock */: - case 206 /* SwitchStatement */: + case 218 /* ClassDeclaration */: + case 222 /* ModuleDeclaration */: + case 221 /* EnumDeclaration */: + case 196 /* Block */: + case 248 /* CatchClause */: + case 223 /* ModuleBlock */: + case 210 /* SwitchStatement */: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 196 /* IfStatement */: - case 206 /* SwitchStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: - case 209 /* TryStatement */: - case 197 /* DoStatement */: - case 205 /* WithStatement */: + case 200 /* IfStatement */: + case 210 /* SwitchStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 202 /* WhileStatement */: + case 213 /* TryStatement */: + case 201 /* DoStatement */: + case 209 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 244 /* CatchClause */: + case 248 /* CatchClause */: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 165 /* ObjectLiteralExpression */; + return context.contextNode.kind === 169 /* ObjectLiteralExpression */; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 168 /* CallExpression */; + return context.contextNode.kind === 172 /* CallExpression */; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 169 /* NewExpression */; + return context.contextNode.kind === 173 /* NewExpression */; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); @@ -41852,11 +45208,14 @@ var ts; Rules.IsPreviousTokenNotComma = function (context) { return context.currentTokenSpan.kind !== 24 /* CommaToken */; }; - Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 174 /* ArrowFunction */; + Rules.IsNextTokenNotCloseBracket = function (context) { + return context.nextTokenSpan.kind !== 20 /* CloseBracketToken */; }; - Rules.IsSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine(); + Rules.IsArrowFunctionContext = function (context) { + return context.contextNode.kind === 178 /* ArrowFunction */; + }; + Rules.IsNonJsxSameLineTokenContext = function (context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 240 /* JsxText */; }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); @@ -41871,41 +45230,41 @@ var ts; while (ts.isExpression(node)) { node = node.parent; } - return node.kind === 139 /* Decorator */; + return node.kind === 141 /* Decorator */; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 212 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 216 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 218 /* ModuleDeclaration */; + return context.contextNode.kind === 222 /* ModuleDeclaration */; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 155 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 157 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { if (token.kind !== 25 /* LessThanToken */ && token.kind !== 27 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 151 /* TypeReference */: - case 171 /* TypeAssertionExpression */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 188 /* ExpressionWithTypeArguments */: + case 153 /* TypeReference */: + case 175 /* TypeAssertionExpression */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 219 /* InterfaceDeclaration */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 192 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -41916,16 +45275,16 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 171 /* TypeAssertionExpression */; + return context.contextNode.kind === 175 /* TypeAssertionExpression */; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 177 /* VoidExpression */; + return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 181 /* VoidExpression */; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 184 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 188 /* YieldExpression */ && context.contextNode.expression !== undefined; }; return Rules; - })(); + }()); formatting.Rules = Rules; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41946,7 +45305,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 134 /* LastToken */ + 1; + this.mapRowLength = 136 /* 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); @@ -41993,7 +45352,7 @@ var ts; return null; }; return RulesMap; - })(); + }()); formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; @@ -42045,7 +45404,7 @@ var ts; this.rulesInsertionIndexBitmap = temp; }; return RulesBucketConstructionState; - })(); + }()); formatting.RulesBucketConstructionState = RulesBucketConstructionState; var RulesBucket = (function () { function RulesBucket() { @@ -42080,7 +45439,7 @@ var ts; state.IncreaseInsertionIndex(position); }; return RulesBucket; - })(); + }()); formatting.RulesBucket = RulesBucket; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42096,7 +45455,7 @@ var ts; function TokenRangeAccess(from, to, except) { this.tokens = []; for (var token = from; token <= to; token++) { - if (except.indexOf(token) < 0) { + if (ts.indexOf(except, token) < 0) { this.tokens.push(token); } } @@ -42108,7 +45467,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenRangeAccess; - })(); + }()); Shared.TokenRangeAccess = TokenRangeAccess; var TokenValuesAccess = (function () { function TokenValuesAccess(tks) { @@ -42121,7 +45480,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenValuesAccess; - })(); + }()); Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { @@ -42134,14 +45493,14 @@ var ts; return tokenValue === this.token; }; return TokenSingleValueAccess; - })(); + }()); Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { var result = []; - for (var token = 0 /* FirstToken */; token <= 134 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 136 /* LastToken */; token++) { result.push(token); } return result; @@ -42153,7 +45512,7 @@ var ts; return "[allTokens]"; }; return TokenAllAccess; - })(); + }()); Shared.TokenAllAccess = TokenAllAccess; var TokenRange = (function () { function TokenRange(tokenAccess) { @@ -42183,9 +45542,9 @@ var ts; }; TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 134 /* LastKeyword */); + TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 136 /* LastKeyword */); TokenRange.BinaryOperators = TokenRange.FromRange(25 /* FirstBinaryOperator */, 68 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 134 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 136 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41 /* PlusPlusToken */, 42 /* MinusMinusToken */, 50 /* TildeToken */, 49 /* ExclamationToken */]); TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 69 /* Identifier */, 17 /* OpenParenToken */, 19 /* OpenBracketToken */, 15 /* OpenBraceToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); @@ -42193,9 +45552,9 @@ var ts; TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 128 /* NumberKeyword */, 130 /* StringKeyword */, 120 /* BooleanKeyword */, 131 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); + TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 129 /* NumberKeyword */, 131 /* StringKeyword */, 120 /* BooleanKeyword */, 132 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); return TokenRange; - })(); + }()); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -42281,6 +45640,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); + } + else { + rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); + } if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } @@ -42306,7 +45673,7 @@ var ts; return rules; }; return RulesProvider; - })(); + }()); formatting.RulesProvider = RulesProvider; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42407,17 +45774,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 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 192 /* Block */ && ts.rangeContainsRange(body.statements, node); - case 248 /* SourceFile */: - case 192 /* Block */: - case 219 /* ModuleBlock */: + return body && body.kind === 196 /* Block */ && ts.rangeContainsRange(body.statements, node); + case 252 /* SourceFile */: + case 196 /* Block */: + case 223 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 244 /* CatchClause */: + case 248 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -42515,17 +45882,17 @@ var ts; */ function getOwnOrInheritedDelta(n, options, sourceFile) { var previousLine = -1 /* Unknown */; - var childKind = 0 /* Unknown */; + var child; while (n) { var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; if (previousLine !== -1 /* Unknown */ && line !== previousLine) { break; } - if (formatting.SmartIndenter.shouldIndentChildNode(n.kind, childKind)) { + if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { return options.IndentSize; } previousLine = line; - childKind = n.kind; + child = n; n = n.parent; } return 0; @@ -42555,6 +45922,13 @@ var ts; var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined); + trimTrailingWhitespacesForRemainingRange(); + } + } formattingScanner.close(); return edits; // local functions @@ -42566,7 +45940,8 @@ var ts; * to inherited indentation from its predecessors. */ function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { - if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { if (inheritedIndentation !== -1 /* Unknown */) { return inheritedIndentation; } @@ -42583,32 +45958,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - if (indentation === -1 /* Unknown */) { - if (isSomeBlock(node.kind)) { - // blocks should be indented in - // - other blocks - // - source file - // - switch\default clauses - if (isSomeBlock(parent.kind) || - parent.kind === 248 /* SourceFile */ || - parent.kind === 241 /* CaseClause */ || - parent.kind === 242 /* DefaultClause */) { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - else { - indentation = parentDynamicIndentation.getIndentation(); - } - } - else { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); - } - else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - } - } - var delta = formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -42616,7 +45966,15 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + } + else if (indentation === -1 /* Unknown */) { + if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + indentation = parentDynamicIndentation.getIndentation(); + } + else { + indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + } } return { indentation: indentation, @@ -42628,25 +45986,25 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 214 /* ClassDeclaration */: return 73 /* ClassKeyword */; - case 215 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; - case 213 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; - case 217 /* EnumDeclaration */: return 217 /* EnumDeclaration */; - case 145 /* GetAccessor */: return 123 /* GetKeyword */; - case 146 /* SetAccessor */: return 129 /* SetKeyword */; - case 143 /* MethodDeclaration */: + case 218 /* ClassDeclaration */: return 73 /* ClassKeyword */; + case 219 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; + case 217 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; + case 221 /* EnumDeclaration */: return 221 /* EnumDeclaration */; + case 147 /* GetAccessor */: return 123 /* GetKeyword */; + case 148 /* SetAccessor */: return 130 /* SetKeyword */; + case 145 /* MethodDeclaration */: if (node.asteriskToken) { return 37 /* AsteriskToken */; } // fall-through - case 141 /* PropertyDeclaration */: - case 138 /* Parameter */: + case 143 /* PropertyDeclaration */: + case 140 /* Parameter */: return node.name.kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { return { - getIndentationForComment: function (kind, tokenIndentation) { + getIndentationForComment: function (kind, tokenIndentation, container) { switch (kind) { // preceding comment to the token that closes the indentation scope inherits the indentation from the scope // .. { @@ -42655,11 +46013,11 @@ var ts; case 16 /* CloseBraceToken */: case 20 /* CloseBracketToken */: case 18 /* CloseParenToken */: - return indentation + delta; + return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind) { + getIndentationForToken: function (line, kind, container) { if (nodeStartLine !== line && node.decorators) { if (kind === getFirstNonDecoratorTokenOfNode(node)) { // if this token is the first token following the list of decorators, we do not need to indent @@ -42680,20 +46038,20 @@ var ts; return indentation; default: // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + delta : indentation; + return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; } }, getIndentation: function () { return indentation; }, - getDelta: function () { return delta; }, + getDelta: function (child) { return getEffectiveDelta(delta, child); }, recomputeIndentation: function (lineAdded) { - if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { indentation += options.IndentSize; } else { indentation -= options.IndentSize; } - if (formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */)) { + if (formatting.SmartIndenter.shouldIndentChildNode(node)) { delta = options.IndentSize; } else { @@ -42702,6 +46060,10 @@ var ts; } } }; + function getEffectiveDelta(delta, child) { + // Delta value should be zero when the node explicitly prevents indentation of the child node + return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0; + } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { @@ -42773,10 +46135,10 @@ var ts; // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules var tokenInfo = formattingScanner.readTokenInfo(child); ts.Debug.assert(tokenInfo.token.end === child.end); - consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 139 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 141 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; @@ -42827,7 +46189,7 @@ var ts; } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -42862,10 +46224,10 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : -1 /* Unknown */; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); + var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); var indentNextTokenOrTrivia = true; for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { var triviaItem = _a[_i]; @@ -42954,9 +46316,7 @@ var ts; } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line - trimTrailingWhitespaces = - (rule.Operation.Action & (4 /* NewLine */ | 2 /* Space */)) && - rule.Flag !== 1 /* CanDeleteNewLines */; + trimTrailingWhitespaces = !(rule.Operation.Action & 8 /* Delete */) && rule.Flag !== 1 /* CanDeleteNewLines */; } else { trimTrailingWhitespaces = true; @@ -43039,16 +46399,36 @@ var ts; if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { continue; } - var pos = lineEndPosition; - while (pos >= lineStartPosition && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { - pos--; - } - if (pos !== lineEndPosition) { - ts.Debug.assert(pos === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))); - recordDelete(pos + 1, lineEndPosition - pos); + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); } } } + /** + * @param start The position of the first character in range + * @param end The position of the last character in range + */ + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + /** + * Trimming will be done for lines after the previous range + */ + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } function newTextChange(start, len, newText) { return { span: ts.createTextSpan(start, len), newText: newText }; } @@ -43102,20 +46482,20 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 196 /* Block */: + case 223 /* ModuleBlock */: return true; } return false; } function getOpenTokenForList(node, list) { switch (node.kind) { - case 144 /* Constructor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 174 /* ArrowFunction */: + case 146 /* Constructor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 178 /* ArrowFunction */: if (node.typeParameters === list) { return 25 /* LessThanToken */; } @@ -43123,8 +46503,8 @@ var ts; return 17 /* OpenParenToken */; } break; - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: if (node.typeArguments === list) { return 25 /* LessThanToken */; } @@ -43132,7 +46512,7 @@ var ts; return 17 /* OpenParenToken */; } break; - case 151 /* TypeReference */: + case 153 /* TypeReference */: if (node.typeArguments === list) { return 25 /* LessThanToken */; } @@ -43161,7 +46541,7 @@ var ts; if (!options.ConvertTabsToSpaces) { var tabs = Math.floor(indentation / options.TabSize); var spaces = indentation - tabs * options.TabSize; - var tabString; + var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; } @@ -43174,7 +46554,7 @@ var ts; return spaces ? tabString + repeat(" ", spaces) : tabString; } else { - var spacesString; + var spacesString = void 0; var quotient = Math.floor(indentation / options.IndentSize); var remainder = indentation % options.IndentSize; if (!internedSpacesIndentation) { @@ -43248,7 +46628,7 @@ var ts; var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } - if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 181 /* BinaryExpression */) { + if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 185 /* 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 */) { @@ -43262,7 +46642,7 @@ var ts; var currentStart; var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : 0 /* Unknown */)) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { currentStart = getStartLineAndCharacterForNode(current, sourceFile); if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) { indentationDelta = 0; @@ -43329,7 +46709,7 @@ var ts; } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line - if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { + if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { indentationDelta += options.IndentSize; } current = parent; @@ -43367,7 +46747,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 === 248 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 252 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -43400,7 +46780,7 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 196 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 200 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 80 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -43412,23 +46792,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 151 /* TypeReference */: + case 153 /* TypeReference */: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 165 /* ObjectLiteralExpression */: + case 169 /* ObjectLiteralExpression */: return node.parent.properties; - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return node.parent.elements; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: { + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -43439,8 +46819,8 @@ var ts; } break; } - case 169 /* NewExpression */: - case 168 /* CallExpression */: { + case 173 /* NewExpression */: + case 172 /* CallExpression */: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -43470,8 +46850,8 @@ var ts; if (node.kind === 18 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 168 /* CallExpression */ || - node.parent.kind === 169 /* NewExpression */) && + if (node.parent && (node.parent.kind === 172 /* CallExpression */ || + node.parent.kind === 173 /* NewExpression */) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -43489,10 +46869,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 170 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: node = node.expression; break; default: @@ -43556,80 +46936,85 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 195 /* ExpressionStatement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 164 /* ArrayLiteralExpression */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 165 /* ObjectLiteralExpression */: - case 155 /* TypeLiteral */: - case 157 /* TupleType */: - case 220 /* CaseBlock */: - case 242 /* DefaultClause */: - case 241 /* CaseClause */: - case 172 /* ParenthesizedExpression */: - case 166 /* PropertyAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 193 /* VariableStatement */: - case 211 /* VariableDeclaration */: - case 227 /* ExportAssignment */: - case 204 /* ReturnStatement */: - case 182 /* ConditionalExpression */: - case 162 /* ArrayBindingPattern */: - case 161 /* ObjectBindingPattern */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 142 /* MethodSignature */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 138 /* Parameter */: - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 160 /* ParenthesizedType */: - case 170 /* TaggedTemplateExpression */: - case 178 /* AwaitExpression */: + case 199 /* ExpressionStatement */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 168 /* ArrayLiteralExpression */: + case 196 /* Block */: + case 223 /* ModuleBlock */: + case 169 /* ObjectLiteralExpression */: + case 157 /* TypeLiteral */: + case 159 /* TupleType */: + case 224 /* CaseBlock */: + case 246 /* DefaultClause */: + case 245 /* CaseClause */: + case 176 /* ParenthesizedExpression */: + case 170 /* PropertyAccessExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 197 /* VariableStatement */: + case 215 /* VariableDeclaration */: + case 231 /* ExportAssignment */: + case 208 /* ReturnStatement */: + case 186 /* ConditionalExpression */: + case 166 /* ArrayBindingPattern */: + case 165 /* ObjectBindingPattern */: + case 239 /* JsxOpeningElement */: + case 238 /* JsxSelfClosingElement */: + case 244 /* JsxExpression */: + case 144 /* MethodSignature */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 140 /* Parameter */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 162 /* ParenthesizedType */: + case 174 /* TaggedTemplateExpression */: + case 182 /* AwaitExpression */: + case 229 /* NamedImports */: return true; } return false; } + /* @internal */ + function nodeWillIndentChild(parent, child, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { + case 201 /* DoStatement */: + case 202 /* WhileStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 203 /* ForStatement */: + case 200 /* IfStatement */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 145 /* MethodDeclaration */: + case 178 /* ArrowFunction */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + return childKind !== 196 /* Block */; + case 237 /* JsxElement */: + return childKind !== 241 /* JsxClosingElement */; + } + // No explicit rule for given nodes so the result will follow the default value argument + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + /* + Function returns true when the parent node should indent the given child by an explicit rule + */ function shouldIndentChildNode(parent, child) { - if (nodeContentIsAlwaysIndented(parent)) { - return true; - } - switch (parent) { - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 196 /* IfStatement */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 143 /* MethodDeclaration */: - case 174 /* ArrowFunction */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - return child !== 192 /* Block */; - default: - return false; - } + return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (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; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; /// /// /// @@ -43661,7 +47046,7 @@ var ts; return undefined; }; return StringScriptSnapshot; - })(); + }()); function fromString(text) { return new StringScriptSnapshot(text); } @@ -43709,13 +47094,18 @@ var ts; ]; var jsDocCompletionEntries; function createNode(kind, pos, end, flags, parent) { - var node = new (ts.getNodeConstructor(kind))(pos, end); + var node = new NodeObject(kind, pos, end); node.flags = flags; node.parent = parent; return node; } var NodeObject = (function () { - function NodeObject() { + function NodeObject(kind, pos, end) { + this.kind = kind; + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -43749,13 +47139,13 @@ var ts; while (pos < end) { var token = scanner.scan(); var textPos = scanner.getTextPos(); - nodes.push(createNode(token, pos, textPos, 2048 /* Synthetic */, this)); + nodes.push(createNode(token, pos, textPos, 0, this)); pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(271 /* SyntaxList */, nodes.pos, nodes.end, 2048 /* Synthetic */, this); + var list = createNode(275 /* SyntaxList */, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -43774,27 +47164,27 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 135 /* FirstNode */) { + if (this.kind >= 137 /* FirstNode */) { scanner.setText((sourceFile || this.getSourceFile()).text); children = []; - var pos = this.pos; + var pos_3 = this.pos; var processNode = function (node) { - if (pos < node.pos) { - pos = _this.addSyntheticNodes(children, pos, node.pos); + if (pos_3 < node.pos) { + pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos); } children.push(node); - pos = node.end; + pos_3 = node.end; }; var processNodes = function (nodes) { - if (pos < nodes.pos) { - pos = _this.addSyntheticNodes(children, pos, nodes.pos); + if (pos_3 < nodes.pos) { + pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos); } children.push(_this.createSyntaxList(nodes)); - pos = nodes.end; + pos_3 = nodes.end; }; ts.forEachChild(this, processNode, processNodes); - if (pos < this.end) { - this.addSyntheticNodes(children, pos, this.end); + if (pos_3 < this.end) { + this.addSyntheticNodes(children, pos_3, this.end); } scanner.setText(undefined); } @@ -43821,7 +47211,7 @@ var ts; return undefined; } var child = children[0]; - return child.kind < 135 /* FirstNode */ ? child : child.getFirstToken(sourceFile); + return child.kind < 137 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { var children = this.getChildren(sourceFile); @@ -43829,10 +47219,10 @@ var ts; if (!child) { return undefined; } - return child.kind < 135 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 137 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; return NodeObject; - })(); + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -43854,7 +47244,7 @@ var ts; return this.documentationComment; }; return SymbolObject; - })(); + }()); function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { var documentationComment = []; var docComments = getJsDocCommentsSeparatedByNewLines(); @@ -43872,31 +47262,31 @@ var ts; // Make sure we are collecting doc comment from declaration once, // In case of union property there might be same declaration multiple times // which only varies in type parameter - // Eg. let a: Array | Array; a.length + // Eg. const a: Array | Array; a.length // The property length will have two declarations of property length coming // from Array - Array and Array if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { - var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); + var sourceFileOfDeclaration_1 = 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 === 138 /* Parameter */) { - ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { - var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + if (canUseParsedParamTagComments && declaration.kind === 140 /* Parameter */) { + ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration_1), function (jsDocCommentTextRange) { + var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration_1); if (cleanedParamJsDocComment) { ts.addRange(jsDocCommentParts, cleanedParamJsDocComment); } }); } // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 218 /* ModuleDeclaration */ && declaration.body.kind === 218 /* ModuleDeclaration */) { + if (declaration.kind === 222 /* ModuleDeclaration */ && declaration.body.kind === 222 /* ModuleDeclaration */) { return; } // If this is dotted module name, get the doc comments from the parent - while (declaration.kind === 218 /* ModuleDeclaration */ && declaration.parent.kind === 218 /* ModuleDeclaration */) { + while (declaration.kind === 222 /* ModuleDeclaration */ && declaration.parent.kind === 222 /* ModuleDeclaration */) { declaration = declaration.parent; } // Get the cleaned js doc comment text from the declaration - ts.forEach(getJsDocCommentTextRange(declaration.kind === 211 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { - var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + ts.forEach(getJsDocCommentTextRange(declaration.kind === 215 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration_1), function (jsDocCommentTextRange) { + var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration_1); if (cleanedJsDocComment) { ts.addRange(jsDocCommentParts, cleanedJsDocComment); } @@ -43943,7 +47333,8 @@ var ts; } function pushDocCommentLineText(docComments, text, blankLineCount) { // Add the empty lines in between texts - while (blankLineCount--) { + while (blankLineCount) { + blankLineCount--; docComments.push(ts.textPart("")); } docComments.push(ts.textPart(text)); @@ -43969,7 +47360,7 @@ var ts; else if (spacesToRemoveAfterAsterisk === undefined) { spacesToRemoveAfterAsterisk = 0; } - // Analyse text on this line + // Analyze text on this line while (pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { var ch = sourceFile.text.charAt(pos); if (ch === "@") { @@ -44089,7 +47480,7 @@ var ts; } paramHelpStringMargin = undefined; } - // If this is the start of another tag, continue with the loop in seach of param tag with symbol name + // If this is the start of another tag, continue with the loop in search of param tag with symbol name if (sourceFile.text.charCodeAt(pos) === 64 /* at */) { continue; } @@ -44169,7 +47560,7 @@ var ts; : undefined; }; return TypeObject; - })(); + }()); var SignatureObject = (function () { function SignatureObject(checker) { this.checker = checker; @@ -44195,11 +47586,11 @@ var ts; return this.documentationComment; }; return SignatureObject; - })(); + }()); var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); - function SourceFileObject() { - _super.apply(this, arguments); + function SourceFileObject(kind, pos, end) { + _super.call(this, kind, pos, end); } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -44239,9 +47630,9 @@ var ts; if (result_2 !== undefined) { return result_2; } - if (declaration.name.kind === 136 /* ComputedPropertyName */) { + if (declaration.name.kind === 138 /* ComputedPropertyName */) { var expr = declaration.name.expression; - if (expr.kind === 166 /* PropertyAccessExpression */) { + if (expr.kind === 170 /* PropertyAccessExpression */) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -44261,9 +47652,9 @@ var ts; } function visit(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -44283,60 +47674,60 @@ var ts; ts.forEachChild(node, visit); } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: - case 218 /* ModuleDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 230 /* ExportSpecifier */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 155 /* TypeLiteral */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 221 /* EnumDeclaration */: + case 222 /* ModuleDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 234 /* ExportSpecifier */: + case 230 /* ImportSpecifier */: + case 225 /* ImportEqualsDeclaration */: + case 227 /* ImportClause */: + case 228 /* NamespaceImport */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 157 /* TypeLiteral */: addDeclaration(node); // fall through - case 144 /* Constructor */: - case 193 /* VariableStatement */: - case 212 /* VariableDeclarationList */: - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 219 /* ModuleBlock */: + case 146 /* Constructor */: + case 197 /* VariableStatement */: + case 216 /* VariableDeclarationList */: + case 165 /* ObjectBindingPattern */: + case 166 /* ArrayBindingPattern */: + case 223 /* ModuleBlock */: ts.forEachChild(node, visit); break; - case 192 /* Block */: + case 196 /* Block */: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } break; - case 138 /* Parameter */: + case 140 /* Parameter */: // Only consider properties defined as constructor parameters - if (!(node.flags & 56 /* AccessibilityModifier */)) { + if (!(node.flags & 28 /* AccessibilityModifier */)) { break; } // fall through - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } - case 247 /* EnumMember */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 251 /* EnumMember */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: addDeclaration(node); break; - case 228 /* ExportDeclaration */: + case 232 /* 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 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -44348,7 +47739,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 228 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -44361,12 +47752,12 @@ var ts; } }; return SourceFileObject; - })(NodeObject); + }(NodeObject)); var TextChange = (function () { function TextChange() { } return TextChange; - })(); + }()); ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { @@ -44456,7 +47847,7 @@ var ts; // enum E ScriptElementKind.enumElement = "enum"; // Inside module and script only - // let v = .. + // const v = .. ScriptElementKind.variableElement = "var"; // Inside function ScriptElementKind.localVariableElement = "local var"; @@ -44521,8 +47912,14 @@ var ts; ClassificationTypeNames.typeAliasName = "type alias name"; ClassificationTypeNames.parameterName = "parameter name"; ClassificationTypeNames.docCommentTagName = "doc comment tag name"; + ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; + ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; + ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; + ClassificationTypeNames.jsxAttribute = "jsx attribute"; + ClassificationTypeNames.jsxText = "jsx text"; + ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; return ClassificationTypeNames; - })(); + }()); ts.ClassificationTypeNames = ClassificationTypeNames; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; @@ -44543,6 +47940,12 @@ var ts; ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; })(ts.ClassificationType || (ts.ClassificationType = {})); var ClassificationType = ts.ClassificationType; function displayPartsToString(displayParts) { @@ -44558,16 +47961,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 173 /* FunctionExpression */) { + if (declaration.kind === 177 /* FunctionExpression */) { return true; } - if (declaration.kind !== 211 /* VariableDeclaration */ && declaration.kind !== 213 /* FunctionDeclaration */) { + if (declaration.kind !== 215 /* VariableDeclaration */ && declaration.kind !== 217 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable - for (var parent_8 = declaration.parent; !ts.isFunctionBlock(parent_8); parent_8 = parent_8.parent) { + for (var parent_10 = declaration.parent; !ts.isFunctionBlock(parent_10); parent_10 = parent_10.parent) { // Reached source file or module block - if (parent_8.kind === 248 /* SourceFile */ || parent_8.kind === 219 /* ModuleBlock */) { + if (parent_10.kind === 252 /* SourceFile */ || parent_10.kind === 223 /* ModuleBlock */) { return false; } } @@ -44579,7 +47982,6 @@ var ts; // Always default to "ScriptTarget.ES5" for the language service return { target: 1 /* ES5 */, - module: 0 /* None */, jsx: 1 /* Preserve */ }; } @@ -44608,12 +48010,14 @@ var ts; }; HostCache.prototype.createEntry = function (fileName, path) { var entry; + var scriptKind = this.host.getScriptKind ? this.host.getScriptKind(fileName) : 0 /* Unknown */; var scriptSnapshot = this.host.getScriptSnapshot(fileName); if (scriptSnapshot) { entry = { hostFileName: fileName, version: this.host.getScriptVersion(fileName), - scriptSnapshot: scriptSnapshot + scriptSnapshot: scriptSnapshot, + scriptKind: scriptKind ? scriptKind : ts.getScriptKindFromFileName(fileName) }; } this.fileNameToEntry.set(path, entry); @@ -44650,7 +48054,7 @@ var ts; return file && file.scriptSnapshot; }; return HostCache; - })(); + }()); var SyntaxTreeCache = (function () { function SyntaxTreeCache(host) { this.host = host; @@ -44661,11 +48065,12 @@ var ts; // The host does not know about this file. throw new Error("Could not find file: '" + fileName + "'."); } + var scriptKind = this.host.getScriptKind ? this.host.getScriptKind(fileName) : 0 /* Unknown */; var version = this.host.getScriptVersion(fileName); var sourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents:*/ true); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents*/ true, scriptKind); } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. @@ -44682,7 +48087,7 @@ var ts; return this.currentSourceFile; }; return SyntaxTreeCache; - })(); + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; @@ -44699,6 +48104,8 @@ var ts; function transpileModule(input, transpileOptions) { var options = transpileOptions.compilerOptions ? ts.clone(transpileOptions.compilerOptions) : getDefaultCompilerOptions(); options.isolatedModules = true; + // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. + options.suppressOutputPathCheck = true; // Filename can be non-ts file. options.allowNonTsExtensions = true; // We are not returning a sourceFile for lib file when asked by the program, @@ -44727,7 +48134,7 @@ var ts; sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); outputText = text; } }, @@ -44737,7 +48144,8 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; } + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; } }; var program = ts.createProgram([inputFileName], options, compilerHost); var diagnostics; @@ -44762,12 +48170,10 @@ var ts; return output.outputText; } ts.transpile = transpile; - function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents) { + function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents); + var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); - // after full parsing we can use table with interned strings as name table - sourceFile.nameTable = sourceFile.identifiers; return sourceFile; } ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; @@ -44779,7 +48185,7 @@ var ts; if (version !== sourceFile.version) { // Once incremental parsing is ready, then just call into this function. if (!ts.disableIncrementalParsing) { - var newText; + var newText = void 0; // 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) @@ -44819,23 +48225,17 @@ var ts; } } // Otherwise, just create a new source file. - return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents:*/ true); + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createGetCanonicalFileName(useCaseSensitivefileNames) { - return useCaseSensitivefileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); - } - ts.createGetCanonicalFileName = createGetCanonicalFileName; function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. var buckets = {}; - var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx; + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + +"|" + settings.allowJs; } function getBucketForCompilationSettings(settings, createIfMissing) { var key = getKeyFromCompilationSettings(settings); @@ -44846,7 +48246,7 @@ var ts; return bucket; } function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = ts.lookUp(buckets, name); var sourceFiles = []; entries.forEachValue(function (key, entry) { @@ -44862,22 +48262,22 @@ var ts; sourceFiles: sourceFiles }; }); - return JSON.stringify(bucketInfoArray, null, 2); + return JSON.stringify(bucketInfoArray, undefined, 2); } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ true); + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ true, scriptKind); } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ false); + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } - function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { + function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = bucket.get(path); 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, /*setNodeParents:*/ false); + var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); entry = { sourceFile: sourceFile, languageServiceRefCount: 0, @@ -44904,7 +48304,7 @@ var ts; return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { - var bucket = getBucketForCompilationSettings(compilationSettings, false); + var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ false); ts.Debug.assert(bucket !== undefined); var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = bucket.get(path); @@ -44922,8 +48322,9 @@ var ts; }; } ts.createDocumentRegistry = createDocumentRegistry; - function preProcessFile(sourceText, readImportFiles) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } var referencedFiles = []; var importedFiles = []; var ambientExternalModules; @@ -44957,9 +48358,207 @@ var ts; end: pos + importPath.length }); } - function processImport() { + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeDeclare() { + var token = scanner.getToken(); + if (token === 122 /* DeclareKeyword */) { + // declare module "mod" + token = scanner.scan(); + if (token === 125 /* ModuleKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + recordAmbientExternalModule(); + } + } + return true; + } + return false; + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeImport() { + var token = scanner.getToken(); + if (token === 89 /* ImportKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import "mod"; + recordModuleName(); + return true; + } + else { + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 134 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import d from "mod"; + recordModuleName(); + return true; + } + } + else if (token === 56 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + else if (token === 24 /* CommaToken */) { + // consume comma and keep going + token = scanner.scan(); + } + else { + // unknown syntax + return true; + } + } + if (token === 15 /* OpenBraceToken */) { + token = scanner.scan(); + // consume "{ a as B, c, d as D}" clauses + // make sure that it stops on EOF + while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = scanner.scan(); + } + if (token === 16 /* CloseBraceToken */) { + token = scanner.scan(); + if (token === 134 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import {a as A} from "mod"; + // import d, {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 37 /* AsteriskToken */) { + token = scanner.scan(); + if (token === 116 /* AsKeyword */) { + token = scanner.scan(); + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 134 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import * as NS from "mod" + // import d, * as NS from "mod" + recordModuleName(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = scanner.getToken(); + if (token === 82 /* ExportKeyword */) { + token = scanner.scan(); + if (token === 15 /* OpenBraceToken */) { + token = scanner.scan(); + // consume "{ a as B, c, d as D}" clauses + // make sure it stops on EOF + while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = scanner.scan(); + } + if (token === 16 /* CloseBraceToken */) { + token = scanner.scan(); + if (token === 134 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // export {a as A} from "mod"; + // export {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 37 /* AsteriskToken */) { + token = scanner.scan(); + if (token === 134 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // export * from "mod" + recordModuleName(); + } + } + } + else if (token === 89 /* ImportKeyword */) { + token = scanner.scan(); + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 56 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? scanner.scan() : scanner.getToken(); + if (token === 128 /* RequireKeyword */) { + token = scanner.scan(); + if (token === 17 /* OpenParenToken */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // require("mod"); + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = scanner.getToken(); + if (token === 69 /* Identifier */ && scanner.getTokenValue() === "define") { + token = scanner.scan(); + if (token !== 17 /* OpenParenToken */) { + return true; + } + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // looks like define ("modname", ... - skip string literal and comma + token = scanner.scan(); + if (token === 24 /* CommaToken */) { + token = scanner.scan(); + } + else { + // unexpected token + return true; + } + } + // should be start of dependency list + if (token !== 19 /* OpenBracketToken */) { + return true; + } + // skip open bracket + token = scanner.scan(); + var i = 0; + // scan until ']' or EOF + while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + // record string literals as module names + if (token === 9 /* StringLiteral */) { + recordModuleName(); + i++; + } + token = scanner.scan(); + } + return true; + } + return false; + } + function processImports() { scanner.setText(sourceText); - var token = scanner.scan(); + scanner.scan(); // Look for: // import "mod"; // import d from "mod" @@ -44971,152 +48570,26 @@ var ts; // export * from "mod" // export {a as b} from "mod" // export import i = require("mod") - while (token !== 1 /* EndOfFileToken */) { - if (token === 122 /* DeclareKeyword */) { - // declare module "mod" - token = scanner.scan(); - if (token === 125 /* ModuleKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - recordAmbientExternalModule(); - continue; - } - } + // (for JavaScript files) require("mod") + while (true) { + if (scanner.getToken() === 1 /* EndOfFileToken */) { + break; } - else if (token === 89 /* ImportKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // import "mod"; - recordModuleName(); - continue; - } - else { - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = scanner.scan(); - if (token === 133 /* FromKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // import d from "mod"; - recordModuleName(); - continue; - } - } - else if (token === 56 /* EqualsToken */) { - token = scanner.scan(); - if (token === 127 /* RequireKeyword */) { - token = scanner.scan(); - if (token === 17 /* OpenParenToken */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // import i = require("mod"); - recordModuleName(); - continue; - } - } - } - } - else if (token === 24 /* CommaToken */) { - // consume comma and keep going - token = scanner.scan(); - } - else { - // unknown syntax - continue; - } - } - if (token === 15 /* OpenBraceToken */) { - token = scanner.scan(); - // consume "{ a as B, c, d as D}" clauses - while (token !== 16 /* CloseBraceToken */) { - token = scanner.scan(); - } - if (token === 16 /* CloseBraceToken */) { - token = scanner.scan(); - if (token === 133 /* FromKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // import {a as A} from "mod"; - // import d, {a, b as B} from "mod" - recordModuleName(); - } - } - } - } - else if (token === 37 /* AsteriskToken */) { - token = scanner.scan(); - if (token === 116 /* AsKeyword */) { - token = scanner.scan(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = scanner.scan(); - if (token === 133 /* FromKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // import * as NS from "mod" - // import d, * as NS from "mod" - recordModuleName(); - } - } - } - } - } - } + // check if at least one of alternative have moved scanner forward + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { + continue; } - else if (token === 82 /* ExportKeyword */) { - token = scanner.scan(); - if (token === 15 /* OpenBraceToken */) { - token = scanner.scan(); - // consume "{ a as B, c, d as D}" clauses - while (token !== 16 /* CloseBraceToken */) { - token = scanner.scan(); - } - if (token === 16 /* CloseBraceToken */) { - token = scanner.scan(); - if (token === 133 /* FromKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // export {a as A} from "mod"; - // export {a, b as B} from "mod" - recordModuleName(); - } - } - } - } - else if (token === 37 /* AsteriskToken */) { - token = scanner.scan(); - if (token === 133 /* FromKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // export * from "mod" - recordModuleName(); - } - } - } - else if (token === 89 /* ImportKeyword */) { - token = scanner.scan(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = scanner.scan(); - if (token === 56 /* EqualsToken */) { - token = scanner.scan(); - if (token === 127 /* RequireKeyword */) { - token = scanner.scan(); - if (token === 17 /* OpenParenToken */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // export import i = require("mod"); - recordModuleName(); - } - } - } - } - } - } + else { + scanner.scan(); } - token = scanner.scan(); } scanner.setText(undefined); } if (readImportFiles) { - processImport(); + processImports(); } processTripleSlashDirectives(); return { referencedFiles: referencedFiles, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientExternalModules }; @@ -45125,7 +48598,7 @@ var ts; /// Helpers function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 207 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 211 /* LabeledStatement */ && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -45134,12 +48607,12 @@ var ts; } function isJumpStatementTarget(node) { return node.kind === 69 /* Identifier */ && - (node.parent.kind === 203 /* BreakStatement */ || node.parent.kind === 202 /* ContinueStatement */) && + (node.parent.kind === 207 /* BreakStatement */ || node.parent.kind === 206 /* ContinueStatement */) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { return node.kind === 69 /* Identifier */ && - node.parent.kind === 207 /* LabeledStatement */ && + node.parent.kind === 211 /* LabeledStatement */ && node.parent.label === node; } /** @@ -45147,7 +48620,7 @@ var ts; * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 207 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 211 /* LabeledStatement */; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -45158,25 +48631,25 @@ var ts; return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } function isRightSideOfQualifiedName(node) { - return node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 137 /* QualifiedName */ && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 170 /* PropertyAccessExpression */ && node.parent.name === node; } function isCallExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 168 /* CallExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 172 /* CallExpression */ && node.parent.expression === node; } function isNewExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 173 /* NewExpression */ && node.parent.expression === node; } function isNameOfModuleDeclaration(node) { - return node.parent.kind === 218 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 222 /* ModuleDeclaration */ && node.parent.name === node; } function isNameOfFunctionDeclaration(node) { return node.kind === 69 /* Identifier */ && @@ -45185,22 +48658,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 === 69 /* Identifier */ || node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - (node.parent.kind === 245 /* PropertyAssignment */ || node.parent.kind === 246 /* ShorthandPropertyAssignment */) && node.parent.name === node; + (node.parent.kind === 249 /* PropertyAssignment */ || node.parent.kind === 250 /* ShorthandPropertyAssignment */) && node.parent.name === node; } function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { switch (node.parent.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 247 /* EnumMember */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 218 /* ModuleDeclaration */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 249 /* PropertyAssignment */: + case 251 /* EnumMember */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 222 /* ModuleDeclaration */: return node.parent.name === node; - case 167 /* ElementAccessExpression */: + case 171 /* ElementAccessExpression */: return node.parent.argumentExpression === node; } } @@ -45259,7 +48732,7 @@ var ts; })(BreakContinueSearchType || (BreakContinueSearchType = {})); // A cache of completion entries for keywords, these do not change between sessions var keywordCompletions = []; - for (var i = 70 /* FirstKeyword */; i <= 134 /* LastKeyword */; i++) { + for (var i = 70 /* FirstKeyword */; i <= 136 /* LastKeyword */; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ScriptElementKind.keyword, @@ -45274,17 +48747,17 @@ var ts; return undefined; } switch (node.kind) { - case 248 /* SourceFile */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 218 /* ModuleDeclaration */: + case 252 /* SourceFile */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 222 /* ModuleDeclaration */: return node; } } @@ -45292,38 +48765,38 @@ var ts; ts.getContainerNode = getContainerNode; /* @internal */ function getNodeKind(node) { switch (node.kind) { - case 218 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; - case 214 /* ClassDeclaration */: return ScriptElementKind.classElement; - case 215 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; - case 216 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; - case 217 /* EnumDeclaration */: return ScriptElementKind.enumElement; - case 211 /* VariableDeclaration */: + case 222 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; + case 218 /* ClassDeclaration */: return ScriptElementKind.classElement; + case 219 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; + case 220 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; + case 221 /* EnumDeclaration */: return ScriptElementKind.enumElement; + case 215 /* VariableDeclaration */: return ts.isConst(node) ? ScriptElementKind.constElement : ts.isLet(node) ? ScriptElementKind.letElement : ScriptElementKind.variableElement; - case 213 /* FunctionDeclaration */: return ScriptElementKind.functionElement; - case 145 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; - case 146 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 217 /* FunctionDeclaration */: return ScriptElementKind.functionElement; + case 147 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; + case 148 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return ScriptElementKind.memberFunctionElement; - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return ScriptElementKind.memberVariableElement; - case 149 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; - case 148 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; - case 147 /* CallSignature */: return ScriptElementKind.callSignatureElement; - case 144 /* Constructor */: return ScriptElementKind.constructorImplementationElement; - case 137 /* TypeParameter */: return ScriptElementKind.typeParameterElement; - case 247 /* EnumMember */: return ScriptElementKind.variableElement; - case 138 /* Parameter */: return (node.flags & 56 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 223 /* ImportClause */: - case 230 /* ExportSpecifier */: - case 224 /* NamespaceImport */: + case 151 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; + case 150 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; + case 149 /* CallSignature */: return ScriptElementKind.callSignatureElement; + case 146 /* Constructor */: return ScriptElementKind.constructorImplementationElement; + case 139 /* TypeParameter */: return ScriptElementKind.typeParameterElement; + case 251 /* EnumMember */: return ScriptElementKind.variableElement; + case 140 /* Parameter */: return (node.flags & 28 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case 225 /* ImportEqualsDeclaration */: + case 230 /* ImportSpecifier */: + case 227 /* ImportClause */: + case 234 /* ExportSpecifier */: + case 228 /* NamespaceImport */: return ScriptElementKind.alias; } return ScriptElementKind.unknown; @@ -45342,7 +48815,7 @@ var ts; } }; return CancellationTokenObject; - })(); + }()); function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -45361,7 +48834,7 @@ var ts; host.log(message); } } - var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -45405,7 +48878,8 @@ var ts; (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx); + oldSettings.jsx !== newSettings.jsx || + oldSettings.allowJs !== newSettings.allowJs); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -45425,8 +48899,15 @@ var ts; // stub missing host functionality var entry = hostCache.getOrCreateEntry(fileName); return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + }, + directoryExists: function (directoryName) { + ts.Debug.assert(!host.resolveModuleNames); + return ts.directoryProbablyExists(directoryName, host); } }; + if (host.trace) { + compilerHost.trace = function (message) { return host.trace(message); }; + } if (host.resolveModuleNames) { compilerHost.resolveModuleNames = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } @@ -45460,7 +48941,7 @@ var ts; return undefined; } // Check if the language version has changed since we last created a program; if they are the same, - // it is safe to reuse the souceFiles; if not, then the shape of the AST can change, and the oldSourceFile + // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. if (!changesInCompilationSettingsAffectSyntax) { // Check if the old program had this file already @@ -45468,7 +48949,7 @@ var ts; if (oldSourceFile) { // We already had a source file for this file name. Go to the registry to // ensure that we get the right up to date version of it. We need this to - // address the following 'race'. Specifically, say we have the following: + // address the following race-condition. Specifically, say we have the following: // // LS1 // \ @@ -45487,15 +48968,22 @@ var ts; // it's source file any more, and instead defers to DocumentRegistry to get // either version 1, version 2 (or some other version) depending on what the // host says should be used. - return documentRegistry.updateDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); + // We do not support the scenario where a host can modify a registered + // file's script kind, i.e. in one project some file is treated as ".ts" + // and in another as ".js" + ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + fileName); + return documentRegistry.updateDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } } // Could not find this file in the old program, create a new SourceFile for it. - return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); + return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } function sourceFileUpToDate(sourceFile) { + if (!sourceFile) { + return false; + } var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); - return sourceFile && sourceFile.version === hostCache.getVersion(path); + return sourceFile.version === hostCache.getVersion(path); } function programUpToDate() { // If we haven't create a program yet, then it is not up-to-date @@ -45538,18 +49026,12 @@ var ts; return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken); } /** - * getSemanticDiagnostiscs return array of Diagnostics. If '-d' is not enabled, only report semantic errors + * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors * If '-d' enabled, report both semantic and emitter errors */ function getSemanticDiagnostics(fileName) { synchronizeHostData(); var targetSourceFile = getValidSourceFile(fileName); - // For JavaScript files, we don't want to report the normal typescript semantic errors. - // Instead, we just report errors for using TypeScript-only constructs from within a - // JavaScript file. - if (ts.isJavaScript(fileName)) { - return getJavaScriptSemanticDiagnostics(targetSourceFile); - } // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); @@ -45560,151 +49042,6 @@ var ts; var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return ts.concatenate(semanticDiagnostics, declarationDiagnostics); } - function getJavaScriptSemanticDiagnostics(sourceFile) { - var diagnostics = []; - walk(sourceFile); - return diagnostics; - function walk(node) { - if (!node) { - return false; - } - switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 227 /* ExportAssignment */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; - case 214 /* ClassDeclaration */: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 243 /* HeritageClause */: - var heritageClause = node; - if (heritageClause.token === 106 /* ImplementsKeyword */) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 215 /* InterfaceDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 218 /* ModuleDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 216 /* TypeAliasDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: - case 213 /* FunctionDeclaration */: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; - } - break; - case 193 /* VariableStatement */: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 211 /* VariableDeclaration */: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 168 /* CallExpression */: - case 169 /* NewExpression */: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 138 /* Parameter */: - var parameter = node; - if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return true; - } - if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, '?')); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 141 /* PropertyDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 217 /* EnumDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 171 /* 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 139 /* Decorator */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 122 /* DeclareKeyword */: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - // These are all legal modifiers. - case 113 /* StaticKeyword */: - case 82 /* ExportKeyword */: - case 74 /* ConstKeyword */: - case 77 /* DefaultKeyword */: - case 115 /* AbstractKeyword */: - } - } - } - return false; - } - } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); @@ -45721,7 +49058,7 @@ var ts; // First check of the displayName is not external module; if it is an external module, it is not valid entry if ((symbol.flags & 1536 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { let x; } | // <= request completion here, "http" should not be there) + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } @@ -45744,22 +49081,16 @@ var ts; // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks) { - if (!ts.isIdentifierStart(name.charCodeAt(0), target)) { + if (!ts.isIdentifier(name, target)) { return undefined; } - for (var i = 1, n = name.length; i < n; i++) { - if (!ts.isIdentifierPart(name.charCodeAt(i), target)) { - return undefined; - } - } } return name; } function getCompletionData(fileName, position) { var typeChecker = program.getTypeChecker(); - var syntacticStart = new Date().getTime(); var sourceFile = getValidSourceFile(fileName); - var isJavaScriptFile = ts.isJavaScript(fileName); + var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; var start = new Date().getTime(); var currentToken = ts.getTokenAtPosition(sourceFile, position); @@ -45769,7 +49100,7 @@ var ts; var insideComment = isInsideComment(sourceFile, currentToken, position); log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); if (insideComment) { - // The current position is next to the '@' sign, when no tag name being provided yet. + // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { isJsDocTagName = true; @@ -45784,9 +49115,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { - case 269 /* JSDocTypeTag */: - case 267 /* JSDocParameterTag */: - case 268 /* JSDocReturnTag */: + case 273 /* JSDocTypeTag */: + case 271 /* JSDocParameterTag */: + case 272 /* JSDocReturnTag */: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -45798,7 +49129,7 @@ var ts; return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { - // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; @@ -45813,9 +49144,9 @@ var ts; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_3 = new Date().getTime(); + var start_6 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_3)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -45831,13 +49162,13 @@ var ts; log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent_9 = contextToken.parent, kind = contextToken.kind; + var parent_11 = contextToken.parent, kind = contextToken.kind; if (kind === 21 /* DotToken */) { - if (parent_9.kind === 166 /* PropertyAccessExpression */) { + if (parent_11.kind === 170 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent_9.kind === 135 /* QualifiedName */) { + else if (parent_11.kind === 137 /* QualifiedName */) { node = contextToken.parent.left; isRightOfDot = true; } @@ -45852,8 +49183,9 @@ var ts; isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 237 /* JsxClosingElement */) { + else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 241 /* JsxClosingElement */) { isStartingCloseTag = true; + location = contextToken; } } } @@ -45877,7 +49209,10 @@ var ts; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; - symbols = [typeChecker.getSymbolAtLocation(tagName)]; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (!typeChecker.isUnknownSymbol(tagSymbol)) { + symbols = [tagSymbol]; + } isMemberCompletion = true; isNewIdentifierLocation = false; } @@ -45895,7 +49230,7 @@ var ts; // Right of dot member completion list isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */) { + if (node.kind === 69 /* Identifier */ || node.kind === 137 /* QualifiedName */ || node.kind === 170 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases if (symbol && symbol.flags & 8388608 /* Alias */) { @@ -45950,8 +49285,8 @@ var ts; return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { - var attrsType; - if ((jsxContainer.kind === 234 /* JsxSelfClosingElement */) || (jsxContainer.kind === 235 /* JsxOpeningElement */)) { + var attrsType = void 0; + if ((jsxContainer.kind === 238 /* JsxSelfClosingElement */) || (jsxContainer.kind === 239 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { @@ -46023,15 +49358,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 236 /* JsxText */) { + if (contextToken.kind === 240 /* JsxText */) { return true; } if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 235 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 239 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 237 /* JsxClosingElement */ || contextToken.parent.kind === 234 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 233 /* JsxElement */; + if (contextToken.parent.kind === 241 /* JsxClosingElement */ || contextToken.parent.kind === 238 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 237 /* JsxElement */; } } return false; @@ -46041,40 +49376,40 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 24 /* CommaToken */: - return containingNodeKind === 168 /* CallExpression */ // func( a, | - || containingNodeKind === 144 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 169 /* NewExpression */ // new C(a, | - || containingNodeKind === 164 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 181 /* BinaryExpression */ // let x = (a, | - || containingNodeKind === 152 /* FunctionType */; // var x: (s: string, list| + return containingNodeKind === 172 /* CallExpression */ // func( a, | + || containingNodeKind === 146 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 173 /* NewExpression */ // new C(a, | + || containingNodeKind === 168 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 185 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 154 /* FunctionType */; // var x: (s: string, list| case 17 /* OpenParenToken */: - return containingNodeKind === 168 /* CallExpression */ // func( | - || containingNodeKind === 144 /* Constructor */ // constructor( | - || containingNodeKind === 169 /* NewExpression */ // new C(a| - || containingNodeKind === 172 /* ParenthesizedExpression */ // let x = (a| - || containingNodeKind === 160 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + return containingNodeKind === 172 /* CallExpression */ // func( | + || containingNodeKind === 146 /* Constructor */ // constructor( | + || containingNodeKind === 173 /* NewExpression */ // new C(a| + || containingNodeKind === 176 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 162 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 19 /* OpenBracketToken */: - return containingNodeKind === 164 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 149 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 136 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + return containingNodeKind === 168 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 151 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 138 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 125 /* ModuleKeyword */: // module | case 126 /* NamespaceKeyword */: return true; case 21 /* DotToken */: - return containingNodeKind === 218 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 222 /* ModuleDeclaration */; // module A.| case 15 /* OpenBraceToken */: - return containingNodeKind === 214 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 218 /* ClassDeclaration */; // class A{ | case 56 /* EqualsToken */: - return containingNodeKind === 211 /* VariableDeclaration */ // let x = a| - || containingNodeKind === 181 /* BinaryExpression */; // x = a| + return containingNodeKind === 215 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 185 /* BinaryExpression */; // x = a| case 12 /* TemplateHead */: - return containingNodeKind === 183 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 187 /* TemplateExpression */; // `aa ${| case 13 /* TemplateMiddle */: - return containingNodeKind === 190 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 194 /* TemplateSpan */; // `aa ${10} dd ${| case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: - return containingNodeKind === 141 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 143 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. switch (previousToken.getText()) { @@ -46088,15 +49423,16 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 /* StringLiteral */ + || contextToken.kind === 164 /* StringLiteralType */ || contextToken.kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_4 = contextToken.getStart(); + var start_7 = contextToken.getStart(); var end = contextToken.getEnd(); // To be "in" one of these literals, the position has to be: // 1. entirely within the token text. // 2. at the end position of an unterminated token. // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). - if (start_4 < position && position < end) { + if (start_7 < position && position < end) { return true; } if (position === end) { @@ -46117,14 +49453,14 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 165 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 169 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 161 /* ObjectBindingPattern */) { + else if (objectLikeContainer.kind === 165 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -46170,9 +49506,9 @@ var ts; * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 225 /* NamedImports */ ? - 222 /* ImportDeclaration */ : - 228 /* ExportDeclaration */; + var declarationKind = namedImportsOrExports.kind === 229 /* NamedImports */ ? + 226 /* ImportDeclaration */ : + 232 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -46195,11 +49531,11 @@ var ts; function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // let x = { | + case 15 /* OpenBraceToken */: // const x = { | case 24 /* CommaToken */: - var parent_10 = contextToken.parent; - if (parent_10 && (parent_10.kind === 165 /* ObjectLiteralExpression */ || parent_10.kind === 161 /* ObjectBindingPattern */)) { - return parent_10; + var parent_12 = contextToken.parent; + if (parent_12 && (parent_12.kind === 169 /* ObjectLiteralExpression */ || parent_12.kind === 165 /* ObjectBindingPattern */)) { + return parent_12; } break; } @@ -46216,8 +49552,8 @@ var ts; case 15 /* OpenBraceToken */: // import { | case 24 /* CommaToken */: switch (contextToken.parent.kind) { - case 225 /* NamedImports */: - case 229 /* NamedExports */: + case 229 /* NamedImports */: + case 233 /* NamedExports */: return contextToken.parent; } } @@ -46226,37 +49562,37 @@ var ts; } function tryGetContainingJsxElement(contextToken) { if (contextToken) { - var parent_11 = contextToken.parent; + var parent_13 = contextToken.parent; switch (contextToken.kind) { case 26 /* LessThanSlashToken */: case 39 /* SlashToken */: case 69 /* Identifier */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - if (parent_11 && (parent_11.kind === 234 /* JsxSelfClosingElement */ || parent_11.kind === 235 /* JsxOpeningElement */)) { - return parent_11; + case 242 /* JsxAttribute */: + case 243 /* JsxSpreadAttribute */: + if (parent_13 && (parent_13.kind === 238 /* JsxSelfClosingElement */ || parent_13.kind === 239 /* JsxOpeningElement */)) { + return parent_13; } - else if (parent_11.kind === 238 /* JsxAttribute */) { - return parent_11.parent; + else if (parent_13.kind === 242 /* JsxAttribute */) { + return parent_13.parent; } break; // The context token is the closing } or " of an attribute, which means // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 9 /* StringLiteral */: - if (parent_11 && ((parent_11.kind === 238 /* JsxAttribute */) || (parent_11.kind === 239 /* JsxSpreadAttribute */))) { - return parent_11.parent; + if (parent_13 && ((parent_13.kind === 242 /* JsxAttribute */) || (parent_13.kind === 243 /* JsxSpreadAttribute */))) { + return parent_13.parent; } break; case 16 /* CloseBraceToken */: - if (parent_11 && - parent_11.kind === 240 /* JsxExpression */ && - parent_11.parent && - (parent_11.parent.kind === 238 /* JsxAttribute */)) { - return parent_11.parent.parent; + if (parent_13 && + parent_13.kind === 244 /* JsxExpression */ && + parent_13.parent && + (parent_13.parent.kind === 242 /* JsxAttribute */)) { + return parent_13.parent.parent; } - if (parent_11 && parent_11.kind === 239 /* JsxSpreadAttribute */) { - return parent_11.parent; + if (parent_13 && parent_13.kind === 243 /* JsxSpreadAttribute */) { + return parent_13.parent; } break; } @@ -46265,16 +49601,16 @@ var ts; } function isFunction(kind) { switch (kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: return true; } return false; @@ -46286,66 +49622,66 @@ var ts; var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 24 /* CommaToken */: - return containingNodeKind === 211 /* VariableDeclaration */ || - containingNodeKind === 212 /* VariableDeclarationList */ || - containingNodeKind === 193 /* VariableStatement */ || - containingNodeKind === 217 /* EnumDeclaration */ || + return containingNodeKind === 215 /* VariableDeclaration */ || + containingNodeKind === 216 /* VariableDeclarationList */ || + containingNodeKind === 197 /* VariableStatement */ || + containingNodeKind === 221 /* EnumDeclaration */ || isFunction(containingNodeKind) || - containingNodeKind === 214 /* ClassDeclaration */ || - containingNodeKind === 186 /* ClassExpression */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 162 /* ArrayBindingPattern */ || - containingNodeKind === 216 /* TypeAliasDeclaration */; // type Map, K, | + containingNodeKind === 218 /* ClassDeclaration */ || + containingNodeKind === 190 /* ClassExpression */ || + containingNodeKind === 219 /* InterfaceDeclaration */ || + containingNodeKind === 166 /* ArrayBindingPattern */ || + containingNodeKind === 220 /* TypeAliasDeclaration */; // type Map, K, | case 21 /* DotToken */: - return containingNodeKind === 162 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 166 /* ArrayBindingPattern */; // var [.| case 54 /* ColonToken */: - return containingNodeKind === 163 /* BindingElement */; // var {x :html| + return containingNodeKind === 167 /* BindingElement */; // var {x :html| case 19 /* OpenBracketToken */: - return containingNodeKind === 162 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 166 /* ArrayBindingPattern */; // var [x| case 17 /* OpenParenToken */: - return containingNodeKind === 244 /* CatchClause */ || + return containingNodeKind === 248 /* CatchClause */ || isFunction(containingNodeKind); case 15 /* OpenBraceToken */: - return containingNodeKind === 217 /* EnumDeclaration */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 155 /* TypeLiteral */; // let x : { | + return containingNodeKind === 221 /* EnumDeclaration */ || + containingNodeKind === 219 /* InterfaceDeclaration */ || + containingNodeKind === 157 /* TypeLiteral */; // const x : { | case 23 /* SemicolonToken */: - return containingNodeKind === 140 /* PropertySignature */ && + return containingNodeKind === 142 /* PropertySignature */ && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 215 /* InterfaceDeclaration */ || - contextToken.parent.parent.kind === 155 /* TypeLiteral */); // let x : { a; | + (contextToken.parent.parent.kind === 219 /* InterfaceDeclaration */ || + contextToken.parent.parent.kind === 157 /* TypeLiteral */); // const x : { a; | case 25 /* LessThanToken */: - return containingNodeKind === 214 /* ClassDeclaration */ || - containingNodeKind === 186 /* ClassExpression */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 216 /* TypeAliasDeclaration */ || + return containingNodeKind === 218 /* ClassDeclaration */ || + containingNodeKind === 190 /* ClassExpression */ || + containingNodeKind === 219 /* InterfaceDeclaration */ || + containingNodeKind === 220 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 113 /* StaticKeyword */: - return containingNodeKind === 141 /* PropertyDeclaration */; + return containingNodeKind === 143 /* PropertyDeclaration */; case 22 /* DotDotDotToken */: - return containingNodeKind === 138 /* Parameter */ || + return containingNodeKind === 140 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 162 /* ArrayBindingPattern */); // var [...z| + contextToken.parent.parent.kind === 166 /* ArrayBindingPattern */); // var [...z| case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: - return containingNodeKind === 138 /* Parameter */; + return containingNodeKind === 140 /* Parameter */; case 116 /* AsKeyword */: - return containingNodeKind === 226 /* ImportSpecifier */ || - containingNodeKind === 230 /* ExportSpecifier */ || - containingNodeKind === 224 /* NamespaceImport */; + return containingNodeKind === 230 /* ImportSpecifier */ || + containingNodeKind === 234 /* ExportSpecifier */ || + containingNodeKind === 228 /* NamespaceImport */; case 73 /* ClassKeyword */: case 81 /* EnumKeyword */: case 107 /* InterfaceKeyword */: case 87 /* FunctionKeyword */: case 102 /* VarKeyword */: case 123 /* GetKeyword */: - case 129 /* SetKeyword */: + case 130 /* SetKeyword */: case 89 /* ImportKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: case 114 /* YieldKeyword */: - case 132 /* TypeKeyword */: + case 133 /* TypeKeyword */: return true; } // Previous token may have been a keyword that was converted to an identifier. @@ -46386,20 +49722,20 @@ var ts; * do not occur at the current position and have not otherwise been typed. */ function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var exisingImportsOrExports = {}; + var existingImportsOrExports = {}; for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_33 = element.propertyName || element.name; - exisingImportsOrExports[name_33.text] = true; + var name_34 = element.propertyName || element.name; + existingImportsOrExports[name_34.text] = true; } - if (ts.isEmpty(exisingImportsOrExports)) { + if (ts.isEmpty(existingImportsOrExports)) { return exportsOfModule; } - return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(exisingImportsOrExports, e.name); }); + return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(existingImportsOrExports, e.name); }); } /** * Filters out completion suggestions for named imports or exports. @@ -46415,9 +49751,10 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 245 /* PropertyAssignment */ && - m.kind !== 246 /* ShorthandPropertyAssignment */ && - m.kind !== 163 /* BindingElement */) { + if (m.kind !== 249 /* PropertyAssignment */ && + m.kind !== 250 /* ShorthandPropertyAssignment */ && + m.kind !== 167 /* BindingElement */ && + m.kind !== 145 /* MethodDeclaration */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -46425,8 +49762,11 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 163 /* BindingElement */ && m.propertyName) { - existingName = m.propertyName.text; + if (m.kind === 167 /* BindingElement */ && m.propertyName) { + // include only identifiers in completion list + if (m.propertyName.kind === 69 /* Identifier */) { + existingName = m.propertyName.text; + } } else { // TODO(jfreeman): Account for computed property name @@ -46452,7 +49792,7 @@ var ts; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } - if (attr.kind === 238 /* JsxAttribute */) { + if (attr.kind === 242 /* JsxAttribute */) { seenNames[attr.name.text] = true; } } @@ -46465,47 +49805,64 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isRightOfDot = completionData.isRightOfDot, isJsDocTagName = completionData.isJsDocTagName; - var entries; + var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() }; } - if (isRightOfDot && ts.isJavaScript(fileName)) { - entries = getCompletionEntriesFromSymbols(symbols); - ts.addRange(entries, getJavaScriptCompletionEntries()); + var sourceFile = getValidSourceFile(fileName); + var entries = []; + if (ts.isSourceFileJavaScript(sourceFile)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries); + ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { if (!symbols || symbols.length === 0) { - return undefined; + if (sourceFile.languageVariant === 1 /* JSX */ && + location.parent && location.parent.kind === 241 /* JsxClosingElement */) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
completion list at "1" will contain "div" with type any + var tagName = location.parent.parent.openingElement.tagName; + entries.push({ + name: tagName.text, + kind: undefined, + kindModifiers: undefined, + sortText: "0" + }); + } + else { + return undefined; + } } - entries = getCompletionEntriesFromSymbols(symbols); + getCompletionEntriesFromSymbols(symbols, entries); } // Add keywords if this is not a member completion list if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - function getJavaScriptCompletionEntries() { + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; - var allNames = {}; var target = program.getCompilerOptions().target; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - var nameTable = getNameTable(sourceFile); - for (var name_34 in nameTable) { - if (!allNames[name_34]) { - allNames[name_34] = name_34; - var displayName = getCompletionEntryDisplayName(name_34, target, /*performCharacterChecks:*/ true); - if (displayName) { - var entry = { - name: displayName, - kind: ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } + var nameTable = getNameTable(sourceFile); + for (var name_35 in nameTable) { + // Skip identifiers produced only from the current location + if (nameTable[name_35] === position) { + continue; + } + if (!uniqueNames[name_35]) { + uniqueNames[name_35] = name_35; + var displayName = getCompletionEntryDisplayName(name_35, target, /*performCharacterChecks*/ true); + if (displayName) { + var entry = { + name: displayName, + kind: ScriptElementKind.warning, + kindModifiers: "", + sortText: "1" + }; + entries.push(entry); } } } @@ -46525,7 +49882,7 @@ var ts; // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks:*/ true, location); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks*/ true, location); if (!displayName) { return undefined; } @@ -46543,25 +49900,24 @@ var ts; sortText: "0" }; } - function getCompletionEntriesFromSymbols(symbols) { + function getCompletionEntriesFromSymbols(symbols, entries) { var start = new Date().getTime(); - var entries = []; + var uniqueNames = {}; if (symbols) { - var nameToSymbol = {}; - for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { - var symbol = symbols_3[_i]; + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; var entry = createCompletionEntry(symbol, location); if (entry) { var id = ts.escapeIdentifier(entry.name); - if (!ts.lookUp(nameToSymbol, id)) { + if (!ts.lookUp(uniqueNames, id)) { entries.push(entry); - nameToSymbol[id] = symbol; + uniqueNames[id] = id; } } } } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); - return entries; + return uniqueNames; } } function getCompletionEntryDetails(fileName, position, entryName) { @@ -46571,11 +49927,11 @@ var ts; if (completionData) { var symbols = completionData.symbols, location_2 = completionData.location; // Find the symbol with the matching entry name. - var target = program.getCompilerOptions().target; + var target_2 = program.getCompilerOptions().target; // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false, location_2) === entryName ? s : undefined; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target_2, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); if (symbol) { var _a = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; return { @@ -46604,7 +49960,7 @@ var ts; function getSymbolKind(symbol, location) { var flags = symbol.getFlags(); if (flags & 32 /* Class */) - return ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 190 /* ClassExpression */) ? ScriptElementKind.localClassElement : ScriptElementKind.classElement; if (flags & 384 /* Enum */) return ScriptElementKind.enumElement; @@ -46669,7 +50025,7 @@ var ts; }); if (!unionPropertyKind) { // If this was union of all methods, - //make sure it has call signatures before we can label it as method + // make sure it has call signatures before we can label it as method var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { return ScriptElementKind.memberFunctionElement; @@ -46703,10 +50059,10 @@ var ts; if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { symbolKind = ScriptElementKind.memberVariableElement; } - var signature; + var signature = void 0; type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 166 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 170 /* 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)) { @@ -46714,8 +50070,8 @@ var ts; } } // try get the call/construct signature from the type if it matches - var callExpression; - if (location.kind === 168 /* CallExpression */ || location.kind === 169 /* NewExpression */) { + var callExpression = void 0; + if (location.kind === 172 /* CallExpression */ || location.kind === 173 /* NewExpression */) { callExpression = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -46728,7 +50084,7 @@ var ts; // Use the first candidate: signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 169 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; + var useConstructSignatures = callExpression.kind === 173 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain @@ -46781,24 +50137,24 @@ var ts; } } else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || - (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 144 /* Constructor */)) { + (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 146 /* Constructor */)) { // get the signature from the declaration and write it var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 144 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); + var allSignatures = functionDeclaration.kind === 146 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 144 /* Constructor */) { + if (functionDeclaration.kind === 146 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 147 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 149 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -46807,7 +50163,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo) { - if (ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 190 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -46830,7 +50186,7 @@ var ts; } if (symbolFlags & 524288 /* TypeAlias */) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(133 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); @@ -46851,7 +50207,7 @@ var ts; } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 218 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 222 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -46874,35 +50230,37 @@ var ts; } else { // Method/function type parameter - var container = ts.getContainingFunction(location); - if (container) { - var signatureDeclaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).parent; - var signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration); - if (signatureDeclaration.kind === 148 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + var declaration = ts.getDeclarationOfKind(symbol, 139 /* TypeParameter */); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 150 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 149 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + displayParts.push(ts.keywordPart(133 /* TypeKeyword */)); displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } - else if (signatureDeclaration.kind !== 147 /* CallSignature */ && signatureDeclaration.name) { - addFullSymbolName(signatureDeclaration.symbol); - } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); - } - else { - // Type aliash type parameter - // For example - // type list = T[]; // Both T will go through same code path - var declaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).parent; - displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(declaration.symbol); - writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } } } if (symbolFlags & 8 /* EnumMember */) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 247 /* EnumMember */) { + if (declaration.kind === 251 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -46918,13 +50276,13 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 221 /* ImportEqualsDeclaration */) { + if (declaration.kind === 225 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(127 /* RequireKeyword */)); + displayParts.push(ts.keywordPart(128 /* RequireKeyword */)); displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); @@ -47047,13 +50405,14 @@ var ts; } var typeChecker = program.getTypeChecker(); var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { + if (!symbol || typeChecker.isUnknownSymbol(symbol)) { // Try getting just type at this position and show switch (node.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: - case 135 /* QualifiedName */: + case 170 /* PropertyAccessExpression */: + case 137 /* QualifiedName */: case 97 /* ThisKeyword */: + case 163 /* ThisType */: case 95 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); @@ -47132,8 +50491,8 @@ var ts; var declarations = []; var definition; ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 144 /* Constructor */) || - (!selectConstructors && (d.kind === 213 /* FunctionDeclaration */ || d.kind === 143 /* MethodDeclaration */ || d.kind === 142 /* MethodSignature */))) { + if ((selectConstructors && d.kind === 146 /* Constructor */) || + (!selectConstructors && (d.kind === 217 /* FunctionDeclaration */ || d.kind === 145 /* MethodDeclaration */ || d.kind === 144 /* MethodSignature */))) { declarations.push(d); if (d.body) definition = d; @@ -47193,7 +50552,14 @@ var ts; // to jump to the implementation directly. if (symbol.flags & 8388608 /* Alias */) { var declaration = symbol.declarations[0]; - if (node.kind === 69 /* Identifier */ && node.parent === declaration) { + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from a named import. + // + if (node.kind === 69 /* Identifier */ && + (node.parent === declaration || + (declaration.kind === 230 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 229 /* NamedImports */))) { symbol = typeChecker.getAliasedSymbol(symbol); } } @@ -47202,16 +50568,16 @@ 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 === 246 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 250 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; } var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind = getSymbolKind(shorthandSymbol, node); - var shorthandSymbolName = typeChecker.symbolToString(shorthandSymbol); - var shorthandContainerName = typeChecker.symbolToString(symbol.parent, node); - return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName); }); + var shorthandSymbolKind_1 = getSymbolKind(shorthandSymbol, node); + var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); + var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); + return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } return getDefinitionFromSymbol(symbol, node); } @@ -47233,13 +50599,13 @@ var ts; return undefined; } if (type.flags & 16384 /* Union */) { - var result = []; + var result_3 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result, /*from*/ getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(/*to*/ result_3, /*from*/ getDefinitionFromSymbol(t.symbol, node)); } }); - return result; + return result_3; } if (!type.symbol) { return undefined; @@ -47249,10 +50615,10 @@ var ts; function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile = getCanonicalFileName(ts.normalizeSlashes(fileName)); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); // Get occurrences only supports reporting occurrences for the file queried. So // filter down to that list. - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile; }); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -47278,10 +50644,11 @@ var ts; function getSemanticDocumentHighlights(node) { if (node.kind === 69 /* Identifier */ || node.kind === 97 /* ThisKeyword */ || + node.kind === 163 /* ThisType */ || node.kind === 95 /* SuperKeyword */ || isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) { - var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings*/ false, /*findInComments*/ false); return convertReferencedSymbols(referencedSymbols); } return undefined; @@ -47331,75 +50698,75 @@ var ts; switch (node.kind) { case 88 /* IfKeyword */: case 80 /* ElseKeyword */: - if (hasKind(node.parent, 196 /* IfStatement */)) { + if (hasKind(node.parent, 200 /* IfStatement */)) { return getIfElseOccurrences(node.parent); } break; case 94 /* ReturnKeyword */: - if (hasKind(node.parent, 204 /* ReturnStatement */)) { + if (hasKind(node.parent, 208 /* ReturnStatement */)) { return getReturnOccurrences(node.parent); } break; case 98 /* ThrowKeyword */: - if (hasKind(node.parent, 208 /* ThrowStatement */)) { + if (hasKind(node.parent, 212 /* ThrowStatement */)) { return getThrowOccurrences(node.parent); } break; case 72 /* CatchKeyword */: - if (hasKind(parent(parent(node)), 209 /* TryStatement */)) { + if (hasKind(parent(parent(node)), 213 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; case 100 /* TryKeyword */: case 85 /* FinallyKeyword */: - if (hasKind(parent(node), 209 /* TryStatement */)) { + if (hasKind(parent(node), 213 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent); } break; case 96 /* SwitchKeyword */: - if (hasKind(node.parent, 206 /* SwitchStatement */)) { + if (hasKind(node.parent, 210 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 71 /* CaseKeyword */: case 77 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 206 /* SwitchStatement */)) { + if (hasKind(parent(parent(parent(node))), 210 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); } break; case 70 /* BreakKeyword */: case 75 /* ContinueKeyword */: - if (hasKind(node.parent, 203 /* BreakStatement */) || hasKind(node.parent, 202 /* ContinueStatement */)) { + if (hasKind(node.parent, 207 /* BreakStatement */) || hasKind(node.parent, 206 /* ContinueStatement */)) { return getBreakOrContinueStatementOccurrences(node.parent); } break; case 86 /* ForKeyword */: - if (hasKind(node.parent, 199 /* ForStatement */) || - hasKind(node.parent, 200 /* ForInStatement */) || - hasKind(node.parent, 201 /* ForOfStatement */)) { + if (hasKind(node.parent, 203 /* ForStatement */) || + hasKind(node.parent, 204 /* ForInStatement */) || + hasKind(node.parent, 205 /* ForOfStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 104 /* WhileKeyword */: case 79 /* DoKeyword */: - if (hasKind(node.parent, 198 /* WhileStatement */) || hasKind(node.parent, 197 /* DoStatement */)) { + if (hasKind(node.parent, 202 /* WhileStatement */) || hasKind(node.parent, 201 /* DoStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 121 /* ConstructorKeyword */: - if (hasKind(node.parent, 144 /* Constructor */)) { + if (hasKind(node.parent, 146 /* Constructor */)) { return getConstructorOccurrences(node.parent); } break; case 123 /* GetKeyword */: - case 129 /* SetKeyword */: - if (hasKind(node.parent, 145 /* GetAccessor */) || hasKind(node.parent, 146 /* SetAccessor */)) { + case 130 /* SetKeyword */: + if (hasKind(node.parent, 147 /* GetAccessor */) || hasKind(node.parent, 148 /* SetAccessor */)) { return getGetAndSetOccurrences(node.parent); } break; default: - if (ts.isModifier(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 193 /* VariableStatement */)) { + if (ts.isModifierKind(node.kind) && node.parent && + (ts.isDeclaration(node.parent) || node.parent.kind === 197 /* VariableStatement */)) { return getModifierOccurrences(node.kind, node.parent); } } @@ -47415,10 +50782,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 208 /* ThrowStatement */) { + if (node.kind === 212 /* ThrowStatement */) { statementAccumulator.push(node); } - else if (node.kind === 209 /* TryStatement */) { + else if (node.kind === 213 /* TryStatement */) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -47445,19 +50812,19 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_12 = child.parent; - if (ts.isFunctionBlock(parent_12) || parent_12.kind === 248 /* SourceFile */) { - return parent_12; + var parent_14 = child.parent; + if (ts.isFunctionBlock(parent_14) || parent_14.kind === 252 /* SourceFile */) { + return parent_14; } // 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_12.kind === 209 /* TryStatement */) { - var tryStatement = parent_12; + if (parent_14.kind === 213 /* TryStatement */) { + var tryStatement = parent_14; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_12; + child = parent_14; } return undefined; } @@ -47466,7 +50833,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 203 /* BreakStatement */ || node.kind === 202 /* ContinueStatement */) { + if (node.kind === 207 /* BreakStatement */ || node.kind === 206 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -47481,16 +50848,16 @@ var ts; function getBreakOrContinueOwner(statement) { for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { switch (node_2.kind) { - case 206 /* SwitchStatement */: - if (statement.kind === 202 /* ContinueStatement */) { + case 210 /* SwitchStatement */: + if (statement.kind === 206 /* ContinueStatement */) { continue; } // Fall through. - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: - case 197 /* DoStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 202 /* WhileStatement */: + case 201 /* DoStatement */: if (!statement.label || isLabeledBy(node_2, statement.label.text)) { return node_2; } @@ -47509,24 +50876,24 @@ 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 === 214 /* ClassDeclaration */ || - container.kind === 186 /* ClassExpression */ || - (declaration.kind === 138 /* Parameter */ && hasKind(container, 144 /* Constructor */)))) { + if (!(container.kind === 218 /* ClassDeclaration */ || + container.kind === 190 /* ClassExpression */ || + (declaration.kind === 140 /* Parameter */ && hasKind(container, 146 /* Constructor */)))) { return undefined; } } else if (modifier === 113 /* StaticKeyword */) { - if (!(container.kind === 214 /* ClassDeclaration */ || container.kind === 186 /* ClassExpression */)) { + if (!(container.kind === 218 /* ClassDeclaration */ || container.kind === 190 /* ClassExpression */)) { return undefined; } } else if (modifier === 82 /* ExportKeyword */ || modifier === 122 /* DeclareKeyword */) { - if (!(container.kind === 219 /* ModuleBlock */ || container.kind === 248 /* SourceFile */)) { + if (!(container.kind === 223 /* ModuleBlock */ || container.kind === 252 /* SourceFile */)) { return undefined; } } else if (modifier === 115 /* AbstractKeyword */) { - if (!(container.kind === 214 /* ClassDeclaration */ || declaration.kind === 214 /* ClassDeclaration */)) { + if (!(container.kind === 218 /* ClassDeclaration */ || declaration.kind === 218 /* ClassDeclaration */)) { return undefined; } } @@ -47538,8 +50905,8 @@ var ts; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { - case 219 /* ModuleBlock */: - case 248 /* SourceFile */: + case 223 /* ModuleBlock */: + case 252 /* SourceFile */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */) { nodes = declaration.members.concat(declaration); @@ -47548,17 +50915,17 @@ var ts; nodes = container.statements; } break; - case 144 /* Constructor */: + case 146 /* Constructor */: nodes = container.parameters.concat(container.parent.members); break; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: 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 & 56 /* AccessibilityModifier */) { + if (modifierFlag & 28 /* AccessibilityModifier */) { var constructor = ts.forEach(container.members, function (member) { - return member.kind === 144 /* Constructor */ && member; + return member.kind === 146 /* Constructor */ && member; }); if (constructor) { nodes = nodes.concat(constructor.parameters); @@ -47580,17 +50947,17 @@ var ts; function getFlagFromModifier(modifier) { switch (modifier) { case 112 /* PublicKeyword */: - return 8 /* Public */; + return 4 /* Public */; case 110 /* PrivateKeyword */: - return 16 /* Private */; + return 8 /* Private */; case 111 /* ProtectedKeyword */: - return 32 /* Protected */; + return 16 /* Protected */; case 113 /* StaticKeyword */: - return 64 /* Static */; + return 32 /* Static */; case 82 /* ExportKeyword */: - return 2 /* Export */; + return 1 /* Export */; case 122 /* DeclareKeyword */: - return 4 /* Ambient */; + return 2 /* Ambient */; case 115 /* AbstractKeyword */: return 128 /* Abstract */; default: @@ -47611,13 +50978,13 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 145 /* GetAccessor */); - tryPushAccessorKeyword(accessorDeclaration.symbol, 146 /* SetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 147 /* GetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 148 /* 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, 123 /* GetKeyword */, 129 /* SetKeyword */); }); + ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 123 /* GetKeyword */, 130 /* SetKeyword */); }); } } } @@ -47635,7 +51002,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86 /* ForKeyword */, 104 /* WhileKeyword */, 79 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 197 /* DoStatement */) { + if (loopNode.kind === 201 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { @@ -47656,13 +51023,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 206 /* SwitchStatement */: + case 210 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -47716,7 +51083,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, 192 /* Block */))) { + if (!(func && hasKind(func.body, 196 /* Block */))) { return undefined; } var keywords = []; @@ -47732,7 +51099,7 @@ var ts; function getIfElseOccurrences(ifStatement) { var keywords = []; // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 196 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 200 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. @@ -47745,7 +51112,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 196 /* IfStatement */)) { + if (!hasKind(ifStatement.elseStatement, 200 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; @@ -47821,11 +51188,11 @@ var ts; return convertReferences(referencedSymbols); } function getReferencesAtPosition(fileName, position) { - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); return convertReferences(referencedSymbols); } function findReferences(fileName, position) { - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); // Only include referenced symbols that have a valid definition. return ts.filter(referencedSymbols, function (rs) { return !!rs.definition; }); } @@ -47838,8 +51205,8 @@ var ts; } if (node.kind !== 69 /* Identifier */ && // TODO (drosen): This should be enabled in a later release - currently breaks rename. - //node.kind !== SyntaxKind.ThisKeyword && - //node.kind !== SyntaxKind.SuperKeyword && + // node.kind !== SyntaxKind.ThisKeyword && + // node.kind !== SyntaxKind.SuperKeyword && !isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && !isNameOfExternalModuleImportOrDeclaration(node)) { return undefined; @@ -47862,7 +51229,7 @@ var ts; return getLabelReferencesInNode(node.parent, node); } } - if (node.kind === 97 /* ThisKeyword */) { + if (node.kind === 97 /* ThisKeyword */ || node.kind === 163 /* ThisType */) { return getReferencesForThisKeyword(node, sourceFiles); } if (node.kind === 95 /* SuperKeyword */) { @@ -47896,11 +51263,11 @@ var ts; } else { var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName)) { + if (ts.lookUp(nameTable, internedName) !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -47923,10 +51290,8 @@ var ts; textSpan: ts.createTextSpan(declarations[0].getStart(), 0) }; } - function isImportOrExportSpecifierImportSymbol(symbol) { - return (symbol.flags & 8388608 /* Alias */) && ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 230 /* ExportSpecifier */; - }); + function isImportSpecifierSymbol(symbol) { + return (symbol.flags & 8388608 /* Alias */) && !!ts.getDeclarationOfKind(symbol, 230 /* ImportSpecifier */); } function getInternedName(symbol, location, declarations) { // If this is an export or import specifier it could have been renamed using the 'as' syntax. @@ -47952,18 +51317,18 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 173 /* FunctionExpression */ || valueDeclaration.kind === 186 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 177 /* FunctionExpression */ || valueDeclaration.kind === 190 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16 /* Private */) ? d : undefined; }); + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8 /* Private */) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 218 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. - // So consider it visibile outside its declaration scope. + // So consider it visible outside its declaration scope. if (symbol.flags & 8388608 /* Alias */) { return undefined; } @@ -47972,11 +51337,11 @@ var ts; if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } - var scope = undefined; + var scope; var declarations = symbol.getDeclarations(); if (declarations) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; @@ -47985,7 +51350,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + if (container.kind === 252 /* 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; @@ -48084,7 +51449,7 @@ var ts; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, container.getStart(), container.getEnd()); if (possiblePositions.length) { // Build the set of symbols to search for, initially it has only the current symbol - var searchSymbols = populateSearchSymbolSet(searchSymbol, searchLocation); + var searchSymbols_1 = populateSearchSymbolSet(searchSymbol, searchLocation); ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -48116,12 +51481,12 @@ var ts; if (referenceSymbol) { var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); - var relatedSymbol = getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation); + var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation); if (relatedSymbol) { var referencedSymbol = getReferencedSymbol(relatedSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceLocation)); } - else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols.indexOf(shorthandValueSymbol) >= 0) { + else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); } @@ -48151,20 +51516,20 @@ var ts; } } function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword, /*includeFunctions*/ false); + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); if (!searchSpaceNode) { return undefined; } // Whether 'super' occurs in a static context within a class. - var staticFlag = 64 /* Static */; + var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -48180,11 +51545,11 @@ var ts; if (!node || node.kind !== 95 /* SuperKeyword */) { return; } - var container = ts.getSuperContainer(node, /*includeFunctions*/ false); + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); // If we have a 'super' container, we must have an enclosing class. // Now make sure the owning class is the same as the search-space // and has the same static qualifier as the original 'super's owner. - if (container && (64 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + if (container && (32 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { references.push(getReferenceEntryFromNode(node)); } }); @@ -48194,29 +51559,29 @@ var ts; function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. - var staticFlag = 64 /* Static */; + var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // fall through - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 248 /* SourceFile */: + case 252 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: + case 177 /* 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. @@ -48225,7 +51590,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 248 /* SourceFile */) { + if (searchSpaceNode.kind === 252 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -48251,33 +51616,33 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 97 /* ThisKeyword */) { + if (!node || (node.kind !== 97 /* ThisKeyword */ && node.kind !== 163 /* ThisType */)) { return; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 218 /* 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 & 64 /* Static */) === staticFlag) { + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 32 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 248 /* SourceFile */: - if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + case 252 /* SourceFile */: + if (container.kind === 252 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -48288,10 +51653,18 @@ var ts; function populateSearchSymbolSet(symbol, location) { // The search set contains at least the current symbol var result = [symbol]; - // If the symbol is an alias, add what it alaises to the list - if (isImportOrExportSpecifierImportSymbol(symbol)) { + // If the symbol is an alias, add what it aliases to the list + if (isImportSpecifierSymbol(symbol)) { result.push(typeChecker.getAliasedSymbol(symbol)); } + // For export specifiers, the exported name can be referring to a local symbol, e.g.: + // import {a} from "mod"; + // export {a as somethingElse} + // We want the *local* declaration of 'a' as declared in the import, + // *not* as declared within "mod" (or farther) + if (location.parent.kind === 234 /* ExportSpecifier */) { + result.push(typeChecker.getExportSpecifierLocalTargetSymbol(location.parent)); + } // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set @@ -48304,8 +51677,8 @@ var ts; * property name and variable declaration of the identifier. * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service * should show both 'name' in 'obj' and 'name' in variable declaration - * let name = "Foo"; - * let obj = { name }; + * const name = "Foo"; + * const obj = { name }; * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. @@ -48315,6 +51688,14 @@ var ts; result.push(shorthandValueSymbol); } } + // If the symbol.valueDeclaration is a property parameter declaration, + // we should include both parameter declaration symbol and property declaration symbol + // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. + // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 140 /* Parameter */ && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } // If this is a union property, add all the symbols from all its source symbols in all unioned types. // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { @@ -48323,19 +51704,44 @@ var ts; } // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ {}); } }); return result; } - function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { - if (symbol && symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { + if (!symbol) { + return; + } + // If the current symbol is the same as the previous-iteration symbol, we can just return the symbol that has already been visited + // This is particularly important for the following cases, so that we do not infinitely visit the same symbol. + // For example: + // interface C extends C { + // /*findRef*/propName: string; + // } + // The first time getPropertySymbolsFromBaseTypes is called when finding-all-references at propName, + // the symbol argument will be the symbol of an interface "C" and previousIterationSymbol is undefined, + // the function will add any found symbol of the property-name, then its sub-routine will call + // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already + // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. + if (ts.hasProperty(previousIterationSymbolsCache, symbol.name)) { + return; + } + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { ts.forEach(symbol.getDeclarations(), function (declaration) { - if (declaration.kind === 214 /* ClassDeclaration */) { + if (declaration.kind === 218 /* ClassDeclaration */) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 215 /* InterfaceDeclaration */) { + else if (declaration.kind === 219 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -48350,7 +51756,8 @@ var ts; result.push(propertySymbol); } // Visit the typeReference as well to see if it directly or indirectly use that property - getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result); + previousIterationSymbolsCache[symbol.name] = symbol; + getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); } } } @@ -48361,12 +51768,22 @@ var ts; } // If the reference symbol is an alias, check if what it is aliasing is one of the search // symbols. - if (isImportOrExportSpecifierImportSymbol(referenceSymbol)) { + if (isImportSpecifierSymbol(referenceSymbol)) { var aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol); if (searchSymbols.indexOf(aliasedSymbol) >= 0) { return aliasedSymbol; } } + // For export specifiers, it can be a local symbol, e.g. + // import {a} from "mod"; + // export {a as somethingElse} + // We want the local target of the export (i.e. the import symbol) and not the final target (i.e. "mod".a) + if (referenceLocation.parent.kind === 234 /* ExportSpecifier */) { + var aliasedSymbol = typeChecker.getExportSpecifierLocalTargetSymbol(referenceLocation.parent); + if (searchSymbols.indexOf(aliasedSymbol) >= 0) { + return aliasedSymbol; + } + } // If the reference location is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this symbol to // compare to our searchSymbol @@ -48385,9 +51802,9 @@ var ts; // Finally, try all properties with the same name in any type the containing type extended or implemented, and // see if any is in the list if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - var result_3 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3); - return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, /*previousIterationSymbolsCache*/ {}); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -48396,28 +51813,28 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_35 = node.text; + var name_36 = 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_35); + var unionProperty = contextualType.getProperty(name_36); if (unionProperty) { return [unionProperty]; } else { - var result_4 = []; + var result_5 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_35); + var symbol = t.getProperty(name_36); if (symbol) { - result_4.push(symbol); + result_5.push(symbol); } }); - return result_4; + return result_5; } } else { - var symbol_1 = contextualType.getProperty(name_35); + var symbol_1 = contextualType.getProperty(name_36); if (symbol_1) { return [symbol_1]; } @@ -48435,7 +51852,7 @@ var ts; */ function getIntersectingMeaningFromDeclarations(meaning, declarations) { if (declarations) { - var lastIterationMeaning; + var lastIterationMeaning = void 0; do { // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module @@ -48443,8 +51860,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var declarationMeaning = getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -48475,10 +51892,10 @@ var ts; } var parent = node.parent; if (parent) { - if (parent.kind === 180 /* PostfixUnaryExpression */ || parent.kind === 179 /* PrefixUnaryExpression */) { + if (parent.kind === 184 /* PostfixUnaryExpression */ || parent.kind === 183 /* PrefixUnaryExpression */) { return true; } - else if (parent.kind === 181 /* BinaryExpression */ && parent.left === node) { + else if (parent.kind === 185 /* BinaryExpression */ && parent.left === node) { var operator = parent.operatorToken.kind; return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; } @@ -48490,9 +51907,6 @@ var ts; synchronizeHostData(); return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); } - function containErrors(diagnostics) { - return ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); - } function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -48512,34 +51926,34 @@ var ts; } function getMeaningFromDeclaration(node) { switch (node.kind) { - case 138 /* Parameter */: - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 246 /* ShorthandPropertyAssignment */: - case 247 /* EnumMember */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 244 /* CatchClause */: + case 140 /* Parameter */: + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 249 /* PropertyAssignment */: + case 250 /* ShorthandPropertyAssignment */: + case 251 /* EnumMember */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 248 /* CatchClause */: return 1 /* Value */; - case 137 /* TypeParameter */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 155 /* TypeLiteral */: + case 139 /* TypeParameter */: + case 219 /* InterfaceDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 157 /* TypeLiteral */: return 2 /* Type */; - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 218 /* ModuleDeclaration */: - if (node.name.kind === 9 /* StringLiteral */) { + case 222 /* ModuleDeclaration */: + if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { @@ -48548,15 +51962,15 @@ var ts; else { return 4 /* Namespace */; } - case 225 /* NamedImports */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 222 /* ImportDeclaration */: - case 227 /* ExportAssignment */: - case 228 /* ExportDeclaration */: + case 229 /* NamedImports */: + case 230 /* ImportSpecifier */: + case 225 /* ImportEqualsDeclaration */: + case 226 /* ImportDeclaration */: + case 231 /* ExportAssignment */: + case 232 /* ExportDeclaration */: return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; // An external module can be a Value - case 248 /* SourceFile */: + case 252 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; @@ -48565,9 +51979,10 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 151 /* TypeReference */ || - (node.parent.kind === 188 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node); + return node.parent.kind === 153 /* TypeReference */ || + (node.parent.kind === 192 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node)) || + node.kind === 163 /* ThisType */; } function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); @@ -48575,32 +51990,32 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 166 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 166 /* PropertyAccessExpression */) { + if (root.parent.kind === 170 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 170 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 188 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 243 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 192 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 247 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 214 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || - (decl.kind === 215 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); + return (decl.kind === 218 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || + (decl.kind === 219 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); } return false; } function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 135 /* QualifiedName */) { - while (root.parent && root.parent.kind === 135 /* QualifiedName */) { + if (root.parent.kind === 137 /* QualifiedName */) { + while (root.parent && root.parent.kind === 137 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 151 /* TypeReference */ && !isLastClause; + return root.parent.kind === 153 /* TypeReference */ && !isLastClause; } function isInRightSideOfImport(node) { - while (node.parent.kind === 135 /* QualifiedName */) { + while (node.parent.kind === 137 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -48610,15 +52025,15 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (node.parent.kind === 135 /* QualifiedName */ && + if (node.parent.kind === 137 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 221 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 225 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function getMeaningFromLocation(node) { - if (node.parent.kind === 227 /* ExportAssignment */) { + if (node.parent.kind === 231 /* ExportAssignment */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } else if (isInRightSideOfImport(node)) { @@ -48658,14 +52073,16 @@ var ts; return; } switch (node.kind) { - case 166 /* PropertyAccessExpression */: - case 135 /* QualifiedName */: + case 170 /* PropertyAccessExpression */: + case 137 /* QualifiedName */: case 9 /* StringLiteral */: + case 164 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: case 95 /* SuperKeyword */: case 97 /* ThisKeyword */: + case 163 /* ThisType */: case 69 /* Identifier */: break; // Cant create the text span @@ -48682,7 +52099,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 === 218 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 222 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -48706,7 +52123,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -48723,10 +52140,10 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 222 /* ModuleDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 217 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -48780,7 +52197,7 @@ var ts; */ function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 218 /* ModuleDeclaration */ && + return declaration.kind === 222 /* ModuleDeclaration */ && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; }); } @@ -48828,6 +52245,12 @@ var ts; case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName; case 17 /* parameterName */: return ClassificationTypeNames.parameterName; case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName; + case 19 /* jsxOpenTagName */: return ClassificationTypeNames.jsxOpenTagName; + case 20 /* jsxCloseTagName */: return ClassificationTypeNames.jsxCloseTagName; + case 21 /* jsxSelfClosingTagName */: return ClassificationTypeNames.jsxSelfClosingTagName; + case 22 /* jsxAttribute */: return ClassificationTypeNames.jsxAttribute; + case 23 /* jsxText */: return ClassificationTypeNames.jsxText; + case 24 /* jsxAttributeStringLiteralValue */: return ClassificationTypeNames.jsxAttributeStringLiteralValue; } } function convertClassifications(classifications) { @@ -48851,8 +52274,8 @@ var ts; var spanStart = span.start; var spanLength = span.length; // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; @@ -48935,16 +52358,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); pos = tag.tagName.end; switch (tag.kind) { - case 267 /* JSDocParameterTag */: + case 271 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 270 /* JSDocTemplateTag */: + case 274 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 269 /* JSDocTypeTag */: + case 273 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 268 /* JSDocReturnTag */: + case 272 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -48981,7 +52404,8 @@ var ts; function classifyDisabledMergeCode(text, start, end) { // Classify the line that the ======= marker is on as a comment. Then just lex // all further tokens and add them to the result. - for (var i = start; i < end; i++) { + var i; + for (i = start; i < end; i++) { if (ts.isLineBreak(text.charCodeAt(i))) { break; } @@ -49001,19 +52425,53 @@ var ts; pushClassification(start, end - start, type); } } - function classifyToken(token) { - if (ts.nodeIsMissing(token)) { - return; + /** + * Returns true if node should be treated as classified and no further processing is required. + * False will mean that node is not classified and traverse routine should recurse into node contents. + */ + function tryClassifyNode(node) { + if (ts.nodeIsMissing(node)) { + return true; } - var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); - var tokenWidth = token.end - tokenStart; + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 240 /* JsxText */ && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 240 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { - var type = classifyTokenType(token.kind, token); + var type = classifiedElementName || classifyTokenType(node.kind, node); if (type) { pushClassification(tokenStart, tokenWidth, type); } } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 239 /* JsxOpeningElement */: + if (token.parent.tagName === token) { + return 19 /* jsxOpenTagName */; + } + break; + case 241 /* JsxClosingElement */: + if (token.parent.tagName === token) { + return 20 /* jsxCloseTagName */; + } + break; + case 238 /* JsxSelfClosingElement */: + if (token.parent.tagName === token) { + return 21 /* jsxSelfClosingTagName */; + } + break; + case 242 /* JsxAttribute */: + if (token.parent.name === token) { + return 22 /* jsxAttribute */; + } + break; + } + return undefined; } // for accurate classification, the actual token should be passed in. however, for // cases like 'disabled merge code' classification, we just get the token kind and @@ -49035,16 +52493,17 @@ var ts; if (token) { if (tokenKind === 56 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 211 /* VariableDeclaration */ || - token.parent.kind === 141 /* PropertyDeclaration */ || - token.parent.kind === 138 /* Parameter */) { + if (token.parent.kind === 215 /* VariableDeclaration */ || + token.parent.kind === 143 /* PropertyDeclaration */ || + token.parent.kind === 140 /* Parameter */ || + token.parent.kind === 242 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 181 /* BinaryExpression */ || - token.parent.kind === 179 /* PrefixUnaryExpression */ || - token.parent.kind === 180 /* PostfixUnaryExpression */ || - token.parent.kind === 182 /* ConditionalExpression */) { + if (token.parent.kind === 185 /* BinaryExpression */ || + token.parent.kind === 183 /* PrefixUnaryExpression */ || + token.parent.kind === 184 /* PostfixUnaryExpression */ || + token.parent.kind === 186 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -49053,8 +52512,8 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { - return 6 /* stringLiteral */; + else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 164 /* StringLiteralType */) { + return token.parent.kind === 242 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -49064,35 +52523,38 @@ var ts; // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } + else if (tokenKind === 240 /* JsxText */) { + return 23 /* jsxText */; + } else if (tokenKind === 69 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 137 /* TypeParameter */: + case 139 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 138 /* Parameter */: + case 140 /* Parameter */: if (token.parent.name === token) { return 17 /* parameterName */; } @@ -49112,10 +52574,7 @@ var ts; 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); - } - else { + if (!tryClassifyNode(child)) { // Recurse into our child nodes. processElement(child); } @@ -49221,7 +52680,6 @@ var ts; * be performed. */ function getDocCommentTemplateAtPosition(fileName, position) { - var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Check if in a context where we don't want to perform any insertion if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { @@ -49240,19 +52698,19 @@ var ts; var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 144 /* Constructor */: - case 214 /* ClassDeclaration */: - case 193 /* VariableStatement */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 146 /* Constructor */: + case 218 /* ClassDeclaration */: + case 197 /* VariableStatement */: break findOwner; - case 248 /* SourceFile */: + case 252 /* SourceFile */: return undefined; - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - if (commentOwner.parent.kind === 218 /* ModuleDeclaration */) { + if (commentOwner.parent.kind === 222 /* ModuleDeclaration */) { return undefined; } break findOwner; @@ -49265,8 +52723,7 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); - // TODO: call a helper method instead once PR #4133 gets merged in. - var newLine = host.getNewLine ? host.getNewLine() : "\r\n"; + var newLine = ts.getNewLineOrDefaultFromHost(host); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; @@ -49294,7 +52751,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 193 /* VariableStatement */) { + if (commentOwner.kind === 197 /* VariableStatement */) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -49312,17 +52769,17 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 172 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 176 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return rightHandSide.parameters; - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 144 /* Constructor */) { + if (member.kind === 146 /* Constructor */) { return member.parameters; } } @@ -49344,7 +52801,7 @@ var ts; var result = []; if (descriptors.length > 0) { var regExp = getTodoCommentsRegExp(); - var matchArray; + var matchArray = void 0; while (matchArray = regExp.exec(fileContents)) { cancellationToken.throwIfCancellationRequested(); // If we got a match, here is what the match array will look like. Say the source text is: @@ -49415,11 +52872,11 @@ var ts; // comment portion. var singleLineCommentStart = /(?:\/\/+\s*)/.source; var multiLineCommentStart = /(?:\/\*+\s*)/.source; - var anyNumberOfSpacesAndAsterixesAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; // Match any of the above three TODO comment start regexps. // Note that the outermost group *is* a capture group. We want to capture the preamble // so that we can determine the starting position of the TODO comment match. - var preamble = "(" + anyNumberOfSpacesAndAsterixesAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; // Takes the descriptors and forms a regexp that matches them as if they were literals. // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: // @@ -49468,12 +52925,17 @@ var ts; if (declarations && declarations.length > 0) { // Disallow rename for elements that are defined in the standard TypeScript library. var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); if (defaultLibFileName) { - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var current = declarations_10[_i]; - var sourceFile_2 = current.getSourceFile(); - var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); - if (sourceFile_2 && getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var current = declarations_11[_i]; + var sourceFile_3 = current.getSourceFile(); + // TODO (drosen): When is there no source file? + if (!sourceFile_3) { + continue; + } + var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_3.fileName)); + if (canonicalName === canonicalDefaultLibName) { return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); } } @@ -49483,10 +52945,10 @@ var ts; if (kind) { return { canRename: true, - localizedErrorMessage: undefined, - displayName: displayName, - fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kind: kind, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kindModifiers: getSymbolModifiers(symbol), triggerSpan: ts.createTextSpan(node.getStart(), node.getWidth()) }; @@ -49562,7 +53024,7 @@ var ts; function walk(node) { switch (node.kind) { case 69 /* Identifier */: - nameTable[node.text] = node.text; + nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; break; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -49571,9 +53033,9 @@ 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 === 232 /* ExternalModuleReference */ || + node.parent.kind === 236 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node)) { - nameTable[node.text] = node.text; + nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; } break; default: @@ -49584,7 +53046,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 167 /* ElementAccessExpression */ && + node.parent.kind === 171 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /// Classifier @@ -49632,7 +53094,7 @@ var ts; function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 123 /* GetKeyword */ || - keyword2 === 129 /* SetKeyword */ || + keyword2 === 130 /* SetKeyword */ || keyword2 === 121 /* ConstructorKeyword */ || keyword2 === 113 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". @@ -49713,7 +53175,7 @@ var ts; // (and a newline). That way when we lex we'll think we're still in a multiline comment. switch (lexState) { case 3 /* InDoubleQuoteStringLiteral */: - text = '"\\\n' + text; + text = "\"\\\n" + text; offset = 3; break; case 2 /* InSingleQuoteStringLiteral */: @@ -49791,10 +53253,10 @@ var ts; angleBracketStack--; } else if (token === 117 /* AnyKeyword */ || - token === 130 /* StringKeyword */ || - token === 128 /* NumberKeyword */ || + token === 131 /* StringKeyword */ || + token === 129 /* NumberKeyword */ || token === 120 /* BooleanKeyword */ || - token === 131 /* SymbolKeyword */) { + token === 132 /* 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, @@ -49843,7 +53305,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */ || token === 164 /* StringLiteralType */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { @@ -49966,7 +53428,7 @@ var ts; } } function isKeyword(token) { - return token >= 70 /* FirstKeyword */ && token <= 134 /* LastKeyword */; + return token >= 70 /* FirstKeyword */ && token <= 136 /* LastKeyword */; } function classFromKind(token) { if (isKeyword(token)) { @@ -49982,6 +53444,7 @@ var ts; case 8 /* NumericLiteral */: return 4 /* numericLiteral */; case 9 /* StringLiteral */: + case 164 /* StringLiteralType */: return 6 /* stringLiteral */; case 10 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; @@ -50021,18 +53484,8 @@ var ts; ts.getDefaultLibFilePath = getDefaultLibFilePath; function initializeServices() { ts.objectAllocator = { - getNodeConstructor: function (kind) { - function Node(pos, end) { - this.pos = pos; - this.end = end; - this.flags = 0 /* None */; - this.parent = undefined; - } - var proto = kind === 248 /* SourceFile */ ? new SourceFileObject() : new NodeObject(); - proto.kind = kind; - Node.prototype = proto; - return Node; - }, + getNodeConstructor: function () { return NodeObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, getSignatureConstructor: function () { return SignatureObject; } @@ -50053,12 +53506,12 @@ var ts; */ function spanInSourceFileAtLocation(sourceFile, position) { // Cannot set breakpoint in dts file - if (sourceFile.flags & 4096 /* DeclarationFile */) { + if (sourceFile.isDeclarationFile) { return undefined; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) { + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line // eg: let x =10; |--- cursor is here // let y = 10; @@ -50077,14 +53530,23 @@ var ts; // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); + } + function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent)); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { - if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { return spanInNode(node); } return spanInNode(otherwiseOnNode); } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } @@ -50093,126 +53555,114 @@ var ts; } function spanInNode(node) { if (node) { - if (ts.isExpression(node)) { - if (node.parent.kind === 197 /* DoStatement */) { - // Set span as if on while keyword - return spanInPreviousNode(node); - } - if (node.parent.kind === 199 /* ForStatement */) { - // For now lets set the span on this expression, fix it later - return textSpan(node); - } - if (node.parent.kind === 181 /* BinaryExpression */ && node.parent.operatorToken.kind === 24 /* CommaToken */) { - // if this is comma expression, the breakpoint is possible in this expression - return textSpan(node); - } - if (node.parent.kind === 174 /* 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 193 /* VariableStatement */: + case 197 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 211 /* VariableDeclaration */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 215 /* VariableDeclaration */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return spanInVariableDeclaration(node); - case 138 /* Parameter */: + case 140 /* Parameter */: return spanInParameterDeclaration(node); - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 144 /* Constructor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 146 /* Constructor */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 192 /* Block */: + case 196 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // Fall through - case 219 /* ModuleBlock */: + case 223 /* ModuleBlock */: return spanInBlock(node); - case 244 /* CatchClause */: + case 248 /* CatchClause */: return spanInBlock(node.block); - case 195 /* ExpressionStatement */: + case 199 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 204 /* ReturnStatement */: + case 208 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 198 /* WhileStatement */: + case 202 /* WhileStatement */: // Span on while(...) - return textSpan(node, ts.findNextToken(node.expression, node)); - case 197 /* DoStatement */: + return textSpanEndingAtNextToken(node, node.expression); + case 201 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 210 /* DebuggerStatement */: + case 214 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 196 /* IfStatement */: + case 200 /* IfStatement */: // set on if(..) span - return textSpan(node, ts.findNextToken(node.expression, node)); - case 207 /* LabeledStatement */: + return textSpanEndingAtNextToken(node, node.expression); + case 211 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: + case 207 /* BreakStatement */: + case 206 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 199 /* ForStatement */: + case 203 /* ForStatement */: return spanInForStatement(node); - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - // span on for (a in ...) - return textSpan(node, ts.findNextToken(node.expression, node)); - case 206 /* SwitchStatement */: + case 204 /* ForInStatement */: + // span of for (a in ...) + return textSpanEndingAtNextToken(node, node.expression); + case 205 /* ForOfStatement */: + // span in initializer + return spanInInitializerOfForLike(node); + case 210 /* SwitchStatement */: // span on switch(...) - return textSpan(node, ts.findNextToken(node.expression, node)); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + return textSpanEndingAtNextToken(node, node.expression); + case 245 /* CaseClause */: + case 246 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 209 /* TryStatement */: + case 213 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 208 /* ThrowStatement */: + case 212 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 251 /* EnumMember */: + case 167 /* BindingElement */: // span on complete node return textSpan(node); - case 205 /* WithStatement */: + case 209 /* WithStatement */: // span in statement return spanInNode(node.statement); + case 141 /* Decorator */: + return spanInNodeArray(node.parent.decorators); + case 165 /* ObjectBindingPattern */: + case 166 /* ArrayBindingPattern */: + return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 219 /* InterfaceDeclaration */: + case 220 /* TypeAliasDeclaration */: return undefined; // Tokens: case 23 /* SemicolonToken */: @@ -50224,6 +53674,8 @@ var ts; return spanInOpenBraceToken(node); case 16 /* CloseBraceToken */: return spanInCloseBraceToken(node); + case 20 /* CloseBracketToken */: + return spanInCloseBracketToken(node); case 17 /* OpenParenToken */: return spanInOpenParenToken(node); case 18 /* CloseParenToken */: @@ -50240,67 +53692,155 @@ var ts; case 72 /* CatchKeyword */: case 85 /* FinallyKeyword */: return spanInNextNode(node); + case 136 /* OfKeyword */: + return spanInOfKeyword(node); default: + // Destructuring pattern in destructuring assignment + // [a, b, c] of + // [a, b, c] = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); + } + // Set breakpoint on identifier element of destructuring pattern + // a or ...c or d: x from + // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + if ((node.kind === 69 /* Identifier */ || + node.kind == 189 /* SpreadElementExpression */ || + node.kind === 249 /* PropertyAssignment */ || + node.kind === 250 /* ShorthandPropertyAssignment */) && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + return textSpan(node); + } + if (node.kind === 185 /* BinaryExpression */) { + var binaryExpression = node; + // Set breakpoint in destructuring pattern if its destructuring assignment + // [a, b, c] or {a, b, c} of + // [a, b, c] = expression or + // {a, b, c} = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); + } + if (binaryExpression.operatorToken.kind === 56 /* EqualsToken */ && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { + // Set breakpoint on assignment expression element of destructuring pattern + // a = expression of + // [a = expression, b, c] = someExpression or + // { a = expression, b, c } = someExpression + return textSpan(node); + } + if (binaryExpression.operatorToken.kind === 24 /* CommaToken */) { + return spanInNode(binaryExpression.left); + } + } + if (ts.isExpression(node)) { + switch (node.parent.kind) { + case 201 /* DoStatement */: + // Set span as if on while keyword + return spanInPreviousNode(node); + case 141 /* Decorator */: + // Set breakpoint on the decorator emit + return spanInNode(node.parent); + case 203 /* ForStatement */: + case 205 /* ForOfStatement */: + return textSpan(node); + case 185 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 24 /* CommaToken */) { + // if this is comma expression, the breakpoint is possible in this expression + return textSpan(node); + } + break; + case 178 /* ArrowFunction */: + if (node.parent.body === node) { + // If this is body of arrow function, it is allowed to have the breakpoint + return textSpan(node); + } + break; + } + } // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 245 /* PropertyAssignment */ && node.parent.name === node) { + if (node.parent.kind === 249 /* PropertyAssignment */ && + node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand - if (node.parent.kind === 171 /* TypeAssertionExpression */ && node.parent.type === node) { - return spanInNode(node.parent.expression); + if (node.parent.kind === 175 /* TypeAssertionExpression */ && node.parent.type === node) { + return spanInNextNode(node.parent.type); } // return type of function go to previous token if (ts.isFunctionLike(node.parent) && node.parent.type === node) { return spanInPreviousNode(node); } + // initializer of variable/parameter declaration go to previous node + if ((node.parent.kind === 215 /* VariableDeclaration */ || + node.parent.kind === 140 /* Parameter */)) { + var paramOrVarDecl = node.parent; + if (paramOrVarDecl.initializer === node || + paramOrVarDecl.type === node || + ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + } + if (node.parent.kind === 185 /* BinaryExpression */) { + var binaryExpression = node.parent; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && + (binaryExpression.right === node || + binaryExpression.operatorToken === node)) { + // If initializer of destructuring assignment move to previous token + return spanInPreviousNode(node); + } + } // Default go to parent to set the breakpoint return spanInNode(node.parent); } } + function textSpanFromVariableDeclaration(variableDeclaration) { + var declarations = variableDeclaration.parent.declarations; + if (declarations && declarations[0] === variableDeclaration) { + // First declaration - include let keyword + return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); + } + else { + // Span only on this declaration + return textSpan(variableDeclaration); + } + } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 200 /* ForInStatement */ || - variableDeclaration.parent.parent.kind === 201 /* ForOfStatement */) { + if (variableDeclaration.parent.parent.kind === 204 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.parent.kind === 193 /* VariableStatement */; - var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 199 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); - var declarations = isParentVariableStatement - ? variableDeclaration.parent.parent.declarationList.declarations - : isDeclarationOfForStatement - ? variableDeclaration.parent.parent.initializer.declarations - : undefined; - // Breakpoint is possible in variableDeclaration only if there is initialization - if (variableDeclaration.initializer || (variableDeclaration.flags & 2 /* Export */)) { - if (declarations && declarations[0] === variableDeclaration) { - if (isParentVariableStatement) { - // First declaration - include let keyword - return textSpan(variableDeclaration.parent, variableDeclaration); - } - else { - ts.Debug.assert(isDeclarationOfForStatement); - // Include let keyword from for statement declarations in the span - return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); - } - } - else { - // Span only on this declaration - return textSpan(variableDeclaration); - } + // If this is a destructuring pattern set breakpoint in binding pattern + if (ts.isBindingPattern(variableDeclaration.name)) { + return spanInBindingPattern(variableDeclaration.name); } - else if (declarations && declarations[0] !== variableDeclaration) { + // Breakpoint is possible in variableDeclaration only if there is initialization + // or its declaration from 'for of' + if (variableDeclaration.initializer || + (variableDeclaration.flags & 1 /* Export */) || + variableDeclaration.parent.parent.kind === 205 /* ForOfStatement */) { + return textSpanFromVariableDeclaration(variableDeclaration); + } + var declarations = variableDeclaration.parent.declarations; + if (declarations && declarations[0] !== variableDeclaration) { // If we cant set breakpoint on this declaration, set it on previous one - var indexOfCurrentDeclaration = ts.indexOf(declarations, variableDeclaration); - return spanInVariableDeclaration(declarations[indexOfCurrentDeclaration - 1]); + // Because the variable declaration may be binding pattern and + // we would like to set breakpoint in last binding element if thats the case, + // use preceding token instead + return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); } } function canHaveSpanInParameterDeclaration(parameter) { // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - !!(parameter.flags & 8 /* Public */) || !!(parameter.flags & 16 /* Private */); + !!(parameter.flags & 4 /* Public */) || !!(parameter.flags & 8 /* Private */); } function spanInParameterDeclaration(parameter) { - if (canHaveSpanInParameterDeclaration(parameter)) { + if (ts.isBindingPattern(parameter.name)) { + // set breakpoint in binding pattern + return spanInBindingPattern(parameter.name); + } + else if (canHaveSpanInParameterDeclaration(parameter)) { return textSpan(parameter); } else { @@ -50317,8 +53857,8 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 2 /* Export */) || - (functionDeclaration.parent.kind === 214 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); + return !!(functionDeclaration.flags & 1 /* Export */) || + (functionDeclaration.parent.kind === 218 /* ClassDeclaration */ && functionDeclaration.kind !== 146 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -50341,34 +53881,39 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement - case 198 /* WhileStatement */: - case 196 /* IfStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 202 /* WhileStatement */: + case 200 /* IfStatement */: + case 204 /* ForInStatement */: 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 199 /* ForStatement */: + case 203 /* ForStatement */: + case 205 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } + function spanInInitializerOfForLike(forLikeStaement) { + if (forLikeStaement.initializer.kind === 216 /* VariableDeclarationList */) { + // declaration list, set breakpoint in first declaration + var variableDeclarationList = forLikeStaement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + // Expression - set breakpoint in it + return spanInNode(forLikeStaement.initializer); + } + } function spanInForStatement(forStatement) { if (forStatement.initializer) { - if (forStatement.initializer.kind === 212 /* VariableDeclarationList */) { - var variableDeclarationList = forStatement.initializer; - if (variableDeclarationList.declarations.length > 0) { - return spanInNode(variableDeclarationList.declarations[0]); - } - } - else { - return spanInNode(forStatement.initializer); - } + return spanInInitializerOfForLike(forStatement); } if (forStatement.condition) { return textSpan(forStatement.condition); @@ -50377,16 +53922,44 @@ var ts; return textSpan(forStatement.incrementor); } } + function spanInBindingPattern(bindingPattern) { + // Set breakpoint in first binding element + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 191 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Empty binding pattern of binding element, set breakpoint on binding element + if (bindingPattern.parent.kind === 167 /* BindingElement */) { + return textSpan(bindingPattern.parent); + } + // Variable declaration is used as the span + return textSpanFromVariableDeclaration(bindingPattern.parent); + } + function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { + ts.Debug.assert(node.kind !== 166 /* ArrayBindingPattern */ && node.kind !== 165 /* ObjectBindingPattern */); + var elements = node.kind === 168 /* ArrayLiteralExpression */ ? + node.elements : + node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 191 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Could be ArrayLiteral from destructuring assignment or + // just nested element in another destructuring assignment + // set breakpoint on assignment when parent is destructuring assignment + // Otherwise set breakpoint for this element + return textSpan(node.parent.kind === 185 /* BinaryExpression */ ? node.parent : node); + } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 220 /* CaseBlock */: + case 224 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -50394,24 +53967,24 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 219 /* ModuleBlock */: + case 223 /* ModuleBlock */: // If this is not instantiated module block no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } - case 217 /* EnumDeclaration */: - case 214 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 218 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 192 /* Block */: + case 196 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // fall through. - case 244 /* CatchClause */: + case 248 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 220 /* CaseBlock */: + case 224 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -50419,33 +53992,66 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; + case 165 /* ObjectBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); // Default to parent node default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var objectLiteral = node.parent; + return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral); + } + return spanInNode(node.parent); + } + } + function spanInCloseBracketToken(node) { + switch (node.parent.kind) { + case 166 /* ArrayBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var arrayLiteral = node.parent; + return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral); + } + // Default to parent node return spanInNode(node.parent); } } function spanInOpenParenToken(node) { - if (node.parent.kind === 197 /* DoStatement */) { - // Go to while keyword and do action instead + if (node.parent.kind === 201 /* DoStatement */ || + node.parent.kind === 172 /* CallExpression */ || + node.parent.kind === 173 /* NewExpression */) { return spanInPreviousNode(node); } + if (node.parent.kind === 176 /* ParenthesizedExpression */) { + return spanInNextNode(node); + } // Default to parent node return spanInNode(node.parent); } function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 144 /* Constructor */: - case 198 /* WhileStatement */: - case 197 /* DoStatement */: - case 199 /* ForStatement */: + case 177 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: + case 178 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 146 /* Constructor */: + case 202 /* WhileStatement */: + case 201 /* DoStatement */: + case 203 /* ForStatement */: + case 205 /* ForOfStatement */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 176 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -50454,21 +54060,31 @@ var ts; } function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration - if (ts.isFunctionLike(node.parent) || node.parent.kind === 245 /* PropertyAssignment */) { + if (ts.isFunctionLike(node.parent) || + node.parent.kind === 249 /* PropertyAssignment */ || + node.parent.kind === 140 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 171 /* TypeAssertionExpression */) { - return spanInNode(node.parent.expression); + if (node.parent.kind === 175 /* TypeAssertionExpression */) { + return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 197 /* DoStatement */) { + if (node.parent.kind === 201 /* DoStatement */) { // Set span on while expression - return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); + return textSpanEndingAtNextToken(node, node.parent.expression); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInOfKeyword(node) { + if (node.parent.kind === 205 /* ForOfStatement */) { + // set using next token + return spanInNextNode(node); } // Default to parent node return spanInNode(node.parent); @@ -50495,6 +54111,9 @@ var ts; /// /* @internal */ var debugObjectHost = this; +// We need to use 'null' to interface with the managed side. +/* tslint:disable:no-null */ +/* tslint:disable:no-in-operator */ /* @internal */ var ts; (function (ts) { @@ -50506,7 +54125,6 @@ var ts; var ScriptSnapshotShimAdapter = (function () { function ScriptSnapshotShimAdapter(scriptSnapshotShim) { this.scriptSnapshotShim = scriptSnapshotShim; - this.lineStartPositions = null; } ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { return this.scriptSnapshotShim.getText(start, end); @@ -50532,7 +54150,7 @@ var ts; } }; return ScriptSnapshotShimAdapter; - })(); + }()); var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { var _this = this; @@ -50550,6 +54168,9 @@ var ts; }); }; } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } LanguageServiceShimHostAdapter.prototype.log = function (s) { if (this.loggingEnabled) { @@ -50587,14 +54208,17 @@ var ts; return this.files = JSON.parse(encoded); }; LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { - // Shim the API changes for 1.5 release. This should be removed once - // TypeScript 1.5 has shipped. - if (this.files && this.files.indexOf(fileName) < 0) { - return undefined; - } var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); }; + LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { + if ("getScriptKind" in this.shimHost) { + return this.shimHost.getScriptKind(fileName); + } + else { + return 0 /* Unknown */; + } + }; LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) { return this.shimHost.getScriptVersion(fileName); }; @@ -50619,17 +54243,10 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { - // Wrap the API changes for 1.5 release. This try/catch - // should be removed once TypeScript 1.5 has shipped. - try { - return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); - } - catch (e) { - return ""; - } + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; return LanguageServiceShimHostAdapter; - })(); + }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; /** A cancellation that throttles calls to the host */ var ThrottledCancellationToken = (function () { @@ -50651,23 +54268,17 @@ var ts; return false; }; return ThrottledCancellationToken; - })(); + }()); var CoreServicesShimHostAdapter = (function () { function CoreServicesShimHostAdapter(shimHost) { + var _this = this; this.shimHost = shimHost; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude) { - // Wrap the API changes for 1.5 release. This try/catch - // should be removed once TypeScript 1.5 has shipped. - // Also consider removing the optional designation for - // the exclude param at this time. - var encoded; - try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); - } - catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension); - } + var encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -50677,18 +54288,19 @@ var ts; return this.shimHost.readFile(fileName); }; return CoreServicesShimHostAdapter; - })(); + }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; if (logPerformance) { logger.log(actionDescription); - var start = Date.now(); + start = Date.now(); } var result = action(); if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof (result) === "string") { + if (typeof result === "string") { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -50721,7 +54333,7 @@ var ts; this.factory.unregisterShim(this); }; return ShimBase; - })(); + }()); function realizeDiagnostics(diagnostics, newLine) { return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); } @@ -50770,9 +54382,7 @@ var ts; * Update the list of scripts known to the compiler */ LanguageServiceShimObject.prototype.refresh = function (throwOnError) { - this.forwardJSONCall("refresh(" + throwOnError + ")", function () { - return null; - }); + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); }; LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { var _this = this; @@ -50787,33 +54397,25 @@ var ts; }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { var _this = this; @@ -50843,10 +54445,7 @@ var ts; */ LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { - var quickInfo = _this.languageService.getQuickInfoAtPosition(fileName, position); - return quickInfo; - }); + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); }; /// NAMEORDOTTEDNAMESPAN /** @@ -50855,10 +54454,7 @@ var ts; */ LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { var _this = this; - return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { - var spanInfo = _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); - return spanInfo; - }); + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); }; /** * STATEMENTSPAN @@ -50866,18 +54462,12 @@ var ts; */ LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { - var spanInfo = _this.languageService.getBreakpointStatementAtPosition(fileName, position); - return spanInfo; - }); + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; /// SIGNATUREHELP LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { - var signatureInfo = _this.languageService.getSignatureHelpItems(fileName, position); - return signatureInfo; - }); + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); }; /// GOTO DEFINITION /** @@ -50886,9 +54476,7 @@ var ts; */ LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; /// GOTO Type /** @@ -50897,29 +54485,20 @@ var ts; */ LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getTypeDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { - return _this.languageService.getRenameInfo(fileName, position); - }); + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); }; LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { - return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); - }); + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); }; /// GET BRACE MATCHING LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { - var textRanges = _this.languageService.getBraceMatchingAtPosition(fileName, position); - return textRanges; - }); + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); }; /// GET SMART INDENT LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { @@ -50932,21 +54511,15 @@ var ts; /// GET REFERENCES LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getReferencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { var _this = this; - return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { - return _this.languageService.findReferences(fileName, position); - }); + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); }; LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getOccurrencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { var _this = this; @@ -50965,41 +54538,32 @@ var ts; */ LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { - var completion = _this.languageService.getCompletionsAtPosition(fileName, position); - return completion; - }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; /** Get a string based representation of a completion list entry details */ LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")", function () { - var details = _this.languageService.getCompletionEntryDetails(fileName, position, entryName); - return details; - }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); - return edits; + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForDocument(fileName, localOptions); - return edits; + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); - return edits; + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { @@ -51010,45 +54574,27 @@ var ts; /** Return a list of symbols that are interesting to navigate to */ LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { - var items = _this.languageService.getNavigateToItems(searchValue, maxResultCount); - return items; - }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; - return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { - var items = _this.languageService.getNavigationBarItems(fileName); - return items; - }); + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; - return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { - var items = _this.languageService.getOutliningSpans(fileName); - return items; - }); + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); }; LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { var _this = this; - return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { - var items = _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); - return items; - }); + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); }; /// Emit LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { var _this = this; - return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { - var output = _this.languageService.getEmitOutput(fileName); - // Shim the API changes for 1.5 release. This should be removed once - // TypeScript 1.5 has shipped. - output.emitOutputStatus = output.emitSkipped ? 1 : 0; - return output; - }); + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); }; return LanguageServiceShimObject; - })(ShimBase); + }(ShimBase)); function convertClassifications(classifications) { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } @@ -51067,17 +54613,17 @@ var ts; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); - var items = classification.entries; var result = ""; - for (var i = 0; i < items.length; i++) { - result += items[i].length + "\n"; - result += items[i].classification + "\n"; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; } result += classification.finalLexState; return result; }; return ClassifierShimObject; - })(ShimBase); + }(ShimBase)); var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { @@ -51102,7 +54648,8 @@ var ts; }; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength())); + // for now treat files as JavaScript + var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); var convertResult = { referencedFiles: [], importedFiles: [], @@ -51135,24 +54682,23 @@ var ts; return { options: {}, files: [], - errors: [realizeDiagnostic(result.error, '\r\n')] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } - var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(ts.normalizeSlashes(fileName))); + var normalizedFileName = ts.normalizeSlashes(fileName); + var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { options: configFile.options, files: configFile.fileNames, - errors: realizeDiagnostics(configFile.errors, '\r\n') + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { - return this.forwardJSONCall("getDefaultCompilationSettings()", function () { - return ts.getDefaultCompilerOptions(); - }); + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); }; return CoreServicesShimObject; - })(ShimBase); + }(ShimBase)); var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; @@ -51166,7 +54712,7 @@ var ts; TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { try { if (this.documentRegistry === undefined) { - this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var hostAdapter = new LanguageServiceShimHostAdapter(host); var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); @@ -51199,7 +54745,7 @@ var ts; TypeScriptServicesFactory.prototype.close = function () { // Forget all the registered shims this._shims = []; - this.documentRegistry = ts.createDocumentRegistry(); + this.documentRegistry = undefined; }; TypeScriptServicesFactory.prototype.registerShim = function (shim) { this._shims.push(shim); @@ -51214,12 +54760,14 @@ var ts; throw new Error("Invalid operation"); }; return TypeScriptServicesFactory; - })(); + }()); ts.TypeScriptServicesFactory = TypeScriptServicesFactory; if (typeof module !== "undefined" && module.exports) { module.exports = ts; } })(ts || (ts = {})); +/* tslint:enable:no-in-operator */ +/* tslint:enable:no-null */ /// TODO: this is used by VS, clean this up on both sides of the interface /* @internal */ var TypeScript; @@ -51229,5 +54777,9 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); +/* tslint:disable:no-unused-variable */ +// 'toolsVersion' gets consumed by the managed side, so it's not unused. +// TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "1.6"; +var toolsVersion = "1.9"; +/* tslint:enable:no-unused-variable */ diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index d2758e6d5e9..2824742c63b 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -160,166 +160,170 @@ declare namespace ts { IsKeyword = 124, ModuleKeyword = 125, NamespaceKeyword = 126, - RequireKeyword = 127, - NumberKeyword = 128, - SetKeyword = 129, - StringKeyword = 130, - SymbolKeyword = 131, - TypeKeyword = 132, - FromKeyword = 133, - OfKeyword = 134, - QualifiedName = 135, - ComputedPropertyName = 136, - TypeParameter = 137, - Parameter = 138, - Decorator = 139, - PropertySignature = 140, - PropertyDeclaration = 141, - MethodSignature = 142, - MethodDeclaration = 143, - Constructor = 144, - GetAccessor = 145, - SetAccessor = 146, - CallSignature = 147, - ConstructSignature = 148, - IndexSignature = 149, - TypePredicate = 150, - TypeReference = 151, - FunctionType = 152, - ConstructorType = 153, - TypeQuery = 154, - TypeLiteral = 155, - ArrayType = 156, - TupleType = 157, - UnionType = 158, - IntersectionType = 159, - ParenthesizedType = 160, - ObjectBindingPattern = 161, - ArrayBindingPattern = 162, - BindingElement = 163, - ArrayLiteralExpression = 164, - ObjectLiteralExpression = 165, - PropertyAccessExpression = 166, - ElementAccessExpression = 167, - CallExpression = 168, - NewExpression = 169, - TaggedTemplateExpression = 170, - TypeAssertionExpression = 171, - ParenthesizedExpression = 172, - FunctionExpression = 173, - ArrowFunction = 174, - DeleteExpression = 175, - TypeOfExpression = 176, - VoidExpression = 177, - AwaitExpression = 178, - PrefixUnaryExpression = 179, - PostfixUnaryExpression = 180, - BinaryExpression = 181, - ConditionalExpression = 182, - TemplateExpression = 183, - YieldExpression = 184, - SpreadElementExpression = 185, - ClassExpression = 186, - OmittedExpression = 187, - ExpressionWithTypeArguments = 188, - AsExpression = 189, - TemplateSpan = 190, - SemicolonClassElement = 191, - Block = 192, - VariableStatement = 193, - EmptyStatement = 194, - ExpressionStatement = 195, - IfStatement = 196, - DoStatement = 197, - WhileStatement = 198, - ForStatement = 199, - ForInStatement = 200, - ForOfStatement = 201, - ContinueStatement = 202, - BreakStatement = 203, - ReturnStatement = 204, - WithStatement = 205, - SwitchStatement = 206, - LabeledStatement = 207, - ThrowStatement = 208, - TryStatement = 209, - DebuggerStatement = 210, - VariableDeclaration = 211, - VariableDeclarationList = 212, - FunctionDeclaration = 213, - ClassDeclaration = 214, - InterfaceDeclaration = 215, - TypeAliasDeclaration = 216, - EnumDeclaration = 217, - ModuleDeclaration = 218, - ModuleBlock = 219, - CaseBlock = 220, - ImportEqualsDeclaration = 221, - ImportDeclaration = 222, - ImportClause = 223, - NamespaceImport = 224, - NamedImports = 225, - ImportSpecifier = 226, - ExportAssignment = 227, - ExportDeclaration = 228, - NamedExports = 229, - ExportSpecifier = 230, - MissingDeclaration = 231, - ExternalModuleReference = 232, - JsxElement = 233, - JsxSelfClosingElement = 234, - JsxOpeningElement = 235, - JsxText = 236, - JsxClosingElement = 237, - JsxAttribute = 238, - JsxSpreadAttribute = 239, - JsxExpression = 240, - CaseClause = 241, - DefaultClause = 242, - HeritageClause = 243, - CatchClause = 244, - PropertyAssignment = 245, - ShorthandPropertyAssignment = 246, - EnumMember = 247, - SourceFile = 248, - JSDocTypeExpression = 249, - JSDocAllType = 250, - JSDocUnknownType = 251, - JSDocArrayType = 252, - JSDocUnionType = 253, - JSDocTupleType = 254, - JSDocNullableType = 255, - JSDocNonNullableType = 256, - JSDocRecordType = 257, - JSDocRecordMember = 258, - JSDocTypeReference = 259, - JSDocOptionalType = 260, - JSDocFunctionType = 261, - JSDocVariadicType = 262, - JSDocConstructorType = 263, - JSDocThisType = 264, - JSDocComment = 265, - JSDocTag = 266, - JSDocParameterTag = 267, - JSDocReturnTag = 268, - JSDocTypeTag = 269, - JSDocTemplateTag = 270, - SyntaxList = 271, - Count = 272, + ReadonlyKeyword = 127, + RequireKeyword = 128, + NumberKeyword = 129, + SetKeyword = 130, + StringKeyword = 131, + SymbolKeyword = 132, + TypeKeyword = 133, + FromKeyword = 134, + GlobalKeyword = 135, + OfKeyword = 136, + QualifiedName = 137, + ComputedPropertyName = 138, + TypeParameter = 139, + Parameter = 140, + Decorator = 141, + PropertySignature = 142, + PropertyDeclaration = 143, + MethodSignature = 144, + MethodDeclaration = 145, + Constructor = 146, + GetAccessor = 147, + SetAccessor = 148, + CallSignature = 149, + ConstructSignature = 150, + IndexSignature = 151, + TypePredicate = 152, + TypeReference = 153, + FunctionType = 154, + ConstructorType = 155, + TypeQuery = 156, + TypeLiteral = 157, + ArrayType = 158, + TupleType = 159, + UnionType = 160, + IntersectionType = 161, + ParenthesizedType = 162, + ThisType = 163, + StringLiteralType = 164, + ObjectBindingPattern = 165, + ArrayBindingPattern = 166, + BindingElement = 167, + ArrayLiteralExpression = 168, + ObjectLiteralExpression = 169, + PropertyAccessExpression = 170, + ElementAccessExpression = 171, + CallExpression = 172, + NewExpression = 173, + TaggedTemplateExpression = 174, + TypeAssertionExpression = 175, + ParenthesizedExpression = 176, + FunctionExpression = 177, + ArrowFunction = 178, + DeleteExpression = 179, + TypeOfExpression = 180, + VoidExpression = 181, + AwaitExpression = 182, + PrefixUnaryExpression = 183, + PostfixUnaryExpression = 184, + BinaryExpression = 185, + ConditionalExpression = 186, + TemplateExpression = 187, + YieldExpression = 188, + SpreadElementExpression = 189, + ClassExpression = 190, + OmittedExpression = 191, + ExpressionWithTypeArguments = 192, + AsExpression = 193, + TemplateSpan = 194, + SemicolonClassElement = 195, + Block = 196, + VariableStatement = 197, + EmptyStatement = 198, + ExpressionStatement = 199, + IfStatement = 200, + DoStatement = 201, + WhileStatement = 202, + ForStatement = 203, + ForInStatement = 204, + ForOfStatement = 205, + ContinueStatement = 206, + BreakStatement = 207, + ReturnStatement = 208, + WithStatement = 209, + SwitchStatement = 210, + LabeledStatement = 211, + ThrowStatement = 212, + TryStatement = 213, + DebuggerStatement = 214, + VariableDeclaration = 215, + VariableDeclarationList = 216, + FunctionDeclaration = 217, + ClassDeclaration = 218, + InterfaceDeclaration = 219, + TypeAliasDeclaration = 220, + EnumDeclaration = 221, + ModuleDeclaration = 222, + ModuleBlock = 223, + CaseBlock = 224, + ImportEqualsDeclaration = 225, + ImportDeclaration = 226, + ImportClause = 227, + NamespaceImport = 228, + NamedImports = 229, + ImportSpecifier = 230, + ExportAssignment = 231, + ExportDeclaration = 232, + NamedExports = 233, + ExportSpecifier = 234, + MissingDeclaration = 235, + ExternalModuleReference = 236, + JsxElement = 237, + JsxSelfClosingElement = 238, + JsxOpeningElement = 239, + JsxText = 240, + JsxClosingElement = 241, + JsxAttribute = 242, + JsxSpreadAttribute = 243, + JsxExpression = 244, + CaseClause = 245, + DefaultClause = 246, + HeritageClause = 247, + CatchClause = 248, + PropertyAssignment = 249, + ShorthandPropertyAssignment = 250, + EnumMember = 251, + SourceFile = 252, + JSDocTypeExpression = 253, + JSDocAllType = 254, + JSDocUnknownType = 255, + JSDocArrayType = 256, + JSDocUnionType = 257, + JSDocTupleType = 258, + JSDocNullableType = 259, + JSDocNonNullableType = 260, + JSDocRecordType = 261, + JSDocRecordMember = 262, + JSDocTypeReference = 263, + JSDocOptionalType = 264, + JSDocFunctionType = 265, + JSDocVariadicType = 266, + JSDocConstructorType = 267, + JSDocThisType = 268, + JSDocComment = 269, + JSDocTag = 270, + JSDocParameterTag = 271, + JSDocReturnTag = 272, + JSDocTypeTag = 273, + JSDocTemplateTag = 274, + SyntaxList = 275, + Count = 276, FirstAssignment = 56, LastAssignment = 68, FirstReservedWord = 70, LastReservedWord = 105, FirstKeyword = 70, - LastKeyword = 134, + LastKeyword = 136, FirstFutureReservedWord = 106, LastFutureReservedWord = 114, - FirstTypeNode = 151, - LastTypeNode = 160, + FirstTypeNode = 152, + LastTypeNode = 164, FirstPunctuation = 15, LastPunctuation = 68, FirstToken = 0, - LastToken = 134, + LastToken = 136, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -328,41 +332,54 @@ declare namespace ts { LastTemplateToken = 14, FirstBinaryOperator = 25, LastBinaryOperator = 68, - FirstNode = 135, + FirstNode = 137, } enum NodeFlags { None = 0, - Export = 2, - Ambient = 4, - Public = 8, - Private = 16, - Protected = 32, - Static = 64, + Export = 1, + Ambient = 2, + Public = 4, + Private = 8, + Protected = 16, + Static = 32, + Readonly = 64, Abstract = 128, Async = 256, Default = 512, - MultiLine = 1024, - Synthetic = 2048, - DeclarationFile = 4096, - Let = 8192, - Const = 16384, - OctalLiteral = 32768, - Namespace = 65536, - ExportContext = 131072, - ContainsThis = 262144, - HasImplicitReturn = 524288, - HasExplicitReturn = 1048576, - Modifier = 1022, - AccessibilityModifier = 56, - BlockScoped = 24576, - ReachabilityCheckFlags = 1572864, + Let = 1024, + Const = 2048, + Namespace = 4096, + ExportContext = 8192, + ContainsThis = 16384, + HasImplicitReturn = 32768, + HasExplicitReturn = 65536, + GlobalAugmentation = 131072, + HasClassExtends = 262144, + HasDecorators = 524288, + HasParamDecorators = 1048576, + HasAsyncFunctions = 2097152, + DisallowInContext = 4194304, + YieldContext = 8388608, + DecoratorContext = 16777216, + AwaitContext = 33554432, + ThisNodeHasError = 67108864, + JavaScriptFile = 134217728, + ThisNodeOrAnySubNodesHasError = 268435456, + HasAggregatedChildData = 536870912, + Modifier = 959, + AccessibilityModifier = 28, + BlockScoped = 3072, + ReachabilityCheckFlags = 98304, + EmitHelperFlags = 3932160, + ContextFlags = 62914560, + TypeExcludesFlags = 41943040, } enum JsxFlags { None = 0, + /** An element from a named property of the JSX.IntrinsicElements interface */ IntrinsicNamedElement = 1, + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - ClassElement = 4, - UnknownElement = 8, IntrinsicElement = 3, } interface Node extends TextRange { @@ -375,9 +392,11 @@ declare namespace ts { interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface ModifiersArray extends NodeArray { + interface ModifiersArray extends NodeArray { flags: number; } + interface Modifier extends Node { + } interface Identifier extends PrimaryExpression { text: string; originalKeywordKind?: SyntaxKind; @@ -387,11 +406,15 @@ declare namespace ts { right: Identifier; } type EntityName = Identifier | QualifiedName; + type PropertyName = Identifier | LiteralExpression | ComputedPropertyName; type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; name?: DeclarationName; } + interface DeclarationStatement extends Declaration, Statement { + name?: Identifier; + } interface ComputedPropertyName extends Node { expression: Expression; } @@ -404,10 +427,15 @@ declare namespace ts { expression?: Expression; } interface SignatureDeclaration extends Declaration { + name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; type?: TypeNode; } + interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + } + interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + } interface VariableDeclaration extends Declaration { parent?: VariableDeclarationList; name: Identifier | BindingPattern; @@ -425,23 +453,30 @@ declare namespace ts { initializer?: Expression; } interface BindingElement extends Declaration { - propertyName?: Identifier; + propertyName?: PropertyName; dotDotDotToken?: Node; name: Identifier | BindingPattern; initializer?: Expression; } - interface PropertyDeclaration extends Declaration, ClassElement { - name: DeclarationName; + interface PropertySignature extends TypeElement { + name: PropertyName; questionToken?: Node; type?: TypeNode; initializer?: Expression; } + interface PropertyDeclaration extends ClassElement { + questionToken?: Node; + name: PropertyName; + type?: TypeNode; + initializer?: Expression; + } interface ObjectLiteralElement extends Declaration { _objectLiteralBrandBrand: any; + name?: PropertyName; } interface PropertyAssignment extends ObjectLiteralElement { _propertyAssignmentBrand: any; - name: DeclarationName; + name: PropertyName; questionToken?: Node; initializer: Expression; } @@ -452,16 +487,23 @@ declare namespace ts { objectAssignmentInitializer?: Expression; } interface VariableLikeDeclaration extends Declaration { - propertyName?: Identifier; + propertyName?: PropertyName; dotDotDotToken?: Node; name: DeclarationName; questionToken?: Node; type?: TypeNode; initializer?: Expression; } + interface PropertyLikeDeclaration extends Declaration { + name: PropertyName; + } interface BindingPattern extends Node { elements: NodeArray; } + interface ObjectBindingPattern extends BindingPattern { + } + interface ArrayBindingPattern extends BindingPattern { + } /** * Several node kinds share function-like features such as a signature, * a name, and a body. These nodes should extend FunctionLikeDeclaration. @@ -476,45 +518,61 @@ declare namespace ts { questionToken?: Node; body?: Block | Expression; } - interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { + interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { name?: Identifier; - body?: Block; + body?: FunctionBody; + } + interface MethodSignature extends SignatureDeclaration, TypeElement { + name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - body?: Block; + name: PropertyName; + body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { - body?: Block; + body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { _semicolonClassElementBrand: any; } interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { _accessorDeclarationBrand: any; - body: Block; + name: PropertyName; + body: FunctionBody; } - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { + interface GetAccessorDeclaration extends AccessorDeclaration { + } + interface SetAccessorDeclaration extends AccessorDeclaration { + } + interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { _indexSignatureDeclarationBrand: any; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface ThisTypeNode extends TypeNode { + _thisTypeNodeBrand: any; + } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { _functionOrConstructorTypeNodeBrand: any; } + interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + } + interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + } interface TypeReferenceNode extends TypeNode { typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { - parameterName: Identifier; + parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { - members: NodeArray; + members: NodeArray; } interface ArrayTypeNode extends TypeNode { elementType: TypeNode; @@ -532,13 +590,18 @@ declare namespace ts { interface ParenthesizedTypeNode extends TypeNode { type: TypeNode; } - interface StringLiteral extends LiteralExpression, TypeNode { + interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode { + _stringLiteralTypeBrand: any; + } + interface StringLiteral extends LiteralExpression { _stringLiteralBrand: any; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } + interface OmittedExpression extends Expression { + } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; } @@ -581,7 +644,7 @@ declare namespace ts { asteriskToken?: Node; expression?: Expression; } - interface BinaryExpression extends Expression { + interface BinaryExpression extends Expression, Declaration { left: Expression; operatorToken: Node; right: Expression; @@ -593,25 +656,34 @@ declare namespace ts { colonToken: Node; whenFalse: Expression; } + type FunctionBody = Block; + type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { name?: Identifier; - body: Block | Expression; + body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { equalsGreaterThanToken: Node; + body: ConciseBody; } - interface LiteralExpression extends PrimaryExpression { + interface LiteralLikeNode extends Node { text: string; isUnterminated?: boolean; hasExtendedUnicodeEscape?: boolean; } + interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { + _literalExpressionBrand: any; + } + interface TemplateLiteralFragment extends LiteralLikeNode { + _templateLiteralFragmentBrand: any; + } interface TemplateExpression extends PrimaryExpression { - head: LiteralExpression; + head: TemplateLiteralFragment; templateSpans: NodeArray; } interface TemplateSpan extends Node { expression: Expression; - literal: LiteralExpression; + literal: TemplateLiteralFragment; } interface ParenthesizedExpression extends PrimaryExpression { expression: Expression; @@ -625,7 +697,7 @@ declare namespace ts { interface ObjectLiteralExpression extends PrimaryExpression, Declaration { properties: NodeArray; } - interface PropertyAccessExpression extends MemberExpression { + interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; dotToken: Node; name: Identifier; @@ -634,7 +706,7 @@ declare namespace ts { expression: LeftHandSideExpression; argumentExpression?: Expression; } - interface CallExpression extends LeftHandSideExpression { + interface CallExpression extends LeftHandSideExpression, Declaration { expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; @@ -693,6 +765,14 @@ declare namespace ts { interface Statement extends Node { _statementBrand: any; } + interface EmptyStatement extends Statement { + } + interface DebuggerStatement extends Statement { + } + interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + name?: Identifier; + } + type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { statements: NodeArray; } @@ -729,9 +809,13 @@ declare namespace ts { initializer: VariableDeclarationList | Expression; expression: Expression; } - interface BreakOrContinueStatement extends Statement { + interface BreakStatement extends Statement { label?: Identifier; } + interface ContinueStatement extends Statement { + label?: Identifier; + } + type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { expression?: Expression; } @@ -747,7 +831,7 @@ declare namespace ts { clauses: NodeArray; } interface CaseClause extends Node { - expression?: Expression; + expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { @@ -776,24 +860,31 @@ declare namespace ts { heritageClauses?: NodeArray; members: NodeArray; } - interface ClassDeclaration extends ClassLikeDeclaration, Statement { + interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { } interface ClassElement extends Declaration { _classElementBrand: any; + name?: PropertyName; } - interface InterfaceDeclaration extends Declaration, Statement { + interface TypeElement extends Declaration { + _typeElementBrand: any; + name?: PropertyName; + questionToken?: Node; + } + interface InterfaceDeclaration extends DeclarationStatement { name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; - members: NodeArray; + members: NodeArray; } interface HeritageClause extends Node { token: SyntaxKind; types?: NodeArray; } - interface TypeAliasDeclaration extends Declaration, Statement { + interface TypeAliasDeclaration extends DeclarationStatement { name: Identifier; typeParameters?: NodeArray; type: TypeNode; @@ -802,18 +893,19 @@ declare namespace ts { name: DeclarationName; initializer?: Expression; } - interface EnumDeclaration extends Declaration, Statement { + interface EnumDeclaration extends DeclarationStatement { name: Identifier; members: NodeArray; } - interface ModuleDeclaration extends Declaration, Statement { + type ModuleBody = ModuleBlock | ModuleDeclaration; + interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; body: ModuleBlock | ModuleDeclaration; } interface ModuleBlock extends Node, Statement { statements: NodeArray; } - interface ImportEqualsDeclaration extends Declaration, Statement { + interface ImportEqualsDeclaration extends DeclarationStatement { name: Identifier; moduleReference: EntityName | ExternalModuleReference; } @@ -831,22 +923,27 @@ declare namespace ts { interface NamespaceImport extends Declaration { name: Identifier; } - interface ExportDeclaration extends Declaration, Statement { + interface ExportDeclaration extends DeclarationStatement { exportClause?: NamedExports; moduleSpecifier?: Expression; } - interface NamedImportsOrExports extends Node { - elements: NodeArray; + interface NamedImports extends Node { + elements: NodeArray; } - type NamedImports = NamedImportsOrExports; - type NamedExports = NamedImportsOrExports; - interface ImportOrExportSpecifier extends Declaration { + interface NamedExports extends Node { + elements: NodeArray; + } + type NamedImportsOrExports = NamedImports | NamedExports; + interface ImportSpecifier extends Declaration { propertyName?: Identifier; name: Identifier; } - type ImportSpecifier = ImportOrExportSpecifier; - type ExportSpecifier = ImportOrExportSpecifier; - interface ExportAssignment extends Declaration, Statement { + interface ExportSpecifier extends Declaration { + propertyName?: Identifier; + name: Identifier; + } + type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; + interface ExportAssignment extends DeclarationStatement { isExportEquals?: boolean; expression: Expression; } @@ -907,7 +1004,8 @@ declare namespace ts { interface JSDocThisType extends JSDocType { type: JSDocType; } - interface JSDocRecordMember extends PropertyDeclaration { + type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; + interface JSDocRecordMember extends PropertySignature { name: Identifier | LiteralExpression; type?: JSDocType; } @@ -933,19 +1031,21 @@ declare namespace ts { postParameterName?: Identifier; isBracketed: boolean; } + interface AmdDependency { + path: string; + name: string; + } interface SourceFile extends Declaration { statements: NodeArray; endOfFileToken: Node; fileName: string; path: Path; text: string; - amdDependencies: { - path: string; - name: string; - }[]; + amdDependencies: AmdDependency[]; moduleName: string; referencedFiles: FileReference[]; languageVariant: LanguageVariant; + isDeclarationFile: boolean; /** * lib.d.ts should have a reference comment like * @@ -1039,6 +1139,7 @@ declare namespace ts { } interface EmitResult { emitSkipped: boolean; + /** Contains declaration emit diagnostics */ diagnostics: Diagnostic[]; } interface TypeChecker { @@ -1052,7 +1153,9 @@ declare namespace ts { getReturnTypeOfSignature(signature: Signature): Type; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol; + getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; getShorthandAssignmentValueSymbol(location: Node): Symbol; + getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; getTypeAtLocation(node: Node): Type; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; @@ -1066,6 +1169,7 @@ declare namespace ts { isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; + isUnknownSymbol(symbol: Symbol): boolean; getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; getAliasedSymbol(symbol: Symbol): Symbol; @@ -1077,10 +1181,11 @@ declare namespace ts { interface SymbolDisplayBuilder { buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; + buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; @@ -1116,11 +1221,22 @@ declare namespace ts { WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, } - interface TypePredicate { - parameterName: string; - parameterIndex: number; + enum TypePredicateKind { + This = 0, + Identifier = 1, + } + interface TypePredicateBase { + kind: TypePredicateKind; type: Type; } + interface ThisTypePredicate extends TypePredicateBase { + _thisTypePredicateBrand: any; + } + interface IdentifierTypePredicate extends TypePredicateBase { + parameterName: string; + parameterIndex: number; + } + type TypePredicate = IdentifierTypePredicate | ThisTypePredicate; enum SymbolFlags { None = 0, FunctionScopedVariable = 1, @@ -1220,6 +1336,7 @@ declare namespace ts { ObjectLiteral = 524288, ESSymbol = 16777216, ThisType = 33554432, + ObjectLiteralPatternWithComputedProperties = 67108864, StringLike = 258, NumberLike = 132, ObjectType = 80896, @@ -1247,8 +1364,8 @@ declare namespace ts { declaredProperties: Symbol[]; declaredCallSignatures: Signature[]; declaredConstructSignatures: Signature[]; - declaredStringIndexType: Type; - declaredNumberIndexType: Type; + declaredStringIndexInfo: IndexInfo; + declaredNumberIndexInfo: IndexInfo; } interface TypeReference extends ObjectType { target: GenericType; @@ -1277,12 +1394,16 @@ declare namespace ts { declaration: SignatureDeclaration; typeParameters: TypeParameter[]; parameters: Symbol[]; - typePredicate?: TypePredicate; } enum IndexKind { String = 0, Number = 1, } + interface IndexInfo { + type: Type; + isReadonly: boolean; + declaration?: SignatureDeclaration; + } interface DiagnosticMessage { key: string; category: DiagnosticCategory; @@ -1318,6 +1439,9 @@ declare namespace ts { Classic = 1, NodeJs = 2, } + type RootPaths = string[]; + type PathSubstitutions = Map; + type TsConfigOnlyOptions = RootPaths | PathSubstitutions; interface CompilerOptions { allowNonTsExtensions?: boolean; charset?: string; @@ -1329,6 +1453,7 @@ declare namespace ts { inlineSourceMap?: boolean; inlineSources?: boolean; jsx?: JsxEmit; + reactNamespace?: string; listFiles?: boolean; locale?: string; mapRoot?: string; @@ -1364,7 +1489,14 @@ declare namespace ts { noImplicitReturns?: boolean; noFallthroughCasesInSwitch?: boolean; forceConsistentCasingInFileNames?: boolean; - [option: string]: string | number | boolean; + baseUrl?: string; + paths?: PathSubstitutions; + rootDirs?: RootPaths; + traceModuleResolution?: boolean; + allowSyntheticDefaultImports?: boolean; + allowJs?: boolean; + noImplicitUseStrict?: boolean; + [option: string]: string | number | boolean | TsConfigOnlyOptions; } enum ModuleKind { None = 0, @@ -1388,6 +1520,13 @@ declare namespace ts { line: number; character: number; } + enum ScriptKind { + Unknown = 0, + JS = 1, + JSX = 2, + TS = 3, + TSX = 4, + } enum ScriptTarget { ES3 = 0, ES5 = 1, @@ -1407,6 +1546,8 @@ declare namespace ts { interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string; + trace?(s: string): void; + directoryExists?(directoryName: string): boolean; } interface ResolvedModule { resolvedFileName: string; @@ -1437,6 +1578,8 @@ declare namespace ts { } } declare namespace ts { + type FileWatcherCallback = (path: string, removed?: boolean) => void; + type DirectoryWatcherCallback = (path: string) => void; interface System { args: string[]; newLine: string; @@ -1444,8 +1587,8 @@ declare namespace ts { write(s: string): void; readFile(path: string, encoding?: string): string; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: (path: string, removed?: boolean) => void): FileWatcher; - watchDirectory?(path: string, callback: (path: string) => void, recursive?: boolean): FileWatcher; + watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher; + watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; fileExists(path: string): boolean; directoryExists(path: string): boolean; @@ -1459,6 +1602,10 @@ declare namespace ts { interface FileWatcher { close(): void; } + interface DirectoryWatcher extends FileWatcher { + directoryPath: Path; + referenceCount: number; + } var sys: System; } declare namespace ts { @@ -1483,6 +1630,7 @@ declare namespace ts { scanJsxIdentifier(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; + scanJSDocToken(): SyntaxKind; scan(): SyntaxKind; setText(text: string, start?: number, length?: number): void; setOnError(onError: ErrorCallback): void; @@ -1490,6 +1638,7 @@ declare namespace ts { setLanguageVariant(variant: LanguageVariant): void; setTextPos(textPos: number): void; lookAhead(callback: () => T): T; + scanRange(start: number, length: number, callback: () => T): T; tryScan(callback: () => T): T; } function tokenToString(t: SyntaxKind): string; @@ -1535,20 +1684,20 @@ declare namespace ts { */ function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; + function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; } declare namespace ts { - function getNodeConstructor(kind: SyntaxKind): new (pos?: number, end?: number) => Node; function createNode(kind: SyntaxKind, pos?: number, end?: number): 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 createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { const version: string; - function findConfigFile(searchPath: string): string; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1581,15 +1730,15 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; - function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string): { + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string): ParsedCommandLine; + function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; } declare namespace ts { /** The version of the language service API */ - let servicesVersion: string; + const servicesVersion: string; interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; @@ -1658,7 +1807,7 @@ declare namespace ts { /** Releases all resources held by this script snapshot */ dispose?(): void; } - module ScriptSnapshot { + namespace ScriptSnapshot { function fromString(text: string): IScriptSnapshot; } interface PreProcessedFileInfo { @@ -1675,6 +1824,7 @@ declare namespace ts { getNewLine?(): string; getProjectVersion?(): string; getScriptFileNames(): string[]; + getScriptKind?(fileName: string): ScriptKind; getScriptVersion(fileName: string): string; getScriptSnapshot(fileName: string): IScriptSnapshot; getLocalizedDiagnosticMessages?(): any; @@ -1686,6 +1836,7 @@ declare namespace ts { error?(s: string): void; useCaseSensitiveFileNames?(): boolean; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + directoryExists?(directoryName: string): boolean; } interface LanguageService { cleanupSemanticCache(): void; @@ -1781,7 +1932,7 @@ declare namespace ts { fileName: string; highlightSpans: HighlightSpan[]; } - module HighlightSpanKind { + namespace HighlightSpanKind { const none: string; const definition: string; const reference: string; @@ -1823,6 +1974,7 @@ declare namespace ts { InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; [s: string]: boolean | number | string; @@ -2041,7 +2193,7 @@ declare namespace ts { * @parm version Current version of the file. Only used if the file was not found * in the registry and a new one was created. */ - acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; /** * Request an updated version of an already existing SourceFile with a given fileName * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile @@ -2054,7 +2206,7 @@ declare namespace ts { * @param scriptSnapshot Text of the file. * @param version Current version of the file. */ - updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; /** * Informs the DocumentRegistry that a file is not needed any longer. * @@ -2067,7 +2219,7 @@ declare namespace ts { releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; reportStats(): string; } - module ScriptElementKind { + namespace ScriptElementKind { const unknown: string; const warning: string; const keyword: string; @@ -2098,7 +2250,7 @@ declare namespace ts { const constElement: string; const letElement: string; } - module ScriptElementKindModifier { + namespace ScriptElementKindModifier { const none: string; const publicMemberModifier: string; const privateMemberModifier: string; @@ -2126,6 +2278,12 @@ declare namespace ts { static typeAliasName: string; static parameterName: string; static docCommentTagName: string; + static jsxOpenTagName: string; + static jsxCloseTagName: string; + static jsxSelfClosingTagName: string; + static jsxAttribute: string; + static jsxText: string; + static jsxAttributeStringLiteralValue: string; } enum ClassificationType { comment = 1, @@ -2146,6 +2304,12 @@ declare namespace ts { typeAliasName = 16, parameterName = 17, docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, } interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; @@ -2166,12 +2330,11 @@ declare namespace ts { } function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; 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; + function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; - function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; + function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; function createClassifier(): Classifier; /** diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 8b0ef04f96e..8dafad54257 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -13,6 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +var __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 ts; (function (ts) { // token > SyntaxKind.Identifer => token is a keyword @@ -156,187 +161,191 @@ var ts; SyntaxKind[SyntaxKind["IsKeyword"] = 124] = "IsKeyword"; SyntaxKind[SyntaxKind["ModuleKeyword"] = 125] = "ModuleKeyword"; SyntaxKind[SyntaxKind["NamespaceKeyword"] = 126] = "NamespaceKeyword"; - SyntaxKind[SyntaxKind["RequireKeyword"] = 127] = "RequireKeyword"; - SyntaxKind[SyntaxKind["NumberKeyword"] = 128] = "NumberKeyword"; - SyntaxKind[SyntaxKind["SetKeyword"] = 129] = "SetKeyword"; - SyntaxKind[SyntaxKind["StringKeyword"] = 130] = "StringKeyword"; - SyntaxKind[SyntaxKind["SymbolKeyword"] = 131] = "SymbolKeyword"; - SyntaxKind[SyntaxKind["TypeKeyword"] = 132] = "TypeKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 133] = "FromKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 134] = "OfKeyword"; + SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 127] = "ReadonlyKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 128] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 129] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 130] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 131] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 132] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 133] = "TypeKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 134] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 135] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 136] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 135] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 136] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 137] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 138] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 137] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 138] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 139] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 139] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 140] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 141] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 140] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 141] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 142] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 143] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 144] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 145] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 146] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 147] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 148] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 149] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 142] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 143] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 144] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 145] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 146] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 147] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 148] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 149] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 150] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 151] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 150] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 151] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 152] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 153] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 154] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 155] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 156] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 157] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 158] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 159] = "IntersectionType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 160] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 152] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 153] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 154] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 155] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 156] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 157] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 158] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 159] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 160] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 161] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 162] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 163] = "ThisType"; + SyntaxKind[SyntaxKind["StringLiteralType"] = 164] = "StringLiteralType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 161] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 162] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 163] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 165] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 166] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 167] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 164] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 165] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 166] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 167] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 168] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 169] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 170] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 171] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 172] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 173] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 174] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 175] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 176] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 177] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 178] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 179] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 180] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 181] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 182] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 183] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 184] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElementExpression"] = 185] = "SpreadElementExpression"; - SyntaxKind[SyntaxKind["ClassExpression"] = 186] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 187] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 188] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 189] = "AsExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 168] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 169] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 170] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 171] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 172] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 173] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 174] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 175] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 176] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 177] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 178] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 179] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 180] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 181] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 182] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 183] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 184] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 185] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 186] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 187] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 188] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElementExpression"] = 189] = "SpreadElementExpression"; + SyntaxKind[SyntaxKind["ClassExpression"] = 190] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 191] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 192] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 193] = "AsExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 190] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 191] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 194] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 195] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 192] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 193] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 194] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 195] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 196] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 197] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 198] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 199] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 200] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 201] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 202] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 203] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 204] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 205] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 206] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 207] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 208] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 209] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 210] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 211] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 212] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 213] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 214] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 215] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 216] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 217] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 218] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 219] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 220] = "CaseBlock"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 221] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 222] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 223] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 224] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 225] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 226] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 227] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 228] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 229] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 230] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 231] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 196] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 197] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 198] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 199] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 200] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 201] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 202] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 203] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 204] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 205] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 206] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 207] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 208] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 209] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 210] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 211] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 212] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 213] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 214] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 215] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 216] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 217] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 218] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 219] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 220] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 221] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 222] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 223] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 224] = "CaseBlock"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 225] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 226] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 227] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 228] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 229] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 230] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 231] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 232] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 233] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 234] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 235] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 232] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 236] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 233] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 234] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 235] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxText"] = 236] = "JsxText"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 237] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 238] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 239] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 240] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 237] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 238] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 239] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxText"] = 240] = "JsxText"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 241] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 242] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 243] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 244] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 241] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 242] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 243] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 244] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 245] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 246] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 247] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 248] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 245] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 246] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 249] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 250] = "ShorthandPropertyAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 247] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 251] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 248] = "SourceFile"; - // JSDoc nodes. - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 249] = "JSDocTypeExpression"; - // The * type. - SyntaxKind[SyntaxKind["JSDocAllType"] = 250] = "JSDocAllType"; - // The ? type. - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 251] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocArrayType"] = 252] = "JSDocArrayType"; - SyntaxKind[SyntaxKind["JSDocUnionType"] = 253] = "JSDocUnionType"; - SyntaxKind[SyntaxKind["JSDocTupleType"] = 254] = "JSDocTupleType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 255] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 256] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocRecordType"] = 257] = "JSDocRecordType"; - SyntaxKind[SyntaxKind["JSDocRecordMember"] = 258] = "JSDocRecordMember"; - SyntaxKind[SyntaxKind["JSDocTypeReference"] = 259] = "JSDocTypeReference"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 260] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 261] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 262] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocConstructorType"] = 263] = "JSDocConstructorType"; - SyntaxKind[SyntaxKind["JSDocThisType"] = 264] = "JSDocThisType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 265] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTag"] = 266] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 267] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 268] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 269] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 270] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["SourceFile"] = 252] = "SourceFile"; + // JSDoc nodes + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 253] = "JSDocTypeExpression"; + // The * type + SyntaxKind[SyntaxKind["JSDocAllType"] = 254] = "JSDocAllType"; + // The ? type + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 255] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 256] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 257] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 258] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 259] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 260] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 261] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 262] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 263] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 264] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 265] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 266] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 267] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 268] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 269] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 270] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 271] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 272] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 273] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 274] = "JSDocTemplateTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 271] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 275] = "SyntaxList"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 272] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 276] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstReservedWord"] = 70] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 105] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 70] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 134] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 136] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 106] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 114] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 151] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 160] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 152] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 164] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 15] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 68] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 134] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 136] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -345,73 +354,58 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 14] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 25] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 68] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 135] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 137] = "FirstNode"; })(ts.SyntaxKind || (ts.SyntaxKind = {})); var SyntaxKind = ts.SyntaxKind; (function (NodeFlags) { NodeFlags[NodeFlags["None"] = 0] = "None"; - NodeFlags[NodeFlags["Export"] = 2] = "Export"; - NodeFlags[NodeFlags["Ambient"] = 4] = "Ambient"; - NodeFlags[NodeFlags["Public"] = 8] = "Public"; - NodeFlags[NodeFlags["Private"] = 16] = "Private"; - NodeFlags[NodeFlags["Protected"] = 32] = "Protected"; - NodeFlags[NodeFlags["Static"] = 64] = "Static"; + NodeFlags[NodeFlags["Export"] = 1] = "Export"; + NodeFlags[NodeFlags["Ambient"] = 2] = "Ambient"; + NodeFlags[NodeFlags["Public"] = 4] = "Public"; + NodeFlags[NodeFlags["Private"] = 8] = "Private"; + NodeFlags[NodeFlags["Protected"] = 16] = "Protected"; + NodeFlags[NodeFlags["Static"] = 32] = "Static"; + NodeFlags[NodeFlags["Readonly"] = 64] = "Readonly"; NodeFlags[NodeFlags["Abstract"] = 128] = "Abstract"; NodeFlags[NodeFlags["Async"] = 256] = "Async"; NodeFlags[NodeFlags["Default"] = 512] = "Default"; - NodeFlags[NodeFlags["MultiLine"] = 1024] = "MultiLine"; - NodeFlags[NodeFlags["Synthetic"] = 2048] = "Synthetic"; - NodeFlags[NodeFlags["DeclarationFile"] = 4096] = "DeclarationFile"; - NodeFlags[NodeFlags["Let"] = 8192] = "Let"; - NodeFlags[NodeFlags["Const"] = 16384] = "Const"; - NodeFlags[NodeFlags["OctalLiteral"] = 32768] = "OctalLiteral"; - NodeFlags[NodeFlags["Namespace"] = 65536] = "Namespace"; - NodeFlags[NodeFlags["ExportContext"] = 131072] = "ExportContext"; - NodeFlags[NodeFlags["ContainsThis"] = 262144] = "ContainsThis"; - NodeFlags[NodeFlags["HasImplicitReturn"] = 524288] = "HasImplicitReturn"; - NodeFlags[NodeFlags["HasExplicitReturn"] = 1048576] = "HasExplicitReturn"; - NodeFlags[NodeFlags["Modifier"] = 1022] = "Modifier"; - NodeFlags[NodeFlags["AccessibilityModifier"] = 56] = "AccessibilityModifier"; - NodeFlags[NodeFlags["BlockScoped"] = 24576] = "BlockScoped"; - NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 1572864] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["Let"] = 1024] = "Let"; + NodeFlags[NodeFlags["Const"] = 2048] = "Const"; + NodeFlags[NodeFlags["Namespace"] = 4096] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 8192] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 16384] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 32768] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 65536] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 131072] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasClassExtends"] = 262144] = "HasClassExtends"; + NodeFlags[NodeFlags["HasDecorators"] = 524288] = "HasDecorators"; + NodeFlags[NodeFlags["HasParamDecorators"] = 1048576] = "HasParamDecorators"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 2097152] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["DisallowInContext"] = 4194304] = "DisallowInContext"; + NodeFlags[NodeFlags["YieldContext"] = 8388608] = "YieldContext"; + NodeFlags[NodeFlags["DecoratorContext"] = 16777216] = "DecoratorContext"; + NodeFlags[NodeFlags["AwaitContext"] = 33554432] = "AwaitContext"; + NodeFlags[NodeFlags["ThisNodeHasError"] = 67108864] = "ThisNodeHasError"; + NodeFlags[NodeFlags["JavaScriptFile"] = 134217728] = "JavaScriptFile"; + NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 268435456] = "ThisNodeOrAnySubNodesHasError"; + NodeFlags[NodeFlags["HasAggregatedChildData"] = 536870912] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["Modifier"] = 959] = "Modifier"; + NodeFlags[NodeFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; + NodeFlags[NodeFlags["BlockScoped"] = 3072] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 98304] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["EmitHelperFlags"] = 3932160] = "EmitHelperFlags"; + // Parsing context flags + NodeFlags[NodeFlags["ContextFlags"] = 62914560] = "ContextFlags"; + // Exclude these flags when parsing a Type + NodeFlags[NodeFlags["TypeExcludesFlags"] = 41943040] = "TypeExcludesFlags"; })(ts.NodeFlags || (ts.NodeFlags = {})); var NodeFlags = ts.NodeFlags; - /* @internal */ - (function (ParserContextFlags) { - ParserContextFlags[ParserContextFlags["None"] = 0] = "None"; - // If this node was parsed in a context where 'in-expressions' are not allowed. - ParserContextFlags[ParserContextFlags["DisallowIn"] = 1] = "DisallowIn"; - // If this node was parsed in the 'yield' context created when parsing a generator. - ParserContextFlags[ParserContextFlags["Yield"] = 2] = "Yield"; - // If this node was parsed as part of a decorator - ParserContextFlags[ParserContextFlags["Decorator"] = 4] = "Decorator"; - // If this node was parsed in the 'await' context created when parsing an async function. - ParserContextFlags[ParserContextFlags["Await"] = 8] = "Await"; - // If the parser encountered an error when parsing the code that created this node. Note - // the parser only sets this directly on the node it creates right after encountering the - // error. - ParserContextFlags[ParserContextFlags["ThisNodeHasError"] = 16] = "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"] = 32] = "JavaScriptFile"; - // Context flags set directly by the parser. - ParserContextFlags[ParserContextFlags["ParserGeneratedFlags"] = 31] = "ParserGeneratedFlags"; - // Exclude these flags when parsing a Type - ParserContextFlags[ParserContextFlags["TypeExcludesFlags"] = 10] = "TypeExcludesFlags"; - // 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"; - // Used to know if we've computed data from children and cached it in this node. - ParserContextFlags[ParserContextFlags["HasAggregatedChildData"] = 128] = "HasAggregatedChildData"; - })(ts.ParserContextFlags || (ts.ParserContextFlags = {})); - var ParserContextFlags = ts.ParserContextFlags; (function (JsxFlags) { JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; - JsxFlags[JsxFlags["ClassElement"] = 4] = "ClassElement"; - JsxFlags[JsxFlags["UnknownElement"] = 8] = "UnknownElement"; JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; })(ts.JsxFlags || (ts.JsxFlags = {})); var JsxFlags = ts.JsxFlags; @@ -426,7 +420,7 @@ var ts; function OperationCanceledException() { } return OperationCanceledException; - })(); + }()); ts.OperationCanceledException = OperationCanceledException; /** Return code used by getEmitOutput function to indicate status of the function */ (function (ExitStatus) { @@ -472,6 +466,11 @@ var ts; SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); var SymbolAccessibility = ts.SymbolAccessibility; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(ts.TypePredicateKind || (ts.TypePredicateKind = {})); + var TypePredicateKind = ts.TypePredicateKind; /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator * metadata */ /* @internal */ @@ -573,21 +572,20 @@ var ts; NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; - NodeCheckFlags[NodeCheckFlags["EmitExtends"] = 8] = "EmitExtends"; - NodeCheckFlags[NodeCheckFlags["EmitDecorate"] = 16] = "EmitDecorate"; - NodeCheckFlags[NodeCheckFlags["EmitParam"] = 32] = "EmitParam"; - NodeCheckFlags[NodeCheckFlags["EmitAwaiter"] = 64] = "EmitAwaiter"; - NodeCheckFlags[NodeCheckFlags["EmitGenerator"] = 128] = "EmitGenerator"; NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["LexicalArguments"] = 2048] = "LexicalArguments"; - NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 4096] = "CaptureArguments"; - // Values for enum members have been computed, and any errors have been reported for them. - NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 8192] = "EnumValuesComputed"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 16384] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; - NodeCheckFlags[NodeCheckFlags["LoopWithBlockScopedBindingCapturedInFunction"] = 65536] = "LoopWithBlockScopedBindingCapturedInFunction"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var NodeCheckFlags = ts.NodeCheckFlags; (function (TypeFlags) { @@ -622,6 +620,7 @@ var ts; TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol"; TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType"; + TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties"; /* @internal */ TypeFlags[TypeFlags["Intrinsic"] = 16777343] = "Intrinsic"; /* @internal */ @@ -647,6 +646,19 @@ var ts; IndexKind[IndexKind["Number"] = 1] = "Number"; })(ts.IndexKind || (ts.IndexKind = {})); var IndexKind = ts.IndexKind; + /* @internal */ + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + /// exports.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + })(ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + var SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; @@ -679,6 +691,14 @@ var ts; NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; })(ts.NewLineKind || (ts.NewLineKind = {})); var NewLineKind = ts.NewLineKind; + (function (ScriptKind) { + ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown"; + ScriptKind[ScriptKind["JS"] = 1] = "JS"; + ScriptKind[ScriptKind["JSX"] = 2] = "JSX"; + ScriptKind[ScriptKind["TS"] = 3] = "TS"; + ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; + })(ts.ScriptKind || (ts.ScriptKind = {})); + var ScriptKind = ts.ScriptKind; (function (ScriptTarget) { ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; @@ -1067,9 +1087,11 @@ var ts; var count = array.length; if (count > 0) { var pos = 0; - var result = arguments.length <= 2 ? array[pos++] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos++; while (pos < count) { - result = f(result, array[pos++]); + result = f(result, array[pos]); + pos++; } return result; } @@ -1081,9 +1103,11 @@ var ts; if (array) { var pos = array.length - 1; if (pos >= 0) { - var result = arguments.length <= 2 ? array[pos--] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos--; while (pos >= 0) { - result = f(result, array[pos--]); + result = f(result, array[pos]); + pos--; } return result; } @@ -1176,6 +1200,32 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + /** + * Reduce the properties of a map. + * + * @param map The map to reduce + * @param callback An aggregation function that is called for each entry in the map + * @param initial The initial value for the reduction. + */ + function reduceProperties(map, callback, initial) { + var result = initial; + if (map) { + for (var key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } + } + return result; + } + ts.reduceProperties = reduceProperties; + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; function memoize(callback) { var value; return function () { @@ -1220,6 +1270,15 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; + /* internal */ + function formatMessage(dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; function createCompilerDiagnostic(message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 1) { @@ -1422,7 +1481,7 @@ var ts; } ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; function getNormalizedPathComponentsOfUrl(url) { - // Get root length of http://www.website.com/folder1/foler2/ + // Get root length of http://www.website.com/folder1/folder2/ // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; @@ -1447,7 +1506,7 @@ var ts; var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); if (indexOfNextSlash !== -1) { // Found the "/" after the website.com so the root is length of http://www.website.com/ - // and get components afetr the root normally like any other folder components + // and get components after the root normally like any other folder components rootLength = indexOfNextSlash + 1; return normalizedPathComponents(url, rootLength); } @@ -1476,7 +1535,8 @@ var ts; directoryComponents.length--; } // Find the component that differs - for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { + var joinStartIndex; + for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { break; } @@ -1501,7 +1561,7 @@ var ts; } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; function getBaseFileName(path) { - if (!path) { + if (path === undefined) { return undefined; } var i = path.lastIndexOf(ts.directorySeparator); @@ -1529,19 +1589,19 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedExtensions = [".ts", ".tsx", ".d.ts"]; - /** - * List of extensions that will be used to look for external modules. - * This list is kept separate from supportedExtensions to for cases when we'll allow to include .js files in compilation, - * but still would like to load only TypeScript files as modules - */ - ts.moduleFileExtensions = ts.supportedExtensions; - function isSupportedSourceFileName(fileName) { + ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedJavascriptExtensions = [".js", ".jsx"]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options) { + return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + ts.getSupportedExtensions = getSupportedExtensions; + function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; } - for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; + for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -1560,22 +1620,6 @@ var ts; return path; } ts.removeFileExtension = removeFileExtension; - var backslashOrDoubleQuote = /[\"\\]/g; - var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = { - "\0": "\\0", - "\t": "\\t", - "\v": "\\v", - "\f": "\\f", - "\b": "\\b", - "\r": "\\r", - "\n": "\\n", - "\\": "\\\\", - "\"": "\\\"", - "\u2028": "\\u2028", - "\u2029": "\\u2029", - "\u0085": "\\u0085" // nextLine - }; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -1586,17 +1630,16 @@ var ts; } function Signature(checker) { } + function Node(kind, pos, end) { + this.kind = kind; + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; + } ts.objectAllocator = { - getNodeConstructor: function (kind) { - function Node(pos, end) { - this.pos = pos; - this.end = end; - this.flags = 0 /* None */; - this.parent = undefined; - } - Node.prototype = { kind: kind }; - return Node; - }, + getNodeConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } @@ -1627,7 +1670,7 @@ var ts; } Debug.assert = assert; function fail(message) { - Debug.assert(false, message); + Debug.assert(/*expression*/ false, message); } Debug.fail = fail; })(Debug = ts.Debug || (ts.Debug = {})); @@ -1642,6 +1685,12 @@ var ts; return copiedList; } ts.copyListRemovingItem = copyListRemovingItem; + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; })(ts || (ts = {})); /// var ts; @@ -1788,10 +1837,9 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); - var _tty = require("tty"); // average async stat takes about 30 microseconds // set chunk size to do 30 files in < 1 millisecond - function createWatchedFileSet(interval, chunkSize) { + function createPollingWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } if (chunkSize === void 0) { chunkSize = 30; } var watchedFiles = []; @@ -1805,13 +1853,13 @@ var ts; if (!watchedFile) { return; } - _fs.stat(watchedFile.fileName, function (err, stats) { + _fs.stat(watchedFile.filePath, function (err, stats) { if (err) { - watchedFile.callback(watchedFile.fileName); + watchedFile.callback(watchedFile.filePath); } else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) { - watchedFile.mtime = getModifiedTime(watchedFile.fileName); - watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0); + watchedFile.mtime = getModifiedTime(watchedFile.filePath); + watchedFile.callback(watchedFile.filePath, watchedFile.mtime.getTime() === 0); } }); } @@ -1837,11 +1885,11 @@ var ts; nextFileToCheck = nextToCheck; }, interval); } - function addFile(fileName, callback) { + function addFile(filePath, callback) { var file = { - fileName: fileName, + filePath: filePath, callback: callback, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(filePath) }; watchedFiles.push(file); if (watchedFiles.length === 1) { @@ -1860,10 +1908,79 @@ var ts; removeFile: removeFile }; } + function createWatchedFileSet() { + var dirWatchers = ts.createFileMap(); + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createFileMap(); + return { addFile: addFile, removeFile: removeFile }; + function reduceDirWatcherRefCountForFile(filePath) { + var dirPath = ts.getDirectoryPath(filePath); + if (dirWatchers.contains(dirPath)) { + var watcher = dirWatchers.get(dirPath); + watcher.referenceCount -= 1; + if (watcher.referenceCount <= 0) { + watcher.close(); + dirWatchers.remove(dirPath); + } + } + } + function addDirWatcher(dirPath) { + if (dirWatchers.contains(dirPath)) { + var watcher_1 = dirWatchers.get(dirPath); + watcher_1.referenceCount += 1; + return; + } + var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher.referenceCount = 1; + dirWatchers.set(dirPath, watcher); + return; + } + function addFileWatcherCallback(filePath, callback) { + if (fileWatcherCallbacks.contains(filePath)) { + fileWatcherCallbacks.get(filePath).push(callback); + } + else { + fileWatcherCallbacks.set(filePath, [callback]); + } + } + function addFile(filePath, callback) { + addFileWatcherCallback(filePath, callback); + addDirWatcher(ts.getDirectoryPath(filePath)); + return { filePath: filePath, callback: callback }; + } + function removeFile(watchedFile) { + removeFileWatcherCallback(watchedFile.filePath, watchedFile.callback); + reduceDirWatcherRefCountForFile(watchedFile.filePath); + } + function removeFileWatcherCallback(filePath, callback) { + if (fileWatcherCallbacks.contains(filePath)) { + var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks.get(filePath)); + if (newCallbacks.length === 0) { + fileWatcherCallbacks.remove(filePath); + } + else { + fileWatcherCallbacks.set(filePath, newCallbacks); + } + } + } + function fileEventHandler(eventName, relativeFileName, baseDirPath) { + // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" + var filePath = typeof relativeFileName !== "string" + ? undefined + : ts.toPath(relativeFileName, baseDirPath, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)); + // Some applications save a working file via rename operations + if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks.contains(filePath)) { + for (var _i = 0, _a = fileWatcherCallbacks.get(filePath); _i < _a.length; _i++) { + var fileCallback = _a[_i]; + fileCallback(filePath); + } + } + } + } // REVIEW: for now this implementation uses polling. // The advantage of polling is that it works reliably // on all os and with network mounted files. - // For 90 referenced files, the average time to detect + // For 90 referenced files, the average time to detect // changes is 2*msInterval (by default 5 seconds). // The overhead of this is .04 percent (1/2500) with // average pause of < 1 millisecond (and max @@ -1873,6 +1990,7 @@ var ts; // changes for large reference sets? If so, do we want // to increase the chunk size or decrease the interval // time dynamically to match the large reference set? + var pollingWatchedFileSet = createPollingWatchedFileSet(); var watchedFileSet = createWatchedFileSet(); function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; @@ -1881,7 +1999,7 @@ var ts; // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; function readFile(fileName, encoding) { - if (!_fs.existsSync(fileName)) { + if (!fileExists(fileName)) { return undefined; } var buffer = _fs.readFileSync(fileName); @@ -1913,10 +2031,42 @@ var ts; if (writeByteOrderMark) { data = "\uFEFF" + data; } - _fs.writeFileSync(fileName, data, "utf8"); + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } } function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path.toLowerCase() : path; + return useCaseSensitiveFileNames ? path : path.toLowerCase(); + } + var FileSystemEntryKind; + (function (FileSystemEntryKind) { + FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File"; + FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory"; + })(FileSystemEntryKind || (FileSystemEntryKind = {})); + function fileSystemEntryExists(path, entryKind) { + try { + var stat = _fs.statSync(path); + switch (entryKind) { + case 0 /* File */: return stat.isFile(); + case 1 /* Directory */: return stat.isDirectory(); + } + } + catch (e) { + return false; + } + } + function fileExists(path) { + return fileSystemEntryExists(path, 0 /* File */); + } + function directoryExists(path) { + return fileSystemEntryExists(path, 1 /* Directory */); } function readDirectory(path, extension, exclude) { var result = []; @@ -1956,24 +2106,28 @@ var ts; }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { - // Node 4.0 stablized the `fs.watch` function on Windows which avoids polling + watchFile: function (filePath, callback) { + // Node 4.0 stabilized the `fs.watch` function on Windows which avoids polling // and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649 // and https://github.com/Microsoft/TypeScript/issues/4643), therefore // if the current node.js version is newer than 4, use `fs.watch` instead. - if (isNode4OrLater()) { - // Note: in node the callback of fs.watch is given only the relative file name as a parameter - return _fs.watch(fileName, function (eventName, relativeFileName) { return callback(fileName); }); - } - var watchedFile = watchedFileSet.addFile(fileName, callback); + var watchSet = isNode4OrLater() ? watchedFileSet : pollingWatchedFileSet; + var watchedFile = watchSet.addFile(filePath, callback); return { - close: function () { return watchedFileSet.removeFile(watchedFile); } + close: function () { return watchSet.removeFile(watchedFile); } }; }, watchDirectory: function (path, callback, recursive) { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) - return _fs.watch(path, { persistent: true, recursive: !!recursive }, function (eventName, relativeFileName) { + var options; + if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + return _fs.watch(path, options, function (eventName, relativeFileName) { // In watchDirectory we only care about adding and removing files (when event name is // "rename"); changes made within files are handled by corresponding fileWatchers (when // event name is "change") @@ -1987,12 +2141,8 @@ var ts; resolvePath: function (path) { return _path.resolve(path); }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); - }, + fileExists: fileExists, + directoryExists: directoryExists, createDirectory: function (directoryName) { if (!this.directoryExists(directoryName)) { _fs.mkdirSync(directoryName); @@ -2016,6 +2166,33 @@ var ts; } }; } + function getChakraSystem() { + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, encoding) { + // encoding is automatically handled by the implementation in ChakraHost + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = "\uFEFF" + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + readDirectory: ChakraHost.readDirectory, + exit: ChakraHost.quit + }; + } if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { return getWScriptSystem(); } @@ -2024,6 +2201,9 @@ var ts; // process.browser check excludes webpack and browserify return getNodeSystem(); } + else if (typeof ChakraHost !== "undefined") { + return getChakraSystem(); + } else { return undefined; // Unsupported host } @@ -2052,6 +2232,7 @@ var ts; An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_a_type_annotation_1021", message: "An index signature must have a type annotation." }, An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_must_have_a_type_annotation_1022", message: "An index signature parameter must have a type annotation." }, An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_type_must_be_string_or_number_1023", message: "An index signature parameter type must be 'string' or 'number'." }, + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: { code: 1024, category: ts.DiagnosticCategory.Error, key: "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", message: "'readonly' modifier can only appear on a property declaration or index signature." }, Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility_modifier_already_seen_1028", message: "Accessibility modifier already seen." }, _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{0}' modifier already seen." }, @@ -2065,7 +2246,7 @@ var ts; _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_a_class_declaration_1041", message: "'{0}' modifier cannot be used with a class declaration." }, _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_here_1042", message: "'{0}' modifier cannot be used here." }, _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_data_property_1043", message: "'{0}' modifier cannot appear on a data property." }, - _0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_element_1044", message: "'{0}' modifier cannot appear on a module element." }, + _0_modifier_cannot_appear_on_a_module_or_namespace_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", message: "'{0}' modifier cannot appear on a module or namespace element." }, A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", message: "A '{0}' modifier cannot be used with an interface declaration." }, A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", message: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_be_optional_1047", message: "A rest parameter cannot be optional." }, @@ -2084,8 +2265,11 @@ var ts; Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." }, _0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "{0} is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." }, + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." }, Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", message: "Unexpected token. A constructor, method, accessor, or property was expected." }, + _0_modifier_cannot_appear_on_a_type_member: { code: 1070, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_type_member_1070", message: "'{0}' modifier cannot appear on a type member." }, + _0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." }, A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." }, Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." }, Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher." }, @@ -2141,10 +2325,9 @@ var ts; String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, - Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: ts.DiagnosticCategory.Error, key: "Modifiers_not_permitted_on_index_signature_members_1145", message: "Modifiers not permitted on index signature members." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_1148", message: "Cannot compile modules unless the '--module' flag is provided." }, + Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting__1148", message: "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -2204,7 +2387,7 @@ var ts; Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_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_Speci_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning." }, + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_6_or_higher_1220", message: "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_1221", message: "Generators are not allowed in an ambient context." }, An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An_overload_signature_cannot_be_declared_as_a_generator_1222", message: "An overload signature cannot be declared as a generator." }, @@ -2227,10 +2410,14 @@ var ts; Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", message: "Unable to resolve signature of parameter decorator when called as an expression." }, Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", message: "Unable to resolve signature of property decorator when called as an expression." }, Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", message: "Unable to resolve signature of method decorator when called as an expression." }, - abstract_modifier_can_only_appear_on_a_class_or_method_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_or_method_declaration_1242", message: "'abstract' modifier can only appear on a class or method declaration." }, + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", message: "'abstract' modifier can only appear on a class, method, or property declaration." }, _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, + An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, + A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, + A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, @@ -2244,11 +2431,12 @@ var ts; Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list_2313", message: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." }, + Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, @@ -2258,6 +2446,7 @@ var ts; Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, + Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, @@ -2314,7 +2503,7 @@ var ts; get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", message: "Specialized overload signature is not assignable to any non-specialized signature." }, - Overload_signatures_must_all_be_exported_or_not_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_not_exported_2383", message: "Overload signatures must all be exported or not exported." }, + Overload_signatures_must_all_be_exported_or_non_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_non_exported_2383", message: "Overload signatures must all be exported or non-exported." }, Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", message: "Overload signatures must all be ambient or non-ambient." }, Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_public_private_or_protected_2385", message: "Overload signatures must all be public, private or protected." }, Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_optional_or_required_2386", message: "Overload signatures must all be optional or required." }, @@ -2328,6 +2517,7 @@ var ts; Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, @@ -2346,7 +2536,6 @@ var ts; Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'" }, Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." }, Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0: { code: 2419, category: ts.DiagnosticCategory.Error, key: "Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0_2419", message: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." }, Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." }, A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_implement_another_class_or_interface_2422", message: "A class may only implement another class or interface." }, Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, @@ -2354,7 +2543,7 @@ var ts; Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'" }, - All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_interface_must_have_identical_type_parameters_2428", message: "All declarations of an interface must have identical type parameters." }, + All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." }, Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'" }, In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, @@ -2374,8 +2563,8 @@ var ts; Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_2449", message: "The operand of an increment or decrement operator cannot be a constant." }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_2450", message: "Left-hand side of assignment expression cannot be a constant." }, + The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property_2449", message: "The operand of an increment or decrement operator cannot be a constant or a read-only property." }, + Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property_2450", message: "Left-hand side of assignment expression cannot be a constant or a read-only property." }, Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, @@ -2408,8 +2597,8 @@ var ts; Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" }, - The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant_2485", message: "The left-hand side of a 'for...of' statement cannot be a previously defined constant." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant_2486", message: "The left-hand side of a 'for...in' statement cannot be a previously defined constant." }, + The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property_2485", message: "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property." }, + The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property_2486", message: "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property." }, Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid_left_hand_side_in_for_of_statement_2487", message: "Invalid left-hand side in 'for...of' statement." }, Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, @@ -2435,12 +2624,13 @@ var ts; Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", message: "Base constructor return type '{0}' is not a class or interface type." }, Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base_constructors_must_all_have_the_same_return_type_2510", message: "Base constructors must all have the same return type." }, Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot_create_an_instance_of_the_abstract_class_0_2511", message: "Cannot create an instance of the abstract class '{0}'." }, - Overload_signatures_must_all_be_abstract_or_not_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_not_abstract_2512", message: "Overload signatures must all be abstract or not abstract." }, + Overload_signatures_must_all_be_abstract_or_non_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", message: "Overload signatures must all be abstract or non-abstract." }, Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", message: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes_containing_abstract_methods_must_be_marked_abstract_2514", message: "Classes containing abstract methods must be marked abstract." }, Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_2522", message: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, @@ -2450,7 +2640,9 @@ var ts; A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_must_be_an_object_type_2600", message: "JSX element attributes type '{0}' must be an object type." }, + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, + Property_0_is_incompatible_with_index_signature: { code: 2530, category: ts.DiagnosticCategory.Error, key: "Property_0_is_incompatible_with_index_signature_2530", message: "Property '{0}' is incompatible with index signature." }, + JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'" }, @@ -2466,6 +2658,25 @@ var ts; Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element" }, + Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'" }, + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, + Cannot_re_export_name_that_is_not_defined_in_the_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_name_that_is_not_defined_in_the_module_2661", message: "Cannot re-export name that is not defined in the module." }, + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, + Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope_2665", message: "Module augmentation cannot introduce new names in the top level scope." }, + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: { code: 2672, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", message: "Cannot assign a '{0}' constructor type to a '{1}' constructor type." }, + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: { code: 2673, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", message: "Constructor of class '{0}' is private and only accessible within the class declaration." }, + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: { code: 2674, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", message: "Constructor of class '{0}' is protected and only accessible within the class declaration." }, + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: { code: 2675, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", message: "Cannot extend a class '{0}'. Class constructor is marked as private." }, + Accessors_must_both_be_abstract_or_non_abstract: { code: 2676, category: ts.DiagnosticCategory.Error, key: "Accessors_must_both_be_abstract_or_non_abstract_2676", message: "Accessors must both be abstract or non-abstract." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2550,6 +2761,14 @@ var ts; Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, + Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'" }, + The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'" }, + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." }, + Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, + Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character" }, + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character" }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -2560,6 +2779,7 @@ var ts; Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -2582,7 +2802,7 @@ var ts; Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." }, - Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015_6046", message: "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', or 'es2015'." }, + Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none_6046", message: "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'none'." }, Argument_for_target_option_must_be_ES3_ES5_or_ES2015: { code: 6047, category: ts.DiagnosticCategory.Error, key: "Argument_for_target_option_must_be_ES3_ES5_or_ES2015_6047", message: "Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'." }, Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form or -. For example '{0}' or '{1}'." }, Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." }, @@ -2599,6 +2819,7 @@ var ts; NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "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_6062", message: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Argument_for_moduleResolution_option_must_be_node_or_classic: { code: 6063, category: ts.DiagnosticCategory.Error, key: "Argument_for_moduleResolution_option_must_be_node_or_classic_6063", message: "Argument for '--moduleResolution' option must be 'node' or 'classic'." }, + Option_0_can_only_be_specified_in_tsconfig_json_file: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", message: "Option '{0}' can only be specified in 'tsconfig.json' file." }, Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, @@ -2614,6 +2835,37 @@ var ts; Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, + Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, + Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." }, + Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit_6084", message: "Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit" }, + Enable_tracing_of_the_module_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_module_resolution_process_6085", message: "Enable tracing of the module resolution process." }, + Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" }, + Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." }, + Module_resolution_kind_is_not_specified_using_0: { code: 6088, category: ts.DiagnosticCategory.Message, key: "Module_resolution_kind_is_not_specified_using_0_6088", message: "Module resolution kind is not specified, using '{0}'." }, + Module_name_0_was_successfully_resolved_to_1: { code: 6089, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_successfully_resolved_to_1_6089", message: "======== Module name '{0}' was successfully resolved to '{1}'. ========" }, + Module_name_0_was_not_resolved: { code: 6090, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_not_resolved_6090", message: "======== Module name '{0}' was not resolved. ========" }, + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: { code: 6091, category: ts.DiagnosticCategory.Message, key: "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", message: "'paths' option is specified, looking for a pattern to match module name '{0}'." }, + Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." }, + Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." }, + Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." }, + Loading_module_as_file_Slash_folder_candidate_module_location_0: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_6095", message: "Loading module as file / folder, candidate module location '{0}'." }, + File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." }, + File_0_exist_use_it_as_a_module_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_module_resolution_result_6097", message: "File '{0}' exist - use it as a module resolution result." }, + Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." }, + Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, + package_json_does_not_have_typings_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_typings_field_6100", message: "'package.json' does not have 'typings' field." }, + package_json_has_typings_field_0_that_references_1: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_typings_field_0_that_references_1_6101", message: "'package.json' has 'typings' field '{0}' that references '{1}'." }, + Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, + Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, + Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." }, + Expected_type_of_typings_field_in_package_json_to_be_string_got_0: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_typings_field_in_package_json_to_be_string_got_0_6105", message: "Expected type of 'typings' field in 'package.json' to be 'string', got '{0}'." }, + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'" }, + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'" }, + Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'" }, + Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'" }, + Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'" }, + Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed" }, + Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2621,6 +2873,7 @@ var ts; _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", message: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation_7016", message: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index_signature_of_object_type_implicitly_has_an_any_type_7017", message: "Index signature of object type implicitly has an 'any' type." }, Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, @@ -2651,7 +2904,6 @@ var ts; 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_8014", message: "'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_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, - 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_8017", message: "'decorators' can only be used in a .ts file." }, 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_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, @@ -2661,7 +2913,9 @@ var ts; Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'" }, An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." } + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, + JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." } }; })(ts || (ts = {})); /// @@ -2697,7 +2951,7 @@ var ts; "false": 84 /* FalseKeyword */, "finally": 85 /* FinallyKeyword */, "for": 86 /* ForKeyword */, - "from": 133 /* FromKeyword */, + "from": 134 /* FromKeyword */, "function": 87 /* FunctionKeyword */, "get": 123 /* GetKeyword */, "if": 88 /* IfKeyword */, @@ -2712,24 +2966,26 @@ var ts; "namespace": 126 /* NamespaceKeyword */, "new": 92 /* NewKeyword */, "null": 93 /* NullKeyword */, - "number": 128 /* NumberKeyword */, + "number": 129 /* NumberKeyword */, "package": 109 /* PackageKeyword */, "private": 110 /* PrivateKeyword */, "protected": 111 /* ProtectedKeyword */, "public": 112 /* PublicKeyword */, - "require": 127 /* RequireKeyword */, + "readonly": 127 /* ReadonlyKeyword */, + "require": 128 /* RequireKeyword */, + "global": 135 /* GlobalKeyword */, "return": 94 /* ReturnKeyword */, - "set": 129 /* SetKeyword */, + "set": 130 /* SetKeyword */, "static": 113 /* StaticKeyword */, - "string": 130 /* StringKeyword */, + "string": 131 /* StringKeyword */, "super": 95 /* SuperKeyword */, "switch": 96 /* SwitchKeyword */, - "symbol": 131 /* SymbolKeyword */, + "symbol": 132 /* SymbolKeyword */, "this": 97 /* ThisKeyword */, "throw": 98 /* ThrowKeyword */, "true": 99 /* TrueKeyword */, "try": 100 /* TryKeyword */, - "type": 132 /* TypeKeyword */, + "type": 133 /* TypeKeyword */, "typeof": 101 /* TypeOfKeyword */, "var": 102 /* VarKeyword */, "void": 103 /* VoidKeyword */, @@ -2738,7 +2994,7 @@ var ts; "yield": 114 /* YieldKeyword */, "async": 118 /* AsyncKeyword */, "await": 119 /* AwaitKeyword */, - "of": 134 /* OfKeyword */, + "of": 136 /* OfKeyword */, "{": 15 /* OpenBraceToken */, "}": 16 /* CloseBraceToken */, "(": 17 /* OpenParenToken */, @@ -2901,7 +3157,8 @@ var ts; var pos = 0; var lineStart = 0; while (pos < text.length) { - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 13 /* carriageReturn */: if (text.charCodeAt(pos) === 10 /* lineFeed */) { @@ -3035,6 +3292,11 @@ var ts; ts.couldStartTrivia = couldStartTrivia; /* @internal */ function skipTrivia(text, pos, stopAfterLineBreak) { + // Using ! with a greater than test is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + if (!(pos >= 0)) { + return pos; + } // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -3104,7 +3366,7 @@ var ts; } ts.skipTrivia = skipTrivia; // All conflict markers consist of the same character repeated seven times. If it is - // a <<<<<<< or >>>>>>> marker then it is also followd by a space. + // a <<<<<<< or >>>>>>> marker then it is also followed by a space. var mergeConflictMarkerLength = "<<<<<<<".length; function isConflictMarkerTrivia(text, pos) { ts.Debug.assert(pos >= 0); @@ -3136,7 +3398,7 @@ var ts; } else { ts.Debug.assert(ch === 61 /* equals */); - // Consume everything from the start of the mid-conlict marker to the start of the next + // Consume everything from the start of the mid-conflict marker to the start of the next // end-conflict marker. while (pos < len) { var ch_1 = text.charCodeAt(pos); @@ -3173,7 +3435,7 @@ var ts; function getCommentRanges(text, pos, trailing) { var result; var collecting = trailing || pos === 0; - while (true) { + while (pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13 /* carriageReturn */: @@ -3242,6 +3504,7 @@ var ts; } return result; } + return result; } function getLeadingCommentRanges(text, pos) { return getCommentRanges(text, pos, /*trailing*/ false); @@ -3270,6 +3533,19 @@ var ts; ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; + /* @internal */ + function isIdentifier(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1, n = name.length; i < n; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifier = isIdentifier; // Creates a scanner over a (possibly unspecified) range of a piece of text. function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } @@ -3305,6 +3581,7 @@ var ts; scanJsxIdentifier: scanJsxIdentifier, reScanJsxToken: reScanJsxToken, scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, scan: scan, setText: setText, setScriptTarget: setScriptTarget, @@ -3312,7 +3589,8 @@ var ts; setOnError: setOnError, setTextPos: setTextPos, tryScan: tryScan, - lookAhead: lookAhead + lookAhead: lookAhead, + scanRange: scanRange }; function error(message, length) { if (onError) { @@ -3343,7 +3621,7 @@ var ts; error(ts.Diagnostics.Digit_expected); } } - return +(text.substring(start, end)); + return "" + +(text.substring(start, end)); } function scanOctalDigits() { var start = pos; @@ -3392,7 +3670,8 @@ var ts; return value; } function scanString() { - var quote = text.charCodeAt(pos++); + var quote = text.charCodeAt(pos); + pos++; var result = ""; var start = pos; while (true) { @@ -3488,7 +3767,8 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); return ""; } - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 48 /* _0 */: return "\0"; @@ -3715,7 +3995,8 @@ var ts; } return pos += 2, token = 31 /* ExclamationEqualsToken */; } - return pos++, token = 49 /* ExclamationToken */; + pos++; + return token = 49 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); @@ -3726,7 +4007,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 62 /* PercentEqualsToken */; } - return pos++, token = 40 /* PercentToken */; + pos++; + return token = 40 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { return pos += 2, token = 51 /* AmpersandAmpersandToken */; @@ -3734,11 +4016,14 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 66 /* AmpersandEqualsToken */; } - return pos++, token = 46 /* AmpersandToken */; + pos++; + return token = 46 /* AmpersandToken */; case 40 /* openParen */: - return pos++, token = 17 /* OpenParenToken */; + pos++; + return token = 17 /* OpenParenToken */; case 41 /* closeParen */: - return pos++, token = 18 /* CloseParenToken */; + pos++; + return token = 18 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 59 /* AsteriskEqualsToken */; @@ -3749,7 +4034,8 @@ var ts; } return pos += 2, token = 38 /* AsteriskAsteriskToken */; } - return pos++, token = 37 /* AsteriskToken */; + pos++; + return token = 37 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { return pos += 2, token = 41 /* PlusPlusToken */; @@ -3757,9 +4043,11 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 57 /* PlusEqualsToken */; } - return pos++, token = 35 /* PlusToken */; + pos++; + return token = 35 /* PlusToken */; case 44 /* comma */: - return pos++, token = 24 /* CommaToken */; + pos++; + return token = 24 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { return pos += 2, token = 42 /* MinusMinusToken */; @@ -3767,16 +4055,18 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 58 /* MinusEqualsToken */; } - return pos++, token = 36 /* MinusToken */; + pos++; + return token = 36 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = "" + scanNumber(); + tokenValue = scanNumber(); return token = 8 /* NumericLiteral */; } if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { return pos += 3, token = 22 /* DotDotDotToken */; } - return pos++, token = 21 /* DotToken */; + pos++; + return token = 21 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -3824,7 +4114,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 61 /* SlashEqualsToken */; } - return pos++, token = 39 /* SlashToken */; + pos++; + return token = 39 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; @@ -3873,12 +4164,14 @@ var ts; case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - tokenValue = "" + scanNumber(); + tokenValue = scanNumber(); return token = 8 /* NumericLiteral */; case 58 /* colon */: - return pos++, token = 54 /* ColonToken */; + pos++; + return token = 54 /* ColonToken */; case 59 /* semicolon */: - return pos++, token = 23 /* SemicolonToken */; + pos++; + return token = 23 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3903,7 +4196,8 @@ var ts; text.charCodeAt(pos + 2) !== 42 /* asterisk */) { return pos += 2, token = 26 /* LessThanSlashToken */; } - return pos++, token = 25 /* LessThanToken */; + pos++; + return token = 25 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3923,7 +4217,8 @@ var ts; if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { return pos += 2, token = 34 /* EqualsGreaterThanToken */; } - return pos++, token = 56 /* EqualsToken */; + pos++; + return token = 56 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3934,20 +4229,26 @@ var ts; return token = 7 /* ConflictMarkerTrivia */; } } - return pos++, token = 27 /* GreaterThanToken */; + pos++; + return token = 27 /* GreaterThanToken */; case 63 /* question */: - return pos++, token = 53 /* QuestionToken */; + pos++; + return token = 53 /* QuestionToken */; case 91 /* openBracket */: - return pos++, token = 19 /* OpenBracketToken */; + pos++; + return token = 19 /* OpenBracketToken */; case 93 /* closeBracket */: - return pos++, token = 20 /* CloseBracketToken */; + pos++; + return token = 20 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 68 /* CaretEqualsToken */; } - return pos++, token = 48 /* CaretToken */; + pos++; + return token = 48 /* CaretToken */; case 123 /* openBrace */: - return pos++, token = 15 /* OpenBraceToken */; + pos++; + return token = 15 /* OpenBraceToken */; case 124 /* bar */: if (text.charCodeAt(pos + 1) === 124 /* bar */) { return pos += 2, token = 52 /* BarBarToken */; @@ -3955,13 +4256,17 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 67 /* BarEqualsToken */; } - return pos++, token = 47 /* BarToken */; + pos++; + return token = 47 /* BarToken */; case 125 /* closeBrace */: - return pos++, token = 16 /* CloseBraceToken */; + pos++; + return token = 16 /* CloseBraceToken */; case 126 /* tilde */: - return pos++, token = 50 /* TildeToken */; + pos++; + return token = 50 /* TildeToken */; case 64 /* at */: - return pos++, token = 55 /* AtToken */; + pos++; + return token = 55 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -3970,7 +4275,8 @@ var ts; return token = getIdentifierToken(); } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0 /* Unknown */; + pos++; + return token = 0 /* Unknown */; default: if (isIdentifierStart(ch, languageVersion)) { pos++; @@ -3992,7 +4298,8 @@ var ts; continue; } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0 /* Unknown */; + pos++; + return token = 0 /* Unknown */; } } } @@ -4008,10 +4315,12 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 64 /* GreaterThanGreaterThanEqualsToken */; } - return pos++, token = 44 /* GreaterThanGreaterThanToken */; + pos++; + return token = 44 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { - return pos++, token = 29 /* GreaterThanEqualsToken */; + pos++; + return token = 29 /* GreaterThanEqualsToken */; } } return token; @@ -4103,7 +4412,7 @@ var ts; break; } } - return token = 236 /* JsxText */; + return token = 240 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -4123,6 +4432,55 @@ var ts; } return token; } + function scanJSDocToken() { + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + startPos = pos; + // Eat leading whitespace + var ch = text.charCodeAt(pos); + while (pos < end) { + ch = text.charCodeAt(pos); + if (isWhiteSpace(ch)) { + pos++; + } + else { + break; + } + } + tokenPos = pos; + switch (ch) { + case 64 /* at */: + return pos += 1, token = 55 /* AtToken */; + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + return pos += 1, token = 4 /* NewLineTrivia */; + case 42 /* asterisk */: + return pos += 1, token = 37 /* AsteriskToken */; + case 123 /* openBrace */: + return pos += 1, token = 15 /* OpenBraceToken */; + case 125 /* closeBrace */: + return pos += 1, token = 16 /* CloseBraceToken */; + case 91 /* openBracket */: + return pos += 1, token = 19 /* OpenBracketToken */; + case 93 /* closeBracket */: + return pos += 1, token = 20 /* CloseBracketToken */; + case 61 /* equals */: + return pos += 1, token = 56 /* EqualsToken */; + case 44 /* comma */: + return pos += 1, token = 24 /* CommaToken */; + } + if (isIdentifierStart(ch, 2 /* Latest */)) { + pos++; + while (isIdentifierPart(text.charCodeAt(pos), 2 /* Latest */) && pos < end) { + pos++; + } + return token = 69 /* Identifier */; + } + else { + return pos += 1, token = 0 /* Unknown */; + } + } function speculationHelper(callback, isLookahead) { var savePos = pos; var saveStartPos = startPos; @@ -4143,11 +4501,34 @@ var ts; } return result; } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var savePrecedingLineBreak = precedingLineBreak; + var saveTokenValue = tokenValue; + var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + var saveTokenIsUnterminated = tokenIsUnterminated; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + precedingLineBreak = savePrecedingLineBreak; + tokenValue = saveTokenValue; + hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; + tokenIsUnterminated = saveTokenIsUnterminated; + return result; + } function lookAhead(callback) { - return speculationHelper(callback, /*isLookahead:*/ true); + return speculationHelper(callback, /*isLookahead*/ true); } function tryScan(callback) { - return speculationHelper(callback, /*isLookahead:*/ false); + return speculationHelper(callback, /*isLookahead*/ false); } function setText(newText, start, length) { text = newText || ""; @@ -4177,1321 +4558,6 @@ var ts; } ts.createScanner = createScanner; })(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - ts.bindTime = 0; - (function (ModuleInstanceState) { - ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; - ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; - ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; - })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); - var ModuleInstanceState = ts.ModuleInstanceState; - var Reachability; - (function (Reachability) { - Reachability[Reachability["Unintialized"] = 1] = "Unintialized"; - Reachability[Reachability["Reachable"] = 2] = "Reachable"; - Reachability[Reachability["Unreachable"] = 4] = "Unreachable"; - Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable"; - })(Reachability || (Reachability = {})); - function or(state1, state2) { - return (state1 | state2) & 2 /* Reachable */ - ? 2 /* Reachable */ - : (state1 & state2) & 8 /* ReportedUnreachable */ - ? 8 /* ReportedUnreachable */ - : 4 /* Unreachable */; - } - function getModuleInstanceState(node) { - // A module is uninstantiated if it contains only - // 1. interface declarations, type alias declarations - if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 216 /* TypeAliasDeclaration */) { - return 0 /* NonInstantiated */; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2 /* ConstEnumOnly */; - } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) { - return 0 /* NonInstantiated */; - } - else if (node.kind === 219 /* ModuleBlock */) { - var state = 0 /* NonInstantiated */; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0 /* NonInstantiated */: - // child is non-instantiated - continue searching - return false; - case 2 /* ConstEnumOnly */: - // child is const enum only - record state and continue searching - state = 2 /* ConstEnumOnly */; - return false; - case 1 /* Instantiated */: - // child is instantiated - record state and stop - state = 1 /* Instantiated */; - return true; - } - }); - return state; - } - else if (node.kind === 218 /* ModuleDeclaration */) { - return getModuleInstanceState(node.body); - } - else { - return 1 /* Instantiated */; - } - } - ts.getModuleInstanceState = getModuleInstanceState; - var ContainerFlags; - (function (ContainerFlags) { - // The current node is not a container, and no container manipulation should happen before - // recursing into it. - ContainerFlags[ContainerFlags["None"] = 0] = "None"; - // The current node is a container. It should be set as the current container (and block- - // container) before recursing into it. The current node does not have locals. Examples: - // - // Classes, ObjectLiterals, TypeLiterals, Interfaces... - ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; - // The current node is a block-scoped-container. It should be set as the current block- - // container before recursing into it. Examples: - // - // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... - ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; - 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 = {})); - var binder = createBinder(); - function bindSourceFile(file, options) { - var start = new Date().getTime(); - binder(file, options); - ts.bindTime += new Date().getTime() - start; - } - ts.bindSourceFile = bindSourceFile; - function createBinder() { - var file; - var options; - var parent; - var container; - var blockScopeContainer; - var lastContainer; - var seenThisKeyword; - // state used by reachability checks - var hasExplicitReturn; - var currentReachabilityState; - var labelStack; - var labelIndexMap; - var implicitLabels; - // 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; - var symbolCount = 0; - var Symbol; - var classifiableNames; - function bindSourceFile(f, opts) { - file = f; - options = opts; - inStrictMode = !!file.externalModuleIndicator; - classifiableNames = {}; - Symbol = ts.objectAllocator.getSymbolConstructor(); - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - hasExplicitReturn = false; - labelStack = undefined; - labelIndexMap = undefined; - implicitLabels = undefined; - } - return bindSourceFile; - function createSymbol(flags, name) { - symbolCount++; - return new Symbol(flags, name); - } - function addDeclarationToSymbol(symbol, node, symbolFlags) { - symbol.flags |= symbolFlags; - node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = []; - } - symbol.declarations.push(node); - if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { - symbol.exports = {}; - } - 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 === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { - return "\"" + node.name.text + "\""; - } - if (node.name.kind === 136 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); - } - return node.name.text; - } - switch (node.kind) { - case 144 /* Constructor */: - return "__constructor"; - case 152 /* FunctionType */: - case 147 /* CallSignature */: - return "__call"; - case 153 /* ConstructorType */: - case 148 /* ConstructSignature */: - return "__new"; - case 149 /* IndexSignature */: - return "__index"; - case 228 /* ExportDeclaration */: - return "__export"; - case 227 /* ExportAssignment */: - return node.isExportEquals ? "export=" : "default"; - case 213 /* FunctionDeclaration */: - case 214 /* ClassDeclaration */: - return node.flags & 512 /* Default */ ? "default" : undefined; - } - } - function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); - } - /** - * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. - * @param symbolTable - The symbol table which node will be added to. - * @param parent - node's parent declaration. - * @param node - The declaration to be added to the symbol table - * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) - * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. - */ - function declareSymbol(symbolTable, parent, node, includes, excludes) { - ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 512 /* Default */; - // The exported symbol for an export default function/class node is always named "default" - var name = isDefaultExport && parent ? "default" : getDeclarationName(node); - var symbol; - if (name !== undefined) { - // Check and see if the symbol table already has a symbol with this name. If not, - // create a new symbol with this name and add it to the table. Note that we don't - // give the new symbol any flags *yet*. This ensures that it will not conflict - // with the 'excludes' flags we pass in. - // - // If we do get an existing symbol, see if it conflicts with the new symbol we're - // creating. For example, a 'var' symbol and a 'class' symbol will conflict within - // the same symbol table. If we have a conflict, report the issue on each - // declaration we have for this symbol, and then create a new symbol for this - // declaration. - // - // 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; - } - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - var message = symbol.flags & 2 /* BlockScopedVariable */ - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 512 /* Default */) { - message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - }); - ts.forEach(symbol.declarations, function (declaration) { - 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 /* None */, name); - } - } - else { - symbol = createSymbol(0 /* None */, "__missing"); - } - addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; - return symbol; - } - function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 2 /* Export */; - if (symbolFlags & 8388608 /* Alias */) { - if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - else { - // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue, - // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set - // on it. There are 2 main reasons: - // - // 1. We treat locals and exports of the same name as mutually exclusive within a container. - // That means the binder will issue a Duplicate Identifier error if you mix locals and exports - // with the same name in the same container. - // TODO: Make this a more specific error and decouple it from the exclusion logic. - // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, - // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way - // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. - if (hasExportModifier || container.flags & 131072 /* ExportContext */) { - 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, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - 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) { - // 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; - // 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); - } - else if (containerFlags & 2 /* IsBlockScopedContainer */) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - var savedReachabilityState; - var savedLabelStack; - var savedLabels; - var savedImplicitLabels; - var savedHasExplicitReturn; - var kind = node.kind; - var flags = node.flags; - // reset all reachability check related flags on node (for incremental scenarios) - flags &= ~1572864 /* ReachabilityCheckFlags */; - if (kind === 215 /* InterfaceDeclaration */) { - seenThisKeyword = false; - } - var saveState = kind === 248 /* SourceFile */ || kind === 219 /* ModuleBlock */ || ts.isFunctionLikeKind(kind); - if (saveState) { - savedReachabilityState = currentReachabilityState; - savedLabelStack = labelStack; - savedLabels = labelIndexMap; - savedImplicitLabels = implicitLabels; - savedHasExplicitReturn = hasExplicitReturn; - currentReachabilityState = 2 /* Reachable */; - hasExplicitReturn = false; - labelStack = labelIndexMap = implicitLabels = undefined; - } - bindReachableStatement(node); - if (currentReachabilityState === 2 /* Reachable */ && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { - flags |= 524288 /* HasImplicitReturn */; - if (hasExplicitReturn) { - flags |= 1048576 /* HasExplicitReturn */; - } - } - if (kind === 215 /* InterfaceDeclaration */) { - flags = seenThisKeyword ? flags | 262144 /* ContainsThis */ : flags & ~262144 /* ContainsThis */; - } - node.flags = flags; - if (saveState) { - hasExplicitReturn = savedHasExplicitReturn; - currentReachabilityState = savedReachabilityState; - labelStack = savedLabelStack; - labelIndexMap = savedLabels; - implicitLabels = savedImplicitLabels; - } - container = saveContainer; - parent = saveParent; - blockScopeContainer = savedBlockScopeContainer; - } - /** - * Returns true if node and its subnodes were successfully traversed. - * Returning false means that node was not examined and caller needs to dive into the node himself. - */ - function bindReachableStatement(node) { - if (checkUnreachable(node)) { - ts.forEachChild(node, bind); - return; - } - switch (node.kind) { - case 198 /* WhileStatement */: - bindWhileStatement(node); - break; - case 197 /* DoStatement */: - bindDoStatement(node); - break; - case 199 /* ForStatement */: - bindForStatement(node); - break; - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - bindForInOrForOfStatement(node); - break; - case 196 /* IfStatement */: - bindIfStatement(node); - break; - case 204 /* ReturnStatement */: - case 208 /* ThrowStatement */: - bindReturnOrThrow(node); - break; - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: - bindBreakOrContinueStatement(node); - break; - case 209 /* TryStatement */: - bindTryStatement(node); - break; - case 206 /* SwitchStatement */: - bindSwitchStatement(node); - break; - case 220 /* CaseBlock */: - bindCaseBlock(node); - break; - case 207 /* LabeledStatement */: - bindLabeledStatement(node); - break; - default: - ts.forEachChild(node, bind); - break; - } - } - function bindWhileStatement(n) { - var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; - var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; - // bind expressions (don't affect reachability) - bind(n.expression); - currentReachabilityState = preWhileState; - var postWhileLabel = pushImplicitLabel(); - bind(n.statement); - popImplicitLabel(postWhileLabel, postWhileState); - } - function bindDoStatement(n) { - var preDoState = currentReachabilityState; - var postDoLabel = pushImplicitLabel(); - bind(n.statement); - var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState; - popImplicitLabel(postDoLabel, postDoState); - // bind expressions (don't affect reachability) - bind(n.expression); - } - function bindForStatement(n) { - var preForState = currentReachabilityState; - var postForLabel = pushImplicitLabel(); - // bind expressions (don't affect reachability) - bind(n.initializer); - bind(n.condition); - bind(n.incrementor); - bind(n.statement); - // for statement is considered infinite when it condition is either omitted or is true keyword - // - for(..;;..) - // - for(..;true;..) - var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */); - var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState; - popImplicitLabel(postForLabel, postForState); - } - function bindForInOrForOfStatement(n) { - var preStatementState = currentReachabilityState; - var postStatementLabel = pushImplicitLabel(); - // bind expressions (don't affect reachability) - bind(n.initializer); - bind(n.expression); - bind(n.statement); - popImplicitLabel(postStatementLabel, preStatementState); - } - function bindIfStatement(n) { - // denotes reachability state when entering 'thenStatement' part of the if statement: - // i.e. if condition is false then thenStatement is unreachable - var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; - // denotes reachability state when entering 'elseStatement': - // i.e. if condition is true then elseStatement is unreachable - var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; - currentReachabilityState = ifTrueState; - // bind expression (don't affect reachability) - bind(n.expression); - bind(n.thenStatement); - if (n.elseStatement) { - var preElseState = currentReachabilityState; - currentReachabilityState = ifFalseState; - bind(n.elseStatement); - currentReachabilityState = or(currentReachabilityState, preElseState); - } - else { - currentReachabilityState = or(currentReachabilityState, ifFalseState); - } - } - function bindReturnOrThrow(n) { - // bind expression (don't affect reachability) - bind(n.expression); - if (n.kind === 204 /* ReturnStatement */) { - hasExplicitReturn = true; - } - currentReachabilityState = 4 /* Unreachable */; - } - function bindBreakOrContinueStatement(n) { - // call bind on label (don't affect reachability) - bind(n.label); - // for continue case touch label so it will be marked a used - var isValidJump = jumpToLabel(n.label, n.kind === 203 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); - if (isValidJump) { - currentReachabilityState = 4 /* Unreachable */; - } - } - function bindTryStatement(n) { - // catch\finally blocks has the same reachability as try block - var preTryState = currentReachabilityState; - bind(n.tryBlock); - var postTryState = currentReachabilityState; - currentReachabilityState = preTryState; - bind(n.catchClause); - var postCatchState = currentReachabilityState; - currentReachabilityState = preTryState; - bind(n.finallyBlock); - // post catch/finally state is reachable if - // - post try state is reachable - control flow can fall out of try block - // - post catch state is reachable - control flow can fall out of catch block - currentReachabilityState = or(postTryState, postCatchState); - } - function bindSwitchStatement(n) { - var preSwitchState = currentReachabilityState; - var postSwitchLabel = pushImplicitLabel(); - // bind expression (don't affect reachability) - bind(n.expression); - bind(n.caseBlock); - var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242 /* DefaultClause */; }); - // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case - var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState; - popImplicitLabel(postSwitchLabel, postSwitchState); - } - function bindCaseBlock(n) { - var startState = currentReachabilityState; - for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { - var clause = _a[_i]; - currentReachabilityState = startState; - bind(clause); - if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } - } - } - function bindLabeledStatement(n) { - // call bind on label (don't affect reachability) - bind(n.label); - var ok = pushNamedLabel(n.label); - bind(n.statement); - if (ok) { - popNamedLabel(n.label, currentReachabilityState); - } - } - function getContainerFlags(node) { - switch (node.kind) { - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 155 /* TypeLiteral */: - case 165 /* ObjectLiteralExpression */: - return 1 /* IsContainer */; - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 213 /* FunctionDeclaration */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 218 /* ModuleDeclaration */: - case 248 /* SourceFile */: - case 216 /* TypeAliasDeclaration */: - return 5 /* IsContainerWithLocals */; - case 244 /* CatchClause */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 220 /* CaseBlock */: - return 2 /* IsBlockScopedContainer */; - case 192 /* 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 */; - } - return 0 /* None */; - } - function addToContainerChain(next) { - if (lastContainer) { - lastContainer.nextContainer = next; - } - lastContainer = next; - } - function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - // Just call this directly so that the return type of this function stays "void". - 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 218 /* ModuleDeclaration */: - return declareModuleMember(node, symbolFlags, symbolExcludes); - case 248 /* SourceFile */: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: - return declareClassMember(node, symbolFlags, symbolExcludes); - case 217 /* EnumDeclaration */: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 155 /* TypeLiteral */: - case 165 /* ObjectLiteralExpression */: - case 215 /* 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 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 216 /* 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 & 64 /* 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 hasExportDeclarations(node) { - var body = node.kind === 248 /* SourceFile */ ? node : node.body; - if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var stat = _a[_i]; - if (stat.kind === 228 /* ExportDeclaration */ || stat.kind === 227 /* ExportAssignment */) { - return true; - } - } - } - return false; - } - function setExportContextFlag(node) { - // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular - // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 131072 /* ExportContext */; - } - else { - node.flags &= ~131072 /* ExportContext */; - } - } - function bindModuleDeclaration(node) { - setExportContextFlag(node); - if (node.name.kind === 9 /* StringLiteral */) { - declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); - } - else { - var state = getModuleInstanceState(node); - if (state === 0 /* NonInstantiated */) { - declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */); - } - else { - declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); - if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { - // if module was already merged with some function, class or non-const enum - // treat is a non-const-enum-only - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; - if (node.symbol.constEnumOnlyModule === undefined) { - // non-merged case - use the current state - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - // merged case: module is const enum only if all its pieces are non-instantiated or const enum - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } - } - } - } - function bindFunctionOrConstructorType(node) { - // For a given function symbol "<...>(...) => T" we want to generate a symbol identical - // to the one we would get for: { <...>(...): T } - // - // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable - // from an actual type literal symbol you would have gotten had you used the long form. - var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072 /* Signature */); - var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); - var _a; - } - 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 !== 69 /* 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 === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* 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 bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - addDeclarationToSymbol(symbol, node, symbolFlags); - } - function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { - switch (blockScopeContainer.kind) { - case 218 /* ModuleDeclaration */: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case 248 /* SourceFile */: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - // fall through. - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); - } - // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized - // check for reserved words used as identifiers in strict mode code. - function checkStrictModeIdentifier(node) { - if (inStrictMode && - node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 114 /* 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.getContainingClass(node)) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - function checkStrictModeBinaryExpression(node) { - if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) - checkStrictModeEvalOrArguments(node, node.left); - } - } - function checkStrictModeCatchClause(node) { - // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the - // Catch production is eval or arguments - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - function checkStrictModeDeleteExpression(node) { - // Grammar checking - if (inStrictMode && node.expression.kind === 69 /* 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 === 69 /* Identifier */ && - (node.text === "eval" || node.text === "arguments"); - } - function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 69 /* 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.getContainingClass(node)) { - return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; - } - function checkStrictModeFunctionName(node) { - if (inStrictMode) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) - checkStrictModeEvalOrArguments(node, node.name); - } - } - function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.flags & 32768 /* 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 === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - function checkStrictModeWithStatement(node) { - // Grammar checking for withStatement - if (inStrictMode) { - errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - function getDestructuringParameterName(node) { - return "__" + ts.indexOf(node.parent.parameters, node); - } - function bind(node) { - if (!node) { - return; - } - node.parent = parent; - var 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 248 /* SourceFile */: - case 219 /* ModuleBlock */: - updateStrictModeStatementList(node.statements); - return; - case 192 /* Block */: - if (ts.isFunctionLike(node.parent)) { - updateStrictModeStatementList(node.statements); - } - return; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - // All classes are automatically in strict mode in ES6. - inStrictMode = true; - return; - } - } - function updateStrictModeStatementList(statements) { - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; - if (!ts.isPrologueDirective(statement)) { - return; - } - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - /// Should be called only on prologue directives (isPrologueDirective(node) should be true) - function isUseStrictPrologueDirective(node) { - var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); - // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the - // string to contain unicode escapes (as per ES5). - return nodeText === "\"use strict\"" || nodeText === "'use strict'"; - } - function bindWorker(node) { - switch (node.kind) { - case 69 /* Identifier */: - return checkStrictModeIdentifier(node); - case 181 /* BinaryExpression */: - return checkStrictModeBinaryExpression(node); - case 244 /* CatchClause */: - return checkStrictModeCatchClause(node); - case 175 /* DeleteExpression */: - return checkStrictModeDeleteExpression(node); - case 8 /* NumericLiteral */: - return checkStrictModeNumericLiteral(node); - case 180 /* PostfixUnaryExpression */: - return checkStrictModePostfixUnaryExpression(node); - case 179 /* PrefixUnaryExpression */: - return checkStrictModePrefixUnaryExpression(node); - case 205 /* WithStatement */: - return checkStrictModeWithStatement(node); - case 97 /* ThisKeyword */: - seenThisKeyword = true; - return; - case 137 /* TypeParameter */: - return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); - case 138 /* Parameter */: - return bindParameter(node); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: - return bindVariableDeclarationOrBindingElement(node); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); - case 245 /* PropertyAssignment */: - case 246 /* ShorthandPropertyAssignment */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); - case 247 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - // If this is an ObjectLiteralExpression method, then it sits in the same space - // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes - // so that it will conflict with any other object literal members with the same - // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); - case 213 /* FunctionDeclaration */: - checkStrictModeFunctionName(node); - return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); - case 144 /* Constructor */: - return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 145 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); - case 146 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - return bindFunctionOrConstructorType(node); - case 155 /* TypeLiteral */: - return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); - case 165 /* ObjectLiteralExpression */: - return bindObjectLiteralExpression(node); - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.text : "__function"; - return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: - return bindClassLikeDeclaration(node); - case 215 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); - case 216 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); - case 217 /* EnumDeclaration */: - return bindEnumDeclaration(node); - case 218 /* ModuleDeclaration */: - return bindModuleDeclaration(node); - case 221 /* ImportEqualsDeclaration */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: - return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - case 223 /* ImportClause */: - return bindImportClause(node); - case 228 /* ExportDeclaration */: - return bindExportDeclaration(node); - case 227 /* ExportAssignment */: - return bindExportAssignment(node); - case 248 /* 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 === 69 /* 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 === 214 /* ClassDeclaration */) { - bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); - } - else { - var bindingName = node.name ? node.name.text : "__class"; - bindAnonymousDeclaration(node, 32 /* Class */, bindingName); - // Add name of class expression into the map for semantic classifier - if (node.name) { - classifiableNames[node.name.text] = node.name.text; - } - } - var symbol = node.symbol; - // TypeScript 1.0 spec (April 2014): 8.4 - // Every class automatically contains a static property member named 'prototype', the - // type of which is an instantiation of the class type with type Any supplied as a type - // argument for each type parameter. It is an error to explicitly declare a static - // property member with the name 'prototype'. - // - // Note: we check for this here because this class may be merging into a module. The - // module might have an exported variable called 'prototype'. We can't allow that as - // that would clash with the built-in 'prototype' for the class. - var prototypeSymbol = createSymbol(4 /* Property */ | 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)); - } - else { - 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 & 56 /* AccessibilityModifier */ && - node.parent.kind === 144 /* Constructor */ && - ts.isClassLike(node.parent.parent)) { - var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); - } - } - function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed") - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - // reachability checks - function pushNamedLabel(name) { - initializeReachabilityStateIfNecessary(); - if (ts.hasProperty(labelIndexMap, name.text)) { - return false; - } - labelIndexMap[name.text] = labelStack.push(1 /* Unintialized */) - 1; - return true; - } - function pushImplicitLabel() { - initializeReachabilityStateIfNecessary(); - var index = labelStack.push(1 /* Unintialized */) - 1; - implicitLabels.push(index); - return index; - } - function popNamedLabel(label, outerState) { - var index = labelIndexMap[label.text]; - ts.Debug.assert(index !== undefined); - ts.Debug.assert(labelStack.length == index + 1); - labelIndexMap[label.text] = undefined; - setCurrentStateAtLabel(labelStack.pop(), outerState, label); - } - function popImplicitLabel(implicitLabelIndex, outerState) { - if (labelStack.length !== implicitLabelIndex + 1) { - ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); - } - var i = implicitLabels.pop(); - if (implicitLabelIndex !== i) { - ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); - } - setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined); - } - function setCurrentStateAtLabel(innerMergedState, outerState, label) { - if (innerMergedState === 1 /* Unintialized */) { - if (label && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); - } - currentReachabilityState = outerState; - } - else { - currentReachabilityState = or(innerMergedState, outerState); - } - } - function jumpToLabel(label, outerState) { - initializeReachabilityStateIfNecessary(); - var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); - if (index === undefined) { - // reference to unknown label or - // break/continue used outside of loops - return false; - } - var stateAtLabel = labelStack[index]; - labelStack[index] = stateAtLabel === 1 /* Unintialized */ ? outerState : or(stateAtLabel, outerState); - return true; - } - function checkUnreachable(node) { - switch (currentReachabilityState) { - case 4 /* Unreachable */: - var reportError = - // report error on all statements - ts.isStatement(node) || - // report error on class declarations - node.kind === 214 /* ClassDeclaration */ || - // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 218 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 217 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); - if (reportError) { - currentReachabilityState = 8 /* ReportedUnreachable */; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 193 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); - } - } - case 8 /* ReportedUnreachable */: - return true; - default: - return false; - } - function shouldReportErrorOnModuleDeclaration(node) { - var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); - } - } - function initializeReachabilityStateIfNecessary() { - if (labelIndexMap) { - return; - } - currentReachabilityState = 2 /* Reachable */; - labelIndexMap = {}; - labelStack = []; - implicitLabels = []; - } - } -})(ts || (ts = {})); -/// /// /* @internal */ var ts; @@ -5513,10 +4579,10 @@ var ts; var stringWriters = []; function getSingleLineStringWriter() { if (stringWriters.length === 0) { - var str = ""; - var writeText = function (text) { return str += text; }; + var str_1 = ""; + var writeText = function (text) { return str_1 += text; }; return { - string: function () { return str; }, + string: function () { return str_1; }, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -5526,10 +4592,10 @@ var ts; writeSymbol: writeText, // Completely ignore indentation for string writers. And map newlines to // a single space. - writeLine: function () { return str += " "; }, + writeLine: function () { return str_1 += " "; }, increaseIndent: function () { }, decreaseIndent: function () { }, - clear: function () { return str = ""; }, + clear: function () { return str_1 = ""; }, trackSymbol: function () { }, reportInaccessibleThisError: function () { } }; @@ -5553,7 +4619,7 @@ var ts; if (array1.length !== array2.length) { return false; } - for (var i = 0; i < array1.length; ++i) { + for (var i = 0; i < array1.length; i++) { var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; if (!equals) { return false; @@ -5580,33 +4646,45 @@ 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.flags & 268435456 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!(node.parserContextFlags & 128 /* HasAggregatedChildData */)) { + if (!(node.flags & 536870912 /* 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. - var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & 16 /* ThisNodeHasError */) !== 0) || + var thisNodeOrAnySubNodesHasError = ((node.flags & 67108864 /* ThisNodeHasError */) !== 0) || ts.forEachChild(node, containsParseError); // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { - node.parserContextFlags |= 64 /* ThisNodeOrAnySubNodesHasError */; + node.flags |= 268435456 /* ThisNodeOrAnySubNodesHasError */; } - // Also mark that we've propogated the child information to this node. This way we can + // Also mark that we've propagated 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.flags |= 536870912 /* HasAggregatedChildData */; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 248 /* SourceFile */) { + while (node && node.kind !== 252 /* SourceFile */) { node = node.parent; } return node; } ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 196 /* Block */: + case 224 /* CaseBlock */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; function getStartPositionOfLine(line, sourceFile) { ts.Debug.assert(line >= 0); return ts.getLineStarts(sourceFile)[line]; @@ -5700,10 +4778,42 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 24576 /* BlockScoped */) !== 0 || + return (getCombinedNodeFlags(declaration) & 3072 /* BlockScoped */) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isAmbientModule(node) { + return node && node.kind === 222 /* ModuleDeclaration */ && + (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isBlockScopedContainerTopLevel(node) { + return node.kind === 252 /* SourceFile */ || + node.kind === 222 /* ModuleDeclaration */ || + isFunctionLike(node) || + isFunctionBlock(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 131072 /* GlobalAugmentation */); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + // external module augmentation is a ambient module declaration that is either: + // - defined in the top level scope and source file is an external module + // - defined inside ambient module declaration located in the top level scope and source file not an external module + if (!node || !isAmbientModule(node)) { + return false; + } + switch (node.parent.kind) { + case 252 /* SourceFile */: + return isExternalModule(node.parent); + case 223 /* ModuleBlock */: + return isAmbientModule(node.parent.parent) && !isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -5713,15 +4823,15 @@ var ts; return current; } switch (current.kind) { - case 248 /* SourceFile */: - case 220 /* CaseBlock */: - case 244 /* CatchClause */: - case 218 /* ModuleDeclaration */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 252 /* SourceFile */: + case 224 /* CaseBlock */: + case 248 /* CatchClause */: + case 222 /* ModuleDeclaration */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: return current; - case 192 /* Block */: + case 196 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block if (!isFunctionLike(current.parent)) { @@ -5734,9 +4844,9 @@ var ts; ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; function isCatchClauseVariableDeclaration(declaration) { return declaration && - declaration.kind === 211 /* VariableDeclaration */ && + declaration.kind === 215 /* VariableDeclaration */ && declaration.parent && - declaration.parent.kind === 244 /* CatchClause */; + declaration.parent.kind === 248 /* CatchClause */; } ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; // Return display name of an identifier @@ -5775,7 +4885,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 248 /* SourceFile */: + case 252 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -5784,16 +4894,20 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 219 /* InterfaceDeclaration */: + case 222 /* ModuleDeclaration */: + case 221 /* EnumDeclaration */: + case 251 /* EnumMember */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 220 /* TypeAliasDeclaration */: errorNode = node.name; break; } @@ -5812,16 +4926,20 @@ var ts; return file.externalModuleIndicator !== undefined; } ts.isExternalModule = isExternalModule; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; function isDeclarationFile(file) { - return (file.flags & 4096 /* DeclarationFile */) !== 0; + return file.isDeclarationFile; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { - return node.kind === 217 /* EnumDeclaration */ && isConst(node); + return node.kind === 221 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 163 /* BindingElement */ || isBindingPattern(node))) { + while (node && (node.kind === 167 /* BindingElement */ || isBindingPattern(node))) { node = node.parent; } return node; @@ -5836,85 +4954,94 @@ var ts; function getCombinedNodeFlags(node) { node = walkUpBindingElementsAndPatterns(node); var flags = node.flags; - if (node.kind === 211 /* VariableDeclaration */) { + if (node.kind === 215 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 212 /* VariableDeclarationList */) { + if (node && node.kind === 216 /* VariableDeclarationList */) { flags |= node.flags; node = node.parent; } - if (node && node.kind === 193 /* VariableStatement */) { + if (node && node.kind === 197 /* VariableStatement */) { flags |= node.flags; } return flags; } ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 16384 /* Const */); + return !!(getCombinedNodeFlags(node) & 2048 /* Const */); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 8192 /* Let */); + return !!(getCombinedNodeFlags(node) & 1024 /* Let */); } ts.isLet = isLet; + function isSuperCallExpression(n) { + return n.kind === 172 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; + } + ts.isSuperCallExpression = isSuperCallExpression; function isPrologueDirective(node) { - return node.kind === 195 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; + return node.kind === 199 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getLeadingCommentRangesOfNodeFromText(node, text) { + return ts.getLeadingCommentRanges(text, node.pos); + } + ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; function getJsDocComments(node, sourceFileOfNode) { - var commentRanges = (node.kind === 138 /* Parameter */ || node.kind === 137 /* TypeParameter */) ? - ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) : - getLeadingCommentRangesOfNode(node, sourceFileOfNode); + return getJsDocCommentsFromText(node, sourceFileOfNode.text); + } + ts.getJsDocComments = getJsDocComments; + function getJsDocCommentsFromText(node, text) { + var commentRanges = (node.kind === 140 /* Parameter */ || node.kind === 139 /* TypeParameter */) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + getLeadingCommentRangesOfNodeFromText(node, text); return ts.filter(commentRanges, isJsDocComment); function isJsDocComment(comment) { // True if the comment starts with '/**' but not if it is '/**/' - return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - sourceFileOfNode.text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && - sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== 47 /* slash */; + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 3) !== 47 /* slash */; } } - ts.getJsDocComments = getJsDocComments; + ts.getJsDocCommentsFromText = getJsDocCommentsFromText; ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; function isTypeNode(node) { - if (151 /* FirstTypeNode */ <= node.kind && node.kind <= 160 /* LastTypeNode */) { + if (152 /* FirstTypeNode */ <= node.kind && node.kind <= 164 /* LastTypeNode */) { return true; } switch (node.kind) { case 117 /* AnyKeyword */: - case 128 /* NumberKeyword */: - case 130 /* StringKeyword */: + case 129 /* NumberKeyword */: + case 131 /* StringKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: return true; case 103 /* VoidKeyword */: - return node.parent.kind !== 177 /* VoidExpression */; - case 9 /* StringLiteral */: - // Specialized signatures can have string literals as their parameters' type names - return node.parent.kind === 138 /* Parameter */; - case 188 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 181 /* VoidExpression */; + case 192 /* 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 69 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 137 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 170 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); - case 135 /* QualifiedName */: - case 166 /* PropertyAccessExpression */: + ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 137 /* QualifiedName */ || node.kind === 170 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + case 137 /* QualifiedName */: + case 170 /* PropertyAccessExpression */: case 97 /* ThisKeyword */: var parent_1 = node.parent; - if (parent_1.kind === 154 /* TypeQuery */) { + if (parent_1.kind === 156 /* TypeQuery */) { return false; } // Do not recursively call isTypeNode on the parent. In the example: @@ -5923,38 +5050,38 @@ var ts; // // Calling isTypeNode would consider the qualified name A.B a type node. Only C or // A.B.C is a type node. - if (151 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 160 /* LastTypeNode */) { + if (152 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 164 /* LastTypeNode */) { return true; } switch (parent_1.kind) { - case 188 /* ExpressionWithTypeArguments */: + case 192 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); - case 137 /* TypeParameter */: + case 139 /* TypeParameter */: return node === parent_1.constraint; - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 138 /* Parameter */: - case 211 /* VariableDeclaration */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 140 /* Parameter */: + case 215 /* VariableDeclaration */: return node === parent_1.type; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 144 /* Constructor */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 146 /* Constructor */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: return node === parent_1.type; - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: return node === parent_1.type; - case 171 /* TypeAssertionExpression */: + case 175 /* TypeAssertionExpression */: return node === parent_1.type; - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; - case 170 /* TaggedTemplateExpression */: + case 174 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -5968,23 +5095,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 204 /* ReturnStatement */: + case 208 /* ReturnStatement */: return visitor(node); - case 220 /* CaseBlock */: - case 192 /* Block */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: + case 224 /* CaseBlock */: + case 196 /* Block */: + case 200 /* IfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 209 /* WithStatement */: + case 210 /* SwitchStatement */: + case 245 /* CaseClause */: + case 246 /* DefaultClause */: + case 211 /* LabeledStatement */: + case 213 /* TryStatement */: + case 248 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -5994,18 +5121,18 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 184 /* YieldExpression */: + case 188 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 221 /* EnumDeclaration */: + case 219 /* InterfaceDeclaration */: + case 222 /* ModuleDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: // 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. @@ -6013,7 +5140,7 @@ var ts; default: if (isFunctionLike(node)) { var name_5 = node.name; - if (name_5 && name_5.kind === 136 /* ComputedPropertyName */) { + if (name_5 && name_5.kind === 138 /* 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_5.expression); @@ -6032,14 +5159,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 163 /* BindingElement */: - case 247 /* EnumMember */: - case 138 /* Parameter */: - case 245 /* PropertyAssignment */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 246 /* ShorthandPropertyAssignment */: - case 211 /* VariableDeclaration */: + case 167 /* BindingElement */: + case 251 /* EnumMember */: + case 140 /* Parameter */: + case 249 /* PropertyAssignment */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 250 /* ShorthandPropertyAssignment */: + case 215 /* VariableDeclaration */: return true; } } @@ -6047,11 +5174,11 @@ var ts; } ts.isVariableLike = isVariableLike; function isAccessor(node) { - return node && (node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */); + return node && (node.kind === 147 /* GetAccessor */ || node.kind === 148 /* SetAccessor */); } ts.isAccessor = isAccessor; function isClassLike(node) { - return node && (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */); + return node && (node.kind === 218 /* ClassDeclaration */ || node.kind === 190 /* ClassExpression */); } ts.isClassLike = isClassLike; function isFunctionLike(node) { @@ -6060,32 +5187,32 @@ var ts; ts.isFunctionLike = isFunctionLike; function isFunctionLikeKind(kind) { switch (kind) { - case 144 /* Constructor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 146 /* Constructor */: + case 177 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: + case 178 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: return true; } } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: return true; } return false; @@ -6093,26 +5220,34 @@ var ts; ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: return true; - case 207 /* LabeledStatement */: + case 211 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; } ts.isIterationStatement = isIterationStatement; function isFunctionBlock(node) { - return node && node.kind === 192 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 196 /* Block */ && isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 143 /* MethodDeclaration */ && node.parent.kind === 165 /* ObjectLiteralExpression */; + return node && node.kind === 145 /* MethodDeclaration */ && node.parent.kind === 169 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0 /* This */; + } + ts.isThisTypePredicate = isThisTypePredicate; function getContainingFunction(node) { while (true) { node = node.parent; @@ -6138,7 +5273,7 @@ var ts; return undefined; } switch (node.kind) { - case 136 /* ComputedPropertyName */: + case 138 /* 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 @@ -6153,9 +5288,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 139 /* Decorator */: + case 141 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 138 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 140 /* 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; @@ -6166,55 +5301,66 @@ var ts; node = node.parent; } break; - case 174 /* ArrowFunction */: + case 178 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // Fall through - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 218 /* ModuleDeclaration */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 217 /* EnumDeclaration */: - case 248 /* SourceFile */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 222 /* ModuleDeclaration */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + case 221 /* EnumDeclaration */: + case 252 /* SourceFile */: return node; } } } ts.getThisContainer = getThisContainer; - function getSuperContainer(node, includeFunctions) { + /** + * Given an super call\property node returns a closest node where either + * - super call\property is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - node is arrow function (so caller might need to call getSuperContainer in case it needs to climb higher) + * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ + function getSuperContainer(node, stopOnFunctions) { while (true) { node = node.parent; - if (!node) + if (!node) { return node; + } switch (node.kind) { - case 136 /* 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 (isClassLike(node.parent.parent)) { - return node; - } - // If this is a computed property, then the parent should not - // make it a super container. The parent might be a property - // in an object literal, like a method or accessor. But in order for - // such a parent to be a super container, the reference must be in - // the *body* of the container. + case 138 /* ComputedPropertyName */: node = node.parent; break; - case 139 /* Decorator */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + return node; + case 141 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 138 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 140 /* 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; @@ -6225,33 +5371,28 @@ var ts; node = node.parent; } break; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - if (!includeFunctions) { - continue; - } - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - return node; } } } ts.getSuperContainer = getSuperContainer; + /** + * Determines whether a node is a property or element access expression for super. + */ + function isSuperPropertyOrElementAccess(node) { + return (node.kind === 170 /* PropertyAccessExpression */ + || node.kind === 171 /* ElementAccessExpression */) + && node.expression.kind === 95 /* SuperKeyword */; + } + ts.isSuperPropertyOrElementAccess = isSuperPropertyOrElementAccess; function getEntityNameFromTypeNode(node) { if (node) { switch (node.kind) { - case 151 /* TypeReference */: + case 153 /* TypeReference */: return node.typeName; - case 188 /* ExpressionWithTypeArguments */: + case 192 /* ExpressionWithTypeArguments */: return node.expression; case 69 /* Identifier */: - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: return node; } } @@ -6259,7 +5400,7 @@ var ts; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 174 /* TaggedTemplateExpression */) { return node.tag; } // Will either be a CallExpression, NewExpression, or Decorator. @@ -6268,73 +5409,40 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node) { switch (node.kind) { - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: // classes are valid targets return true; - case 141 /* PropertyDeclaration */: + case 143 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return node.parent.kind === 214 /* ClassDeclaration */; - case 138 /* 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 === 214 /* ClassDeclaration */; - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 143 /* MethodDeclaration */: + return node.parent.kind === 218 /* ClassDeclaration */; + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 145 /* 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 === 214 /* ClassDeclaration */; + return node.body !== undefined + && node.parent.kind === 218 /* ClassDeclaration */; + case 140 /* 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 !== undefined + && (node.parent.kind === 146 /* Constructor */ + || node.parent.kind === 145 /* MethodDeclaration */ + || node.parent.kind === 148 /* SetAccessor */) + && node.parent.parent.kind === 218 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node) { - switch (node.kind) { - case 214 /* ClassDeclaration */: - if (node.decorators) { - return true; - } - return false; - case 141 /* PropertyDeclaration */: - case 138 /* Parameter */: - if (node.decorators) { - return true; - } - return false; - case 145 /* GetAccessor */: - if (node.body && node.decorators) { - return true; - } - return false; - case 143 /* MethodDeclaration */: - case 146 /* SetAccessor */: - if (node.body && node.decorators) { - return true; - } - return false; - } - return false; + return node.decorators !== undefined + && nodeCanBeDecorated(node); } ts.nodeIsDecorated = nodeIsDecorated; - function childIsDecorated(node) { - switch (node.kind) { - case 214 /* ClassDeclaration */: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 143 /* MethodDeclaration */: - case 146 /* SetAccessor */: - return ts.forEach(node.parameters, nodeIsDecorated); - } - return false; - } - ts.childIsDecorated = childIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); - } - ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function isPropertyAccessExpression(node) { - return node.kind === 166 /* PropertyAccessExpression */; + return node.kind === 170 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 167 /* ElementAccessExpression */; + return node.kind === 171 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isExpression(node) { @@ -6344,42 +5452,42 @@ var ts; case 99 /* TrueKeyword */: case 84 /* FalseKeyword */: case 10 /* RegularExpressionLiteral */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 170 /* TaggedTemplateExpression */: - case 189 /* AsExpression */: - case 171 /* TypeAssertionExpression */: - case 172 /* ParenthesizedExpression */: - case 173 /* FunctionExpression */: - case 186 /* ClassExpression */: - case 174 /* ArrowFunction */: - case 177 /* VoidExpression */: - case 175 /* DeleteExpression */: - case 176 /* TypeOfExpression */: - case 179 /* PrefixUnaryExpression */: - case 180 /* PostfixUnaryExpression */: - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 183 /* TemplateExpression */: + case 168 /* ArrayLiteralExpression */: + case 169 /* ObjectLiteralExpression */: + case 170 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 174 /* TaggedTemplateExpression */: + case 193 /* AsExpression */: + case 175 /* TypeAssertionExpression */: + case 176 /* ParenthesizedExpression */: + case 177 /* FunctionExpression */: + case 190 /* ClassExpression */: + case 178 /* ArrowFunction */: + case 181 /* VoidExpression */: + case 179 /* DeleteExpression */: + case 180 /* TypeOfExpression */: + case 183 /* PrefixUnaryExpression */: + case 184 /* PostfixUnaryExpression */: + case 185 /* BinaryExpression */: + case 186 /* ConditionalExpression */: + case 189 /* SpreadElementExpression */: + case 187 /* TemplateExpression */: case 11 /* NoSubstitutionTemplateLiteral */: - case 187 /* OmittedExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 184 /* YieldExpression */: - case 178 /* AwaitExpression */: + case 191 /* OmittedExpression */: + case 237 /* JsxElement */: + case 238 /* JsxSelfClosingElement */: + case 188 /* YieldExpression */: + case 182 /* AwaitExpression */: return true; - case 135 /* QualifiedName */: - while (node.parent.kind === 135 /* QualifiedName */) { + case 137 /* QualifiedName */: + while (node.parent.kind === 137 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 154 /* TypeQuery */; + return node.parent.kind === 156 /* TypeQuery */; case 69 /* Identifier */: - if (node.parent.kind === 154 /* TypeQuery */) { + if (node.parent.kind === 156 /* TypeQuery */) { return true; } // fall through @@ -6388,47 +5496,47 @@ var ts; case 97 /* ThisKeyword */: var parent_2 = node.parent; switch (parent_2.kind) { - case 211 /* VariableDeclaration */: - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 247 /* EnumMember */: - case 245 /* PropertyAssignment */: - case 163 /* BindingElement */: + case 215 /* VariableDeclaration */: + case 140 /* Parameter */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 251 /* EnumMember */: + case 249 /* PropertyAssignment */: + case 167 /* BindingElement */: return parent_2.initializer === node; - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 204 /* ReturnStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 208 /* ThrowStatement */: - case 206 /* SwitchStatement */: + case 199 /* ExpressionStatement */: + case 200 /* IfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: + case 208 /* ReturnStatement */: + case 209 /* WithStatement */: + case 210 /* SwitchStatement */: + case 245 /* CaseClause */: + case 212 /* ThrowStatement */: + case 210 /* SwitchStatement */: return parent_2.expression === node; - case 199 /* ForStatement */: + case 203 /* ForStatement */: var forStatement = parent_2; - return (forStatement.initializer === node && forStatement.initializer.kind !== 212 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 216 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: var forInStatement = parent_2; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 212 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 216 /* VariableDeclarationList */) || forInStatement.expression === node; - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 175 /* TypeAssertionExpression */: + case 193 /* AsExpression */: return node === parent_2.expression; - case 190 /* TemplateSpan */: + case 194 /* TemplateSpan */: return node === parent_2.expression; - case 136 /* ComputedPropertyName */: + case 138 /* ComputedPropertyName */: return node === parent_2.expression; - case 139 /* Decorator */: - case 240 /* JsxExpression */: - case 239 /* JsxSpreadAttribute */: + case 141 /* Decorator */: + case 244 /* JsxExpression */: + case 243 /* JsxSpreadAttribute */: return true; - case 188 /* ExpressionWithTypeArguments */: + case 192 /* ExpressionWithTypeArguments */: return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); default: if (isExpression(parent_2)) { @@ -6452,7 +5560,7 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */; + return node.kind === 225 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 236 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -6461,34 +5569,94 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 232 /* ExternalModuleReference */; + return node.kind === 225 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 236 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJavaScript(file) { + return isInJavaScriptFile(file); + } + ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isInJavaScriptFile(node) { + return node && !!(node.flags & 134217728 /* JavaScriptFile */); + } + ts.isInJavaScriptFile = isInJavaScriptFile; + /** + * Returns true if the node is a CallExpression to the identifier 'require' with + * exactly one argument. + * This function does not test if the node is in a JavaScript file or not. + */ + function isRequireCall(expression, checkArgumentIsStringLiteral) { + // of the form 'require("name")' + var isRequire = expression.kind === 172 /* CallExpression */ && + expression.expression.kind === 69 /* Identifier */ && + expression.expression.text === "require" && + expression.arguments.length === 1; + return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9 /* StringLiteral */); + } + ts.isRequireCall = isRequireCall; + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getSpecialPropertyAssignmentKind(expression) { + if (expression.kind !== 185 /* BinaryExpression */) { + return 0 /* None */; + } + var expr = expression; + if (expr.operatorToken.kind !== 56 /* EqualsToken */ || expr.left.kind !== 170 /* PropertyAccessExpression */) { + return 0 /* None */; + } + var lhs = expr.left; + if (lhs.expression.kind === 69 /* Identifier */) { + var lhsId = lhs.expression; + if (lhsId.text === "exports") { + // exports.name = expr + return 1 /* ExportsProperty */; + } + else if (lhsId.text === "module" && lhs.name.text === "exports") { + // module.exports = expr + return 2 /* ModuleExports */; + } + } + else if (lhs.expression.kind === 97 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } + else if (lhs.expression.kind === 170 /* PropertyAccessExpression */) { + // chained dot, e.g. x.y.z = expr; this var is the 'x.y' part + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 69 /* Identifier */ && innerPropertyAccess.name.text === "prototype") { + return 3 /* PrototypeProperty */; + } + } + return 0 /* None */; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; function getExternalModuleName(node) { - if (node.kind === 222 /* ImportDeclaration */) { + if (node.kind === 226 /* ImportDeclaration */) { return node.moduleSpecifier; } - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 225 /* ImportEqualsDeclaration */) { var reference = node.moduleReference; - if (reference.kind === 232 /* ExternalModuleReference */) { + if (reference.kind === 236 /* ExternalModuleReference */) { return reference.expression; } } - if (node.kind === 228 /* ExportDeclaration */) { + if (node.kind === 232 /* ExportDeclaration */) { return node.moduleSpecifier; } + if (node.kind === 222 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { + return node.name; + } } ts.getExternalModuleName = getExternalModuleName; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 138 /* Parameter */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 246 /* ShorthandPropertyAssignment */: - case 245 /* PropertyAssignment */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 140 /* Parameter */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 250 /* ShorthandPropertyAssignment */: + case 249 /* PropertyAssignment */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -6496,31 +5664,70 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 261 /* JSDocFunctionType */ && + return node.kind === 265 /* JSDocFunctionType */ && node.parameters.length > 0 && - node.parameters[0].type.kind === 263 /* JSDocConstructorType */; + node.parameters[0].type.kind === 267 /* JSDocConstructorType */; } 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 getJSDocTag(node, kind, checkParentVariableStatement) { + if (!node) { + return undefined; + } + var jsDocComment = getJSDocComment(node, checkParentVariableStatement); + if (!jsDocComment) { + return undefined; + } + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === kind) { + return tag; } } } + function getJSDocComment(node, checkParentVariableStatement) { + if (node.jsDocComment) { + return node.jsDocComment; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + if (checkParentVariableStatement) { + var isInitializerOfVariableDeclarationInStatement = node.parent.kind === 215 /* VariableDeclaration */ && + node.parent.initializer === node && + node.parent.parent.parent.kind === 197 /* VariableStatement */; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined; + if (variableStatementNode) { + return variableStatementNode.jsDocComment; + } + // Also recognize when the node is the RHS of an assignment expression + var parent_3 = node.parent; + var isSourceOfAssignmentExpressionStatement = parent_3 && parent_3.parent && + parent_3.kind === 185 /* BinaryExpression */ && + parent_3.operatorToken.kind === 56 /* EqualsToken */ && + parent_3.parent.kind === 199 /* ExpressionStatement */; + if (isSourceOfAssignmentExpressionStatement) { + return parent_3.parent.jsDocComment; + } + var isPropertyAssignmentExpression = parent_3 && parent_3.kind === 249 /* PropertyAssignment */; + if (isPropertyAssignmentExpression) { + return parent_3.jsDocComment; + } + } + return undefined; + } function getJSDocTypeTag(node) { - return getJSDocTag(node, 269 /* JSDocTypeTag */); + return getJSDocTag(node, 273 /* JSDocTypeTag */, /*checkParentVariableStatement*/ false); } ts.getJSDocTypeTag = getJSDocTypeTag; function getJSDocReturnTag(node) { - return getJSDocTag(node, 268 /* JSDocReturnTag */); + return getJSDocTag(node, 272 /* JSDocReturnTag */, /*checkParentVariableStatement*/ true); } ts.getJSDocReturnTag = getJSDocReturnTag; function getJSDocTemplateTag(node) { - return getJSDocTag(node, 270 /* JSDocTemplateTag */); + return getJSDocTag(node, 274 /* JSDocTemplateTag */, /*checkParentVariableStatement*/ false); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function getCorrespondingJSDocParameterTag(parameter) { @@ -6528,19 +5735,21 @@ var ts; // 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 === 267 /* JSDocParameterTag */) { - var parameterTag = t; + var jsDocComment = getJSDocComment(parameter.parent, /*checkParentVariableStatement*/ true); + if (jsDocComment) { + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === 271 /* JSDocParameterTag */) { + var parameterTag = tag; var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; if (name_6.text === parameterName) { - return t; + return parameterTag; } } - }); + } } } + return undefined; } ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; function hasRestParameter(s) { @@ -6549,13 +5758,13 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { if (node) { - if (node.parserContextFlags & 32 /* JavaScriptFile */) { - if (node.type && node.type.kind === 262 /* JSDocVariadicType */) { + if (node.flags & 134217728 /* JavaScriptFile */) { + if (node.type && node.type.kind === 266 /* JSDocVariadicType */) { return true; } var paramTag = getCorrespondingJSDocParameterTag(node); if (paramTag && paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 262 /* JSDocVariadicType */; + return paramTag.typeExpression.type.kind === 266 /* JSDocVariadicType */; } } return node.dotDotDotToken !== undefined; @@ -6576,7 +5785,7 @@ var ts; } ts.isTemplateLiteralKind = isTemplateLiteralKind; function isBindingPattern(node) { - return !!node && (node.kind === 162 /* ArrayBindingPattern */ || node.kind === 161 /* ObjectBindingPattern */); + return !!node && (node.kind === 166 /* ArrayBindingPattern */ || node.kind === 165 /* ObjectBindingPattern */); } ts.isBindingPattern = isBindingPattern; function isNodeDescendentOf(node, ancestor) { @@ -6590,7 +5799,7 @@ var ts; ts.isNodeDescendentOf = isNodeDescendentOf; function isInAmbientContext(node) { while (node) { - if (node.flags & (4 /* Ambient */ | 4096 /* DeclarationFile */)) { + if (node.flags & 2 /* Ambient */ || (node.kind === 252 /* SourceFile */ && node.isDeclarationFile)) { return true; } node = node.parent; @@ -6600,34 +5809,34 @@ var ts; ts.isInAmbientContext = isInAmbientContext; function isDeclaration(node) { switch (node.kind) { - case 174 /* ArrowFunction */: - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 144 /* Constructor */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 230 /* ExportSpecifier */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 145 /* GetAccessor */: - case 223 /* ImportClause */: - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 215 /* InterfaceDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 218 /* ModuleDeclaration */: - case 224 /* NamespaceImport */: - case 138 /* Parameter */: - case 245 /* PropertyAssignment */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 146 /* SetAccessor */: - case 246 /* ShorthandPropertyAssignment */: - case 216 /* TypeAliasDeclaration */: - case 137 /* TypeParameter */: - case 211 /* VariableDeclaration */: + case 178 /* ArrowFunction */: + case 167 /* BindingElement */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 146 /* Constructor */: + case 221 /* EnumDeclaration */: + case 251 /* EnumMember */: + case 234 /* ExportSpecifier */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 147 /* GetAccessor */: + case 227 /* ImportClause */: + case 225 /* ImportEqualsDeclaration */: + case 230 /* ImportSpecifier */: + case 219 /* InterfaceDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 222 /* ModuleDeclaration */: + case 228 /* NamespaceImport */: + case 140 /* Parameter */: + case 249 /* PropertyAssignment */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 148 /* SetAccessor */: + case 250 /* ShorthandPropertyAssignment */: + case 220 /* TypeAliasDeclaration */: + case 139 /* TypeParameter */: + case 215 /* VariableDeclaration */: return true; } return false; @@ -6635,25 +5844,25 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: - case 210 /* DebuggerStatement */: - case 197 /* DoStatement */: - case 195 /* ExpressionStatement */: - case 194 /* EmptyStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 196 /* IfStatement */: - case 207 /* LabeledStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 193 /* VariableStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 227 /* ExportAssignment */: + case 207 /* BreakStatement */: + case 206 /* ContinueStatement */: + case 214 /* DebuggerStatement */: + case 201 /* DoStatement */: + case 199 /* ExpressionStatement */: + case 198 /* EmptyStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 203 /* ForStatement */: + case 200 /* IfStatement */: + case 211 /* LabeledStatement */: + case 208 /* ReturnStatement */: + case 210 /* SwitchStatement */: + case 212 /* ThrowStatement */: + case 213 /* TryStatement */: + case 197 /* VariableStatement */: + case 202 /* WhileStatement */: + case 209 /* WithStatement */: + case 231 /* ExportAssignment */: return true; default: return false; @@ -6662,13 +5871,13 @@ var ts; ts.isStatement = isStatement; function isClassElement(n) { switch (n.kind) { - case 144 /* Constructor */: - case 141 /* PropertyDeclaration */: - case 143 /* MethodDeclaration */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 142 /* MethodSignature */: - case 149 /* IndexSignature */: + case 146 /* Constructor */: + case 143 /* PropertyDeclaration */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 144 /* MethodSignature */: + case 151 /* IndexSignature */: return true; default: return false; @@ -6681,7 +5890,7 @@ var ts; return false; } var parent = name.parent; - if (parent.kind === 226 /* ImportSpecifier */ || parent.kind === 230 /* ExportSpecifier */) { + if (parent.kind === 230 /* ImportSpecifier */ || parent.kind === 234 /* ExportSpecifier */) { if (parent.propertyName) { return true; } @@ -6696,31 +5905,31 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 247 /* EnumMember */: - case 245 /* PropertyAssignment */: - case 166 /* PropertyAccessExpression */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 251 /* EnumMember */: + case 249 /* PropertyAssignment */: + case 170 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: // Name on right hand side of dot in a type query if (parent.right === node) { - while (parent.kind === 135 /* QualifiedName */) { + while (parent.kind === 137 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 154 /* TypeQuery */; + return parent.kind === 156 /* TypeQuery */; } return false; - case 163 /* BindingElement */: - case 226 /* ImportSpecifier */: + case 167 /* BindingElement */: + case 230 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 230 /* ExportSpecifier */: + case 234 /* ExportSpecifier */: // Any name in an export specifier return true; } @@ -6736,12 +5945,12 @@ var ts; // export = ... // export default ... function isAliasSymbolDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ || - node.kind === 223 /* ImportClause */ && !!node.name || - node.kind === 224 /* NamespaceImport */ || - node.kind === 226 /* ImportSpecifier */ || - node.kind === 230 /* ExportSpecifier */ || - node.kind === 227 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; + return node.kind === 225 /* ImportEqualsDeclaration */ || + node.kind === 227 /* ImportClause */ && !!node.name || + node.kind === 228 /* NamespaceImport */ || + node.kind === 230 /* ImportSpecifier */ || + node.kind === 234 /* ExportSpecifier */ || + node.kind === 231 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getClassExtendsHeritageClauseElement(node) { @@ -6791,8 +6000,8 @@ var ts; function getFileReferenceFromReferencePath(comment, commentRange) { var simpleReferenceRegEx = /^\/\/\/\s*/gim; - if (simpleReferenceRegEx.exec(comment)) { - if (isNoDefaultLibRegEx.exec(comment)) { + if (simpleReferenceRegEx.test(comment)) { + if (isNoDefaultLibRegEx.test(comment)) { return { isNoDefaultLib: true }; @@ -6823,7 +6032,7 @@ var ts; } ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; function isKeyword(token) { - return 70 /* FirstKeyword */ <= token && token <= 134 /* LastKeyword */; + return 70 /* FirstKeyword */ <= token && token <= 136 /* LastKeyword */; } ts.isKeyword = isKeyword; function isTrivia(token) { @@ -6834,6 +6043,10 @@ var ts; return isFunctionLike(node) && (node.flags & 256 /* Async */) !== 0 && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; + function isStringOrNumericLiteral(kind) { + return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */; + } + ts.isStringOrNumericLiteral = isStringOrNumericLiteral; /** * A declaration has a dynamic name if both of the following are true: * 1. The declaration has a computed property name @@ -6842,11 +6055,15 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - return declaration.name && - declaration.name.kind === 136 /* ComputedPropertyName */ && - !isWellKnownSymbolSyntactically(declaration.name.expression); + return declaration.name && isDynamicName(declaration.name); } ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 138 /* ComputedPropertyName */ && + !isStringOrNumericLiteral(name.expression.kind) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; /** * Checks if the expression is of the form: * Symbol.name @@ -6860,7 +6077,7 @@ var ts; if (name.kind === 69 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { return name.text; } - if (name.kind === 136 /* ComputedPropertyName */) { + if (name.kind === 138 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { var rightHandSideName = nameExpression.name.text; @@ -6881,7 +6098,7 @@ var ts; return node.kind === 69 /* Identifier */ && node.text === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; - function isModifier(token) { + function isModifierKind(token) { switch (token) { case 115 /* AbstractKeyword */: case 118 /* AsyncKeyword */: @@ -6892,44 +6109,79 @@ var ts; case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: + case 127 /* ReadonlyKeyword */: case 113 /* StaticKeyword */: return true; } return false; } - ts.isModifier = isModifier; + ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 138 /* Parameter */; + return root.kind === 140 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 163 /* BindingElement */) { + while (node.kind === 167 /* BindingElement */) { node = node.parent.parent; } return node; } ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(n) { - return isFunctionLike(n) || n.kind === 218 /* ModuleDeclaration */ || n.kind === 248 /* SourceFile */; + return isFunctionLike(n) || n.kind === 222 /* ModuleDeclaration */ || n.kind === 252 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function cloneEntityName(node) { - if (node.kind === 69 /* Identifier */) { - var clone_1 = createSynthesizedNode(69 /* Identifier */); - clone_1.text = node.text; - return clone_1; + /** + * Creates a shallow, memberwise clone of a node. The "kind", "pos", "end", "flags", and "parent" + * properties are excluded by default, and can be provided via the "location", "flags", and + * "parent" parameters. + * @param node The node to clone. + * @param location An optional TextRange to use to supply the new position. + * @param flags The NodeFlags to use for the cloned node. + * @param parent The parent for the new node. + */ + function cloneNode(node, location, flags, parent) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + var clone = location !== undefined + ? ts.createNode(node.kind, location.pos, location.end) + : createSynthesizedNode(node.kind); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; } - else { - var clone_2 = createSynthesizedNode(135 /* QualifiedName */); - clone_2.left = cloneEntityName(node.left); - clone_2.left.parent = clone_2; - clone_2.right = cloneEntityName(node.right); - clone_2.right.parent = clone_2; - return clone_2; + if (flags !== undefined) { + clone.flags = flags; } + if (parent !== undefined) { + clone.parent = parent; + } + return clone; + } + ts.cloneNode = cloneNode; + /** + * Creates a deep clone of an EntityName, with new parent pointers. + * @param node The EntityName to clone. + * @param parent The parent for the cloned node. + */ + function cloneEntityName(node, parent) { + var clone = cloneNode(node, node, node.flags, parent); + if (isQualifiedName(clone)) { + var left = clone.left, right = clone.right; + clone.left = cloneEntityName(left, clone); + clone.right = cloneNode(right, right, right.flags, parent); + } + return clone; } ts.cloneEntityName = cloneEntityName; + function isQualifiedName(node) { + return node.kind === 137 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; function nodeIsSynthesized(node) { return node.pos === -1; } @@ -7087,11 +6339,11 @@ var ts; } ts.getIndentSize = getIndentSize; function createTextWriter(newLine) { - var output = ""; - var indent = 0; - var lineStart = true; - var lineCount = 0; - var linePos = 0; + var output; + var indent; + var lineStart; + var lineCount; + var linePos; function write(s) { if (s && s.length) { if (lineStart) { @@ -7101,6 +6353,13 @@ var ts; output += s; } } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } function rawWrite(s) { if (s !== undefined) { if (lineStart) { @@ -7127,25 +6386,38 @@ var ts; lineStart = true; } } - function writeTextOfNode(sourceFile, node) { - write(getSourceTextOfNodeFromSourceFile(sourceFile, node)); + function writeTextOfNode(text, node) { + write(getTextOfNodeFromSourceText(text, node)); } + reset(); return { write: write, rawWrite: rawWrite, writeTextOfNode: writeTextOfNode, writeLiteral: writeLiteral, writeLine: writeLine, - increaseIndent: function () { return indent++; }, - decreaseIndent: function () { return indent--; }, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, getLine: function () { return lineCount + 1; }, getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, - getText: function () { return output; } + getText: function () { return output; }, + reset: reset }; } ts.createTextWriter = createTextWriter; + /** + * Resolves a local path to a path which is absolute to the base of the emit + */ + function getExternalModuleNameFromPath(host, fileName) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.removeFileExtension(relativePath); + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; function getOwnEmitOutputFilePath(sourceFile, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; @@ -7158,6 +6430,78 @@ var ts; return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { + var options = host.getCompilerOptions(); + // Emit on each source file + if (options.outFile || options.out) { + onBundledEmit(host); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + if (!isDeclarationFile(sourceFile)) { + onSingleFileEmit(host, sourceFile); + } + } + } + function onSingleFileEmit(host, sourceFile) { + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + var extension = ".js"; + if (options.jsx === 1 /* Preserve */) { + if (isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + extension = ".jsx"; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + extension = ".jsx"; + } + } + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined + }; + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + } + function onBundledEmit(host) { + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + (!isExternalModule(sourceFile) || + (getEmitModuleKind(options) && isExternalModule(sourceFile))); }); // module that can emit - note falsy value from getEmitModuleKind means the module kind that shouldn't be emitted + if (bundledSources.length) { + var jsFilePath = options.outFile || options.out; + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options) + }; + action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + } + } + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getDeclarationEmitFilePath(jsFilePath, options) { + return options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; + } + } + ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); @@ -7166,7 +6510,7 @@ var ts; ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }); } ts.writeFile = writeFile; @@ -7174,9 +6518,13 @@ var ts; return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { return ts.forEach(node.members, function (member) { - if (member.kind === 144 /* Constructor */ && nodeIsPresent(member.body)) { + if (member.kind === 146 /* Constructor */ && nodeIsPresent(member.body)) { return member; } }); @@ -7186,18 +6534,6 @@ var ts; return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; - function shouldEmitToOwnFile(sourceFile, compilerOptions) { - if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) { - // 1. in-browser single file compilation scenario - // 2. non .js file - return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); - } - return false; - } - return false; - } - ts.shouldEmitToOwnFile = shouldEmitToOwnFile; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -7205,10 +6541,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 145 /* GetAccessor */) { + if (accessor.kind === 147 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 146 /* SetAccessor */) { + else if (accessor.kind === 148 /* SetAccessor */) { setAccessor = accessor; } else { @@ -7217,8 +6553,8 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) - && (member.flags & 64 /* Static */) === (accessor.flags & 64 /* Static */)) { + if ((member.kind === 147 /* GetAccessor */ || member.kind === 148 /* SetAccessor */) + && (member.flags & 32 /* Static */) === (accessor.flags & 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -7228,10 +6564,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 145 /* GetAccessor */ && !getAccessor) { + if (member.kind === 147 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 146 /* SetAccessor */ && !setAccessor) { + if (member.kind === 148 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -7246,22 +6582,22 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) { + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { // If the leading comments start on different line than the start of node, write new line if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && - getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) { + getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { writer.writeLine(); } } ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; - function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) { + function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) { var emitLeadingSpace = !trailingSeparator; ts.forEach(comments, function (comment) { if (emitLeadingSpace) { writer.write(" "); emitLeadingSpace = false; } - writeComment(currentSourceFile, writer, comment, newLine); + writeComment(text, lineMap, writer, comment, newLine); if (comment.hasTrailingNewLine) { writer.writeLine(); } @@ -7279,7 +6615,7 @@ var ts; * Detached comment is a comment at the top of file or function body that is separated from * the next statement by space. */ - function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) { + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { var leadingComments; var currentDetachedCommentInfo; if (removeComments) { @@ -7289,21 +6625,21 @@ var ts; // // var x = 10; if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment); + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); } } else { // removeComments is false, just get detached as normal and bypass the process to filter comment - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + leadingComments = ts.getLeadingCommentRanges(text, node.pos); } if (leadingComments) { var detachedComments = []; - var lastComment; + var lastComment = void 0; for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { var comment = leadingComments_1[_i]; if (lastComment) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); if (commentLine >= lastCommentLine + 2) { // There was a blank line between the last comment and this comment. This // comment is not part of the copyright comments. Return what we have so @@ -7318,36 +6654,36 @@ var ts; // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); - var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } } return currentDetachedCommentInfo; function isPinnedComment(comment) { - return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; } } ts.emitDetachedComments = emitDetachedComments; - function writeCommentRange(currentSourceFile, writer, comment, newLine) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { - var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos); - var lineCount = ts.getLineStarts(currentSourceFile).length; - var firstCommentLineIndent; + function writeCommentRange(text, lineMap, writer, comment, newLine) { + if (text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { var nextLineStart = (currentLine + 1) === lineCount - ? currentSourceFile.text.length + 1 - : getStartPositionOfLine(currentLine + 1, currentSourceFile); + ? text.length + 1 + : lineMap[currentLine + 1]; if (pos !== comment.pos) { // If we are not emitting first line, we need to write the spaces to adjust the alignment if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos); + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos); } // These are number of spaces writer is going to write at current indent var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); @@ -7365,7 +6701,7 @@ var ts; // More right indented comment */ --4 = 8 - 4 + 11 // class c { } // } - var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); if (spacesToEmit > 0) { var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); @@ -7383,57 +6719,58 @@ var ts; } } // Write the comment line text - writeTrimmedCurrentLine(pos, nextLineStart); + writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart); pos = nextLineStart; } } else { // Single line comment of style //.... - writer.write(currentSourceFile.text.substring(comment.pos, comment.end)); - } - function writeTrimmedCurrentLine(pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); - var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ""); - if (currentLineText) { - // trimmed forward and ending spaces text - writer.write(currentLineText); - if (end !== comment.end) { - writer.writeLine(); - } - } - else { - // Empty string - make sure we write empty line - writer.writeLiteral(newLine); - } - } - function calculateIndent(pos, end) { - var currentLineIndent = 0; - for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) { - if (currentSourceFile.text.charCodeAt(pos) === 9 /* tab */) { - // Tabs = TabSize = indent size and go to next tabStop - currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); - } - else { - // Single space - currentLineIndent++; - } - } - return currentLineIndent; + writer.write(text.substring(comment.pos, comment.end)); } } ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) { + var end = Math.min(comment.end, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + // trimmed forward and ending spaces text + writer.write(currentLineText); + if (end !== comment.end) { + writer.writeLine(); + } + } + else { + // Empty string - make sure we write empty line + writer.writeLiteral(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpace(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9 /* tab */) { + // Tabs = TabSize = indent size and go to next tabStop + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + // Single space + currentLineIndent++; + } + } + return currentLineIndent; + } function modifierToFlag(token) { switch (token) { - case 113 /* StaticKeyword */: return 64 /* Static */; - case 112 /* PublicKeyword */: return 8 /* Public */; - case 111 /* ProtectedKeyword */: return 32 /* Protected */; - case 110 /* PrivateKeyword */: return 16 /* Private */; + case 113 /* StaticKeyword */: return 32 /* Static */; + case 112 /* PublicKeyword */: return 4 /* Public */; + case 111 /* ProtectedKeyword */: return 16 /* Protected */; + case 110 /* PrivateKeyword */: return 8 /* Private */; case 115 /* AbstractKeyword */: return 128 /* Abstract */; - case 82 /* ExportKeyword */: return 2 /* Export */; - case 122 /* DeclareKeyword */: return 4 /* Ambient */; - case 74 /* ConstKeyword */: return 16384 /* Const */; + case 82 /* ExportKeyword */: return 1 /* Export */; + case 122 /* DeclareKeyword */: return 2 /* Ambient */; + case 74 /* ConstKeyword */: return 2048 /* Const */; case 77 /* DefaultKeyword */: return 512 /* Default */; case 118 /* AsyncKeyword */: return 256 /* Async */; + case 127 /* ReadonlyKeyword */: return 64 /* Readonly */; } return 0; } @@ -7441,24 +6778,24 @@ var ts; function isLeftHandSideExpression(expr) { if (expr) { switch (expr.kind) { - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 169 /* NewExpression */: - case 168 /* CallExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 170 /* TaggedTemplateExpression */: - case 164 /* ArrayLiteralExpression */: - case 172 /* ParenthesizedExpression */: - case 165 /* ObjectLiteralExpression */: - case 186 /* ClassExpression */: - case 173 /* FunctionExpression */: + case 170 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: + case 173 /* NewExpression */: + case 172 /* CallExpression */: + case 237 /* JsxElement */: + case 238 /* JsxSelfClosingElement */: + case 174 /* TaggedTemplateExpression */: + case 168 /* ArrayLiteralExpression */: + case 176 /* ParenthesizedExpression */: + case 169 /* ObjectLiteralExpression */: + case 190 /* ClassExpression */: + case 177 /* FunctionExpression */: case 69 /* Identifier */: case 10 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 11 /* NoSubstitutionTemplateLiteral */: - case 183 /* TemplateExpression */: + case 187 /* TemplateExpression */: case 84 /* FalseKeyword */: case 93 /* NullKeyword */: case 97 /* ThisKeyword */: @@ -7475,7 +6812,7 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return node.kind === 188 /* ExpressionWithTypeArguments */ && + return node.kind === 192 /* ExpressionWithTypeArguments */ && node.parent.token === 83 /* ExtendsKeyword */ && isClassLike(node.parent.parent); } @@ -7498,16 +6835,16 @@ var ts; } } function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 137 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 170 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteralOrArrayLiteral(expression) { var kind = expression.kind; - if (kind === 165 /* ObjectLiteralExpression */) { + if (kind === 169 /* ObjectLiteralExpression */) { return expression.properties.length === 0; } - if (kind === 164 /* ArrayLiteralExpression */) { + if (kind === 168 /* ArrayLiteralExpression */) { return expression.elements.length === 0; } return false; @@ -7517,14 +6854,10 @@ var ts; return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function isJavaScript(fileName) { - return ts.fileExtensionIs(fileName, ".js"); + function hasJavaScriptFileExtension(fileName) { + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.isJavaScript = isJavaScript; - function isTsx(fileName) { - return ts.fileExtensionIs(fileName, ".tsx"); - } - ts.isTsx = isTsx; + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; /** * 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. @@ -7559,6 +6892,47 @@ var ts; } return output; } + /** + * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph + * as the fallback implementation does not check for circular references by default. + */ + ts.stringify = typeof JSON !== "undefined" && JSON.stringify + ? JSON.stringify + : stringifyFallback; + /** + * Serialize an object graph into a JSON string. + */ + function stringifyFallback(value) { + // JSON.stringify returns `undefined` here, instead of the string "undefined". + return value === undefined ? undefined : stringifyValue(value); + } + function stringifyValue(value) { + return typeof value === "string" ? "\"" + escapeString(value) + "\"" + : typeof value === "number" ? isFinite(value) ? String(value) : "null" + : typeof value === "boolean" ? value ? "true" : "false" + : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) + : "null"; + } + function cycleCheck(cb, value) { + ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); + value.__cycle = true; + var result = cb(value); + delete value.__cycle; + return result; + } + function stringifyArray(value) { + return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; + } + function stringifyElement(memo, value) { + return (memo ? memo + "," : memo) + stringifyValue(value); + } + function stringifyObject(value) { + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; + } + function stringifyProperty(memo, value, key) { + return value === undefined || typeof value === "function" || key === "__cycle" ? memo + : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); + } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** * Converts a string to a base-64 encoded ASCII string. @@ -7584,7 +6958,7 @@ var ts; else if (i + 2 >= length) { byte4 = 64; } - // Write to the ouput + // Write to the output result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); i += 3; } @@ -7770,9 +7144,9 @@ var ts; // . | \ // ----------------------------------------------------------------------*-------------------------------- // - // (Note the dots represent the newly inferrred start. + // (Note the dots represent the newly inferred start. // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the - // absolute positions at the asterixes, and the relative change between the dollar signs. Basically, we see + // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that // means: // @@ -7795,8 +7169,8 @@ var ts; // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started // that's the same as if we started at char 80 instead of 60. // - // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter - // than pusing the first edit forward to match the second, we'll push the second edit forward to match the + // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rather + // than pushing the first edit forward to match the second, we'll push the second edit forward to match the // first. // // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange @@ -7825,28 +7199,34 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 137 /* TypeParameter */) { + if (d && d.kind === 139 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 215 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 219 /* InterfaceDeclaration */) { return current; } } } } ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return node.flags & 28 /* AccessibilityModifier */ && node.parent.kind === 146 /* Constructor */ && ts.isClassLike(node.parent.parent); + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; })(ts || (ts = {})); -/// /// +/// var ts; (function (ts) { - var nodeConstructors = new Array(272 /* Count */); /* @internal */ ts.parseTime = 0; - function getNodeConstructor(kind) { - return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); - } - ts.getNodeConstructor = getNodeConstructor; + var NodeConstructor; + var SourceFileConstructor; function createNode(kind, pos, end) { - return new (getNodeConstructor(kind))(pos, end); + if (kind === 252 /* SourceFile */) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } } ts.createNode = createNode; function visitNode(cbNode, node) { @@ -7884,26 +7264,26 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 137 /* TypeParameter */: + case 139 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 246 /* ShorthandPropertyAssignment */: + case 250 /* ShorthandPropertyAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 140 /* Parameter */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 249 /* PropertyAssignment */: + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -7912,24 +7292,24 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNodes(cbNodes, node.typeParameters) || visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 177 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: + case 178 /* ArrowFunction */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -7940,302 +7320,319 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 151 /* TypeReference */: + case 153 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 150 /* TypePredicate */: + case 152 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 154 /* TypeQuery */: + case 156 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 155 /* TypeLiteral */: + case 157 /* TypeLiteral */: return visitNodes(cbNodes, node.members); - case 156 /* ArrayType */: + case 158 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 157 /* TupleType */: + case 159 /* TupleType */: return visitNodes(cbNodes, node.elementTypes); - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 160 /* UnionType */: + case 161 /* IntersectionType */: return visitNodes(cbNodes, node.types); - case 160 /* ParenthesizedType */: + case 162 /* ParenthesizedType */: return visitNode(cbNode, node.type); - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: + case 165 /* ObjectBindingPattern */: + case 166 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return visitNodes(cbNodes, node.elements); - case 165 /* ObjectLiteralExpression */: + case 169 /* ObjectLiteralExpression */: return visitNodes(cbNodes, node.properties); - case 166 /* PropertyAccessExpression */: + case 170 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 167 /* ElementAccessExpression */: + case 171 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 170 /* TaggedTemplateExpression */: + case 174 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 171 /* TypeAssertionExpression */: + case 175 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 175 /* DeleteExpression */: + case 179 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 176 /* TypeOfExpression */: + case 180 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 177 /* VoidExpression */: + case 181 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 184 /* YieldExpression */: + case 188 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 178 /* AwaitExpression */: + case 182 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 180 /* PostfixUnaryExpression */: + case 184 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 189 /* AsExpression */: + case 193 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 185 /* SpreadElementExpression */: + case 189 /* SpreadElementExpression */: return visitNode(cbNode, node.expression); - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 196 /* Block */: + case 223 /* ModuleBlock */: return visitNodes(cbNodes, node.statements); - case 248 /* SourceFile */: + case 252 /* SourceFile */: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 212 /* VariableDeclarationList */: + case 216 /* VariableDeclarationList */: return visitNodes(cbNodes, node.declarations); - case 195 /* ExpressionStatement */: + case 199 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 196 /* IfStatement */: + case 200 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 197 /* DoStatement */: + case 201 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 198 /* WhileStatement */: + case 202 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 199 /* ForStatement */: + case 203 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 200 /* ForInStatement */: + case 204 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 201 /* ForOfStatement */: + case 205 /* ForOfStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 206 /* ContinueStatement */: + case 207 /* BreakStatement */: return visitNode(cbNode, node.label); - case 204 /* ReturnStatement */: + case 208 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 205 /* WithStatement */: + case 209 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 206 /* SwitchStatement */: + case 210 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 220 /* CaseBlock */: + case 224 /* CaseBlock */: return visitNodes(cbNodes, node.clauses); - case 241 /* CaseClause */: + case 245 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 242 /* DefaultClause */: + case 246 /* DefaultClause */: return visitNodes(cbNodes, node.statements); - case 207 /* LabeledStatement */: + case 211 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 208 /* ThrowStatement */: + case 212 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 209 /* TryStatement */: + case 213 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 244 /* CatchClause */: + case 248 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 139 /* Decorator */: + case 141 /* Decorator */: return visitNode(cbNode, node.expression); - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 218 /* ClassDeclaration */: + case 190 /* 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 215 /* InterfaceDeclaration */: + case 219 /* 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 216 /* TypeAliasDeclaration */: + case 220 /* TypeAliasDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.members); - case 247 /* EnumMember */: + case 251 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 223 /* ImportClause */: + case 227 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 224 /* NamespaceImport */: + case 228 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 225 /* NamedImports */: - case 229 /* NamedExports */: + case 229 /* NamedImports */: + case 233 /* NamedExports */: return visitNodes(cbNodes, node.elements); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 230 /* ImportSpecifier */: + case 234 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 183 /* TemplateExpression */: + case 187 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 190 /* TemplateSpan */: + case 194 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 136 /* ComputedPropertyName */: + case 138 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 243 /* HeritageClause */: + case 247 /* HeritageClause */: return visitNodes(cbNodes, node.types); - case 188 /* ExpressionWithTypeArguments */: + case 192 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 232 /* ExternalModuleReference */: + case 236 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 231 /* MissingDeclaration */: + case 235 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); - case 233 /* JsxElement */: + case 237 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 234 /* JsxSelfClosingElement */: - case 235 /* JsxOpeningElement */: + case 238 /* JsxSelfClosingElement */: + case 239 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 238 /* JsxAttribute */: + case 242 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 239 /* JsxSpreadAttribute */: + case 243 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 240 /* JsxExpression */: + case 244 /* JsxExpression */: return visitNode(cbNode, node.expression); - case 237 /* JsxClosingElement */: + case 241 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 249 /* JSDocTypeExpression */: + case 253 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 253 /* JSDocUnionType */: + case 257 /* JSDocUnionType */: return visitNodes(cbNodes, node.types); - case 254 /* JSDocTupleType */: + case 258 /* JSDocTupleType */: return visitNodes(cbNodes, node.types); - case 252 /* JSDocArrayType */: + case 256 /* JSDocArrayType */: return visitNode(cbNode, node.elementType); - case 256 /* JSDocNonNullableType */: + case 260 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 255 /* JSDocNullableType */: + case 259 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 257 /* JSDocRecordType */: + case 261 /* JSDocRecordType */: return visitNodes(cbNodes, node.members); - case 259 /* JSDocTypeReference */: + case 263 /* JSDocTypeReference */: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); - case 260 /* JSDocOptionalType */: + case 264 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 261 /* JSDocFunctionType */: + case 265 /* JSDocFunctionType */: return visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 262 /* JSDocVariadicType */: + case 266 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 263 /* JSDocConstructorType */: + case 267 /* JSDocConstructorType */: return visitNode(cbNode, node.type); - case 264 /* JSDocThisType */: + case 268 /* JSDocThisType */: return visitNode(cbNode, node.type); - case 258 /* JSDocRecordMember */: + case 262 /* JSDocRecordMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 265 /* JSDocComment */: + case 269 /* JSDocComment */: return visitNodes(cbNodes, node.tags); - case 267 /* JSDocParameterTag */: + case 271 /* JSDocParameterTag */: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 268 /* JSDocReturnTag */: + case 272 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 269 /* JSDocTypeTag */: + case 273 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 270 /* JSDocTemplateTag */: + case 274 /* JSDocTemplateTag */: return visitNodes(cbNodes, node.typeParameters); } } ts.forEachChild = forEachChild; - function createSourceFile(fileName, sourceText, languageVersion, setParentNodes) { + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } var start = new Date().getTime(); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); ts.parseTime += new Date().getTime() - start; return result; } ts.createSourceFile = createSourceFile; + /* @internal */ + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js": + return 1 /* JS */; + case ".jsx": + return 2 /* JSX */; + case ".ts": + return 3 /* TS */; + case ".tsx": + return 4 /* TSX */; + default: + return 3 /* TS */; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter // indicates what changed between the 'text' that this SourceFile has and the 'newText'. // The SourceFile will be created with the compiler attempting to reuse as many nodes from @@ -8268,7 +7665,10 @@ var ts; // Share a single scanner across all calls to parse a source file. This helps speed things // up by avoiding the cost of creating/compiling scanners over and over again. var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); - var disallowInAndDecoratorContext = 1 /* DisallowIn */ | 4 /* Decorator */; + var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */; + // capture constructors in 'initializeState' to avoid null checks + var NodeConstructor; + var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; @@ -8353,14 +7753,26 @@ var ts; // Note: any errors at the end of the file that do not precede a regular node, should get // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) { - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); - var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes, scriptKind) { + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then attempt + // to get the ScriptKind from the file name. + scriptKind = scriptKind ? scriptKind : getScriptKindFromFileName(fileName); + initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); return result; } Parser.parseSourceFile = parseSourceFile; - function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) { + function getLanguageVariant(scriptKind) { + // .tsx and .jsx files are treated as jsx language variant. + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ ? 1 /* JSX */ : 0 /* Standard */; + } + function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; @@ -8368,27 +7780,28 @@ var ts; identifiers = {}; identifierCount = 0; nodeCount = 0; - contextFlags = ts.isJavaScript(fileName) ? 32 /* JavaScriptFile */ : 0 /* None */; + contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 134217728 /* JavaScriptFile */ : 0 /* None */; parseErrorBeforeNextFinishedNode = false; // Initialize and prime the scanner before parsing the source elements. scanner.setText(sourceText); scanner.setOnError(scanError); scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(ts.isTsx(fileName) ? 1 /* JSX */ : 0 /* Standard */); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); } function clearState() { // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. scanner.setText(""); scanner.setOnError(undefined); - // Clear any data. We don't want to accidently hold onto it for too long. + // Clear any data. We don't want to accidentally hold onto it for too long. parseDiagnostics = undefined; sourceFile = undefined; identifiers = undefined; syntaxCursor = undefined; sourceText = undefined; } - function parseSourceFileWorker(fileName, languageVersion, setParentNodes) { - sourceFile = createSourceFile(fileName, languageVersion); + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + sourceFile.flags = contextFlags; // Prime the scanner. token = nextToken(); processReferenceComments(sourceFile); @@ -8403,40 +7816,22 @@ var ts; if (setParentNodes) { fixupParentReferences(sourceFile); } - // 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 193 /* VariableStatement */: - case 213 /* FunctionDeclaration */: - case 138 /* Parameter */: - addJSDocComment(node); - } - forEachChild(node, visit); - } - } function addJSDocComment(node) { - var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); - if (comments) { - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var comment = comments_1[_i]; - var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (jsDocComment) { - node.jsDocComment = jsDocComment; + if (contextFlags & 134217728 /* JavaScriptFile */) { + var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); + if (comments) { + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (jsDocComment) { + node.jsDocComment = jsDocComment; + } } } } + return node; } function fixupParentReferences(sourceFile) { // normally parent references are set during binding. However, for clients that only need @@ -8460,16 +7855,18 @@ var ts; } } Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion) { - var sourceFile = createNode(248 /* SourceFile */, /*pos*/ 0); - sourceFile.pos = 0; - sourceFile.end = sourceText.length; + function createSourceFile(fileName, languageVersion, scriptKind) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(252 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 /* DeclarationFile */ : 0; - sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */; + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.scriptKind = scriptKind; return sourceFile; } function setContextFlag(val, flag) { @@ -8481,16 +7878,16 @@ var ts; } } function setDisallowInContext(val) { - setContextFlag(val, 1 /* DisallowIn */); + setContextFlag(val, 4194304 /* DisallowInContext */); } function setYieldContext(val) { - setContextFlag(val, 2 /* Yield */); + setContextFlag(val, 8388608 /* YieldContext */); } function setDecoratorContext(val) { - setContextFlag(val, 4 /* Decorator */); + setContextFlag(val, 16777216 /* DecoratorContext */); } function setAwaitContext(val) { - setContextFlag(val, 8 /* Await */); + setContextFlag(val, 33554432 /* AwaitContext */); } function doOutsideOfContext(context, func) { // contextFlagsToClear will contain only the context flags that are @@ -8502,10 +7899,10 @@ var ts; var contextFlagsToClear = context & contextFlags; if (contextFlagsToClear) { // clear the requested context flags - setContextFlag(false, contextFlagsToClear); + setContextFlag(/*val*/ false, contextFlagsToClear); var result = func(); // restore the context flags we just cleared - setContextFlag(true, contextFlagsToClear); + setContextFlag(/*val*/ true, contextFlagsToClear); return result; } // no need to do anything special as we are not in any of the requested contexts @@ -8521,56 +7918,50 @@ var ts; var contextFlagsToSet = context & ~contextFlags; if (contextFlagsToSet) { // set the requested context flags - setContextFlag(true, contextFlagsToSet); + setContextFlag(/*val*/ true, contextFlagsToSet); var result = func(); // reset the context flags we just set - setContextFlag(false, contextFlagsToSet); + setContextFlag(/*val*/ false, contextFlagsToSet); return result; } // no need to do anything special as we are already in all of the requested contexts return func(); } function allowInAnd(func) { - return doOutsideOfContext(1 /* DisallowIn */, func); + return doOutsideOfContext(4194304 /* DisallowInContext */, func); } function disallowInAnd(func) { - return doInsideOfContext(1 /* DisallowIn */, func); + return doInsideOfContext(4194304 /* DisallowInContext */, func); } function doInYieldContext(func) { - return doInsideOfContext(2 /* Yield */, func); - } - function doOutsideOfYieldContext(func) { - return doOutsideOfContext(2 /* Yield */, func); + return doInsideOfContext(8388608 /* YieldContext */, func); } function doInDecoratorContext(func) { - return doInsideOfContext(4 /* Decorator */, func); + return doInsideOfContext(16777216 /* DecoratorContext */, func); } function doInAwaitContext(func) { - return doInsideOfContext(8 /* Await */, func); + return doInsideOfContext(33554432 /* AwaitContext */, func); } function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(8 /* Await */, func); + return doOutsideOfContext(33554432 /* AwaitContext */, func); } function doInYieldAndAwaitContext(func) { - return doInsideOfContext(2 /* Yield */ | 8 /* Await */, func); - } - function doOutsideOfYieldAndAwaitContext(func) { - return doOutsideOfContext(2 /* Yield */ | 8 /* Await */, func); + return doInsideOfContext(8388608 /* YieldContext */ | 33554432 /* AwaitContext */, func); } function inContext(flags) { return (contextFlags & flags) !== 0; } function inYieldContext() { - return inContext(2 /* Yield */); + return inContext(8388608 /* YieldContext */); } function inDisallowInContext() { - return inContext(1 /* DisallowIn */); + return inContext(4194304 /* DisallowInContext */); } function inDecoratorContext() { - return inContext(4 /* Decorator */); + return inContext(16777216 /* DecoratorContext */); } function inAwaitContext() { - return inContext(8 /* Await */); + return inContext(33554432 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { var start = scanner.getTokenPos(); @@ -8600,9 +7991,6 @@ var ts; function nextToken() { return token = scanner.scan(); } - function getTokenPos(pos) { - return ts.skipTrivia(sourceText, pos); - } function reScanGreaterToken() { return token = scanner.reScanGreaterToken(); } @@ -8645,16 +8033,18 @@ var ts; } return result; } - // Invokes the provided callback then unconditionally restores the parser to the state it - // was in immediately prior to invoking the callback. The result of invoking the callback - // is returned from this function. + /** Invokes the provided callback then unconditionally restores the parser to the state it + * was in immediately prior to invoking the callback. The result of invoking the callback + * is returned from this function. + */ function lookAhead(callback) { return speculationHelper(callback, /*isLookAhead*/ true); } - // Invokes the provided callback. If the callback returns something falsy, then it restores - // the parser to the state it was in immediately prior to invoking the callback. If the - // callback returns something truthy, then the parser state is not rolled back. The result - // of invoking the callback is returned from this function. + /** Invokes the provided callback. If the callback returns something falsy, then it restores + * the parser to the state it was in immediately prior to invoking the callback. If the + * callback returns something truthy, then the parser state is not rolled back. The result + * of invoking the callback is returned from this function. + */ function tryParse(callback) { return speculationHelper(callback, /*isLookAhead*/ false); } @@ -8734,24 +8124,25 @@ var ts; return parseExpected(23 /* SemicolonToken */); } } + // note: this function creates only node function createNode(kind, pos) { nodeCount++; if (!(pos >= 0)) { pos = scanner.getStartPos(); } - return new (nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)))(pos, pos); + return new NodeConstructor(kind, pos, pos); } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; if (contextFlags) { - node.parserContextFlags = contextFlags; + node.flags |= contextFlags; } // Keep track on the node if we encountered an error while parsing it. If we did, then // we cannot reuse the node incrementally. Once we've marked this node, clear out the // flag so that we don't mark any subsequent nodes. if (parseErrorBeforeNextFinishedNode) { parseErrorBeforeNextFinishedNode = false; - node.parserContextFlags |= 16 /* ThisNodeHasError */; + node.flags |= 67108864 /* ThisNodeHasError */; } return node; } @@ -8808,10 +8199,10 @@ var ts; return parseIdentifierName(); } function parsePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ true); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); } function parseSimplePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ false); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); } function isSimplePropertyName() { return token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token); @@ -8820,7 +8211,7 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(136 /* ComputedPropertyName */); + var node = createNode(138 /* ComputedPropertyName */); parseExpected(19 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker @@ -8832,6 +8223,13 @@ var ts; function parseContextualModifier(t) { return token === t && tryParse(nextTokenCanFollowModifier); } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } function nextTokenCanFollowModifier() { if (token === 74 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. @@ -8851,14 +8249,10 @@ var ts; nextToken(); return canFollowModifier(); } - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); + return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifier(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { return token === 19 /* OpenBracketToken */ @@ -8890,7 +8284,7 @@ var ts; case 2 /* SwitchClauses */: return token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; case 4 /* TypeMembers */: - return isStartOfTypeMember(); + return lookAhead(isTypeMemberStart); case 5 /* ClassMembers */: // We allow semicolons as class elements (as specified by ES6) as long as we're // not in error recovery. If we're in error recovery, we don't want an errant @@ -8904,7 +8298,7 @@ var ts; case 12 /* ObjectLiteralMembers */: return token === 19 /* OpenBracketToken */ || token === 37 /* AsteriskToken */ || isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return isLiteralPropertyName(); + return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); case 7 /* HeritageClauseElement */: // If we see { } then only consume it as an expression if it is followed by , or { // That way we won't consume the body of a class in its heritage clause. @@ -9064,7 +8458,7 @@ var ts; function isInSomeParsingContext() { for (var kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & (1 << kind)) { - if (isListElement(kind, /* inErrorRecovery */ true) || isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; } } @@ -9078,7 +8472,7 @@ var ts; var result = []; result.pos = getNodePos(); while (!isListTerminator(kind)) { - if (isListElement(kind, /* inErrorRecovery */ false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); result.push(element); continue; @@ -9130,20 +8524,20 @@ var ts; // We can only reuse a node if it was parsed under the same strict mode that we're // currently in. i.e. if we originally parsed a node in non-strict mode, but then // the user added 'using strict' at the top of the file, then we can't use that node - // again as the presense of strict mode may cause us to parse the tokens in the file - // differetly. + // again as the presence of strict mode may cause us to parse the tokens in the file + // differently. // // Note: we *can* reuse tokens when the strict mode changes. That's because tokens // are unaffected by strict mode. It's just the parser will decide what to do with it // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.parserContextFlags & 31 /* ParserGeneratedFlags */; + var nodeContextFlags = node.flags & 62914560 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } // Ok, we have a node that looks like it could be reused. Now verify that it is valid - // in the currest list parsing context that we're currently at. + // in the current list parsing context that we're currently at. if (!canReuseNode(node, parsingContext)) { return undefined; } @@ -9218,14 +8612,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 144 /* Constructor */: - case 149 /* IndexSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 141 /* PropertyDeclaration */: - case 191 /* SemicolonClassElement */: + case 146 /* Constructor */: + case 151 /* IndexSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 143 /* PropertyDeclaration */: + case 195 /* SemicolonClassElement */: return true; - case 143 /* MethodDeclaration */: + case 145 /* 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. @@ -9240,8 +8634,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 245 /* CaseClause */: + case 246 /* DefaultClause */: return true; } } @@ -9250,58 +8644,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 193 /* VariableStatement */: - case 192 /* Block */: - case 196 /* IfStatement */: - case 195 /* ExpressionStatement */: - case 208 /* ThrowStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 194 /* EmptyStatement */: - case 209 /* TryStatement */: - case 207 /* LabeledStatement */: - case 197 /* DoStatement */: - case 210 /* DebuggerStatement */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: - case 227 /* ExportAssignment */: - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 217 /* FunctionDeclaration */: + case 197 /* VariableStatement */: + case 196 /* Block */: + case 200 /* IfStatement */: + case 199 /* ExpressionStatement */: + case 212 /* ThrowStatement */: + case 208 /* ReturnStatement */: + case 210 /* SwitchStatement */: + case 207 /* BreakStatement */: + case 206 /* ContinueStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 203 /* ForStatement */: + case 202 /* WhileStatement */: + case 209 /* WithStatement */: + case 198 /* EmptyStatement */: + case 213 /* TryStatement */: + case 211 /* LabeledStatement */: + case 201 /* DoStatement */: + case 214 /* DebuggerStatement */: + case 226 /* ImportDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 232 /* ExportDeclaration */: + case 231 /* ExportAssignment */: + case 222 /* ModuleDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 220 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 247 /* EnumMember */; + return node.kind === 251 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 148 /* ConstructSignature */: - case 142 /* MethodSignature */: - case 149 /* IndexSignature */: - case 140 /* PropertySignature */: - case 147 /* CallSignature */: + case 150 /* ConstructSignature */: + case 144 /* MethodSignature */: + case 151 /* IndexSignature */: + case 142 /* PropertySignature */: + case 149 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 211 /* VariableDeclaration */) { + if (node.kind !== 215 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -9322,7 +8716,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 138 /* Parameter */) { + if (node.kind !== 140 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -9370,14 +8764,14 @@ var ts; } ; // Parses a comma-delimited list of elements - function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimeter) { + function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; var result = []; result.pos = getNodePos(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { - if (isListElement(kind, /* inErrorRecovery */ false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(24 /* CommaToken */)) { @@ -9395,7 +8789,7 @@ var ts; // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. - if (considerSemicolonAsDelimeter && token === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { + if (considerSemicolonAsDelimiter && token === 23 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); } continue; @@ -9439,7 +8833,7 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); while (parseOptional(21 /* DotToken */)) { - var node = createNode(135 /* QualifiedName */, entity.pos); + var node = createNode(137 /* QualifiedName */, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -9472,14 +8866,14 @@ var ts; // Report that we need an identifier. However, report it right after the dot, // and not on the next token. This is because the next token might actually // be an identifier and the error would be quite confusing. - return createMissingNode(69 /* Identifier */, /*reportAtCurrentToken*/ true, ts.Diagnostics.Identifier_expected); + return createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(183 /* TemplateExpression */); - template.head = parseLiteralNode(); + var template = createNode(187 /* TemplateExpression */); + template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = []; templateSpans.pos = getNodePos(); @@ -9491,12 +8885,12 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(190 /* TemplateSpan */); + var span = createNode(194 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token === 16 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseLiteralNode(); + literal = parseTemplateLiteralFragment(); } else { literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); @@ -9504,8 +8898,17 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(164 /* StringLiteralType */, /*internName*/ true); + } function parseLiteralNode(internName) { - var node = createNode(token); + return parseLiteralLikeNode(token, internName); + } + function parseTemplateLiteralFragment() { + return parseLiteralLikeNode(token, /*internName*/ false); + } + function parseLiteralLikeNode(kind, internName) { + var node = createNode(kind); var text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -9526,35 +8929,40 @@ var ts; if (node.kind === 8 /* NumericLiteral */ && sourceText.charCodeAt(tokenPos) === 48 /* _0 */ && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - node.flags |= 32768 /* OctalLiteral */; + node.isOctalLiteral = true; } return node; } // TYPES - function parseTypeReferenceOrTypePredicate() { + function parseTypeReference() { var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); - if (typeName.kind === 69 /* Identifier */ && token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var node_1 = createNode(150 /* TypePredicate */, typeName.pos); - node_1.parameterName = typeName; - node_1.type = parseType(); - return finishNode(node_1); - } - var node = createNode(151 /* TypeReference */, typeName.pos); + var node = createNode(153 /* TypeReference */, typeName.pos); node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); } return finishNode(node); } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(152 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(163 /* ThisType */); + nextToken(); + return finishNode(node); + } function parseTypeQuery() { - var node = createNode(154 /* TypeQuery */); + var node = createNode(156 /* TypeQuery */); parseExpected(101 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(137 /* TypeParameter */); + var node = createNode(139 /* TypeParameter */); node.name = parseIdentifier(); if (parseOptional(83 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -9584,14 +8992,12 @@ var ts; } function parseParameterType() { if (parseOptional(54 /* ColonToken */)) { - return token === 9 /* StringLiteral */ - ? parseLiteralNode(/*internName*/ true) - : parseType(); + return parseType(); } return undefined; } function isStartOfParameter() { - return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifier(token) || token === 55 /* AtToken */; + return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */; } function setModifiers(node, modifiers) { if (modifiers) { @@ -9600,14 +9006,14 @@ var ts; } } function parseParameter() { - var node = createNode(138 /* Parameter */); + var node = createNode(140 /* Parameter */); node.decorators = parseDecorators(); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifier(token)) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { // in cases like // 'use strict' // function foo(static) @@ -9629,7 +9035,7 @@ var ts; // contexts. In addition, parameter initializers are semantically disallowed in // overload signatures. So parameter initializers are transitively disallowed in // ambient contexts. - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseBindingElementInitializer(inParameter) { return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); @@ -9643,10 +9049,10 @@ var ts; signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); if (returnTokenRequired) { parseExpected(returnToken); - signature.type = parseType(); + signature.type = parseTypeOrTypePredicate(); } else if (parseOptional(returnToken)) { - signature.type = parseType(); + signature.type = parseTypeOrTypePredicate(); } } function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { @@ -9694,7 +9100,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 148 /* ConstructSignature */) { + if (kind === 150 /* ConstructSignature */) { parseExpected(92 /* NewKeyword */); } fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); @@ -9728,7 +9134,7 @@ var ts; if (token === 22 /* DotDotDotToken */ || token === 20 /* CloseBracketToken */) { return true; } - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -9758,7 +9164,7 @@ var ts; return token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 20 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(149 /* IndexSignature */, fullStart); + var node = createNode(151 /* IndexSignature */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); @@ -9766,109 +9172,87 @@ var ts; parseTypeMemberSemicolon(); return finishNode(node); } - function parsePropertyOrMethodSignature() { - var fullStart = scanner.getStartPos(); + function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); var questionToken = parseOptionalToken(53 /* QuestionToken */); if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { - var method = createNode(142 /* MethodSignature */, fullStart); + var method = createNode(144 /* MethodSignature */, fullStart); + setModifiers(method, modifiers); method.name = name; method.questionToken = questionToken; - // Method signatues don't exist in expression contexts. So they have neither + // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); parseTypeMemberSemicolon(); return finishNode(method); } else { - var property = createNode(140 /* PropertySignature */, fullStart); + var property = createNode(142 /* PropertySignature */, fullStart); + setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); + if (token === 56 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + property.initializer = parseNonParameterInitializer(); + } parseTypeMemberSemicolon(); return finishNode(property); } } - function isStartOfTypeMember() { - switch (token) { - case 17 /* OpenParenToken */: - case 25 /* LessThanToken */: - case 19 /* OpenBracketToken */: - return true; - default: - if (ts.isModifier(token)) { - var result = lookAhead(isStartOfIndexSignatureDeclaration); - if (result) { - return result; - } - } - return isLiteralPropertyName() && lookAhead(isTypeMemberWithLiteralPropertyName); + function isTypeMemberStart() { + var idToken; + // Return true if we have the start of a signature member + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + return true; } - } - function isStartOfIndexSignatureDeclaration() { - while (ts.isModifier(token)) { + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier + while (ts.isModifierKind(token)) { + idToken = token; nextToken(); } - return isIndexSignature(); - } - function isTypeMemberWithLiteralPropertyName() { - nextToken(); - return token === 17 /* OpenParenToken */ || - token === 25 /* LessThanToken */ || - token === 53 /* QuestionToken */ || - token === 54 /* ColonToken */ || - canParseSemicolon(); + // Index signatures and computed property names are type members + if (token === 19 /* OpenBracketToken */) { + return true; + } + // Try to get the first property-like token following all modifiers + if (isLiteralPropertyName()) { + idToken = token; + nextToken(); + } + // If we were able to get any potential identifier, check that it is + // the start of a member declaration + if (idToken) { + return token === 17 /* OpenParenToken */ || + token === 25 /* LessThanToken */ || + token === 53 /* QuestionToken */ || + token === 54 /* ColonToken */ || + canParseSemicolon(); + } + return false; } function parseTypeMember() { - switch (token) { - case 17 /* OpenParenToken */: - case 25 /* LessThanToken */: - return parseSignatureMember(147 /* CallSignature */); - case 19 /* OpenBracketToken */: - // Indexer or computed property - return isIndexSignature() - ? parseIndexSignatureDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined) - : parsePropertyOrMethodSignature(); - case 92 /* NewKeyword */: - if (lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(148 /* ConstructSignature */); - } - // fall through. - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - return parsePropertyOrMethodSignature(); - default: - // Index declaration as allowed as a type member. But as per the grammar, - // they also allow modifiers. So we have to check for an index declaration - // that might be following modifiers. This ensures that things work properly - // when incrementally parsing as the parser will produce the Index declaration - // if it has the same text regardless of whether it is inside a class or an - // object type. - if (ts.isModifier(token)) { - var result = tryParse(parseIndexSignatureWithModifiers); - if (result) { - return result; - } - } - if (ts.tokenIsIdentifierOrKeyword(token)) { - return parsePropertyOrMethodSignature(); - } + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + return parseSignatureMember(149 /* CallSignature */); } - } - function parseIndexSignatureWithModifiers() { - var fullStart = scanner.getStartPos(); - var decorators = parseDecorators(); + if (token === 92 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { + return parseSignatureMember(150 /* ConstructSignature */); + } + var fullStart = getNodePos(); var modifiers = parseModifiers(); - return isIndexSignature() - ? parseIndexSignatureDeclaration(fullStart, decorators, modifiers) - : undefined; + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, /*decorators*/ undefined, modifiers); + } + return parsePropertyOrMethodSignature(fullStart, modifiers); } function isStartOfConstructSignature() { nextToken(); return token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */; } function parseTypeLiteral() { - var node = createNode(155 /* TypeLiteral */); + var node = createNode(157 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -9884,12 +9268,12 @@ var ts; return members; } function parseTupleType() { - var node = createNode(157 /* TupleType */); + var node = createNode(159 /* TupleType */); node.elementTypes = parseBracketedList(19 /* TupleElementTypes */, parseType, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(160 /* ParenthesizedType */); + var node = createNode(162 /* ParenthesizedType */); parseExpected(17 /* OpenParenToken */); node.type = parseType(); parseExpected(18 /* CloseParenToken */); @@ -9897,7 +9281,7 @@ var ts; } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 153 /* ConstructorType */) { + if (kind === 155 /* ConstructorType */) { parseExpected(92 /* NewKeyword */); } fillSignature(34 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); @@ -9910,16 +9294,26 @@ var ts; function parseNonArrayType() { switch (token) { case 117 /* AnyKeyword */: - case 130 /* StringKeyword */: - case 128 /* NumberKeyword */: + case 131 /* StringKeyword */: + case 129 /* NumberKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: // If these are followed by a dot, then parse these out as a dotted type reference instead. var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReferenceOrTypePredicate(); + return node || parseTypeReference(); + case 9 /* StringLiteral */: + return parseStringLiteralTypeNode(); case 103 /* VoidKeyword */: - case 97 /* ThisKeyword */: return parseTokenNode(); + case 97 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } case 101 /* TypeOfKeyword */: return parseTypeQuery(); case 15 /* OpenBraceToken */: @@ -9929,16 +9323,16 @@ var ts; case 17 /* OpenParenToken */: return parseParenthesizedType(); default: - return parseTypeReferenceOrTypePredicate(); + return parseTypeReference(); } } function isStartOfType() { switch (token) { case 117 /* AnyKeyword */: - case 130 /* StringKeyword */: - case 128 /* NumberKeyword */: + case 131 /* StringKeyword */: + case 129 /* NumberKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: case 103 /* VoidKeyword */: case 97 /* ThisKeyword */: case 101 /* TypeOfKeyword */: @@ -9946,6 +9340,7 @@ var ts; case 19 /* OpenBracketToken */: case 25 /* LessThanToken */: case 92 /* NewKeyword */: + case 9 /* StringLiteral */: return true; case 17 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, @@ -9963,7 +9358,7 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(19 /* OpenBracketToken */)) { parseExpected(20 /* CloseBracketToken */); - var node = createNode(156 /* ArrayType */, type.pos); + var node = createNode(158 /* ArrayType */, type.pos); node.elementType = type; type = finishNode(node); } @@ -9985,10 +9380,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(159 /* IntersectionType */, parseArrayTypeOrHigher, 46 /* AmpersandToken */); + return parseUnionOrIntersectionType(161 /* IntersectionType */, parseArrayTypeOrHigher, 46 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(158 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); + return parseUnionOrIntersectionType(160 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); } function isStartOfFunctionType() { if (token === 25 /* LessThanToken */) { @@ -9996,6 +9391,23 @@ var ts; } return token === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); } + function skipParameterStart() { + if (ts.isModifierKind(token)) { + // Skip modifiers + parseModifiers(); + } + if (isIdentifier()) { + nextToken(); + return true; + } + if (token === 19 /* OpenBracketToken */ || token === 15 /* OpenBraceToken */) { + // Return true if we can parse an array or object binding pattern with no errors + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } function isUnambiguouslyStartOfFunctionType() { nextToken(); if (token === 18 /* CloseParenToken */ || token === 22 /* DotDotDotToken */) { @@ -10003,39 +9415,58 @@ var ts; // ( ... return true; } - if (isIdentifier() || ts.isModifier(token)) { - nextToken(); + if (skipParameterStart()) { + // We successfully skipped modifiers (if any) and an identifier or binding pattern, + // now see if we have something that indicates a parameter declaration if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || - token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */ || - isIdentifier() || ts.isModifier(token)) { - // ( id : - // ( id , - // ( id ? - // ( id = - // ( modifier id + token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */) { + // ( xxx : + // ( xxx , + // ( xxx ? + // ( xxx = return true; } if (token === 18 /* CloseParenToken */) { nextToken(); if (token === 34 /* EqualsGreaterThanToken */) { - // ( id ) => + // ( xxx ) => return true; } } } return false; } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(152 /* TypePredicate */, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } function parseType() { // The rules about 'yield' only apply to actual code/expression contexts. They don't // apply to 'type' contexts. So we disable these parameters here before moving on. - return doOutsideOfContext(10 /* TypeExcludesFlags */, parseTypeWorker); + return doOutsideOfContext(41943040 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(152 /* FunctionType */); + return parseFunctionOrConstructorType(154 /* FunctionType */); } if (token === 92 /* NewKeyword */) { - return parseFunctionOrConstructorType(153 /* ConstructorType */); + return parseFunctionOrConstructorType(155 /* ConstructorType */); } return parseUnionTypeOrHigher(); } @@ -10108,9 +9539,6 @@ var ts; token !== 55 /* AtToken */ && isStartOfExpression(); } - function allowInAndParseExpression() { - return allowInAnd(parseExpression); - } function parseExpression() { // Expression[in]: // AssignmentExpression[in] @@ -10118,7 +9546,7 @@ var ts; // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; @@ -10126,7 +9554,7 @@ var ts; expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } return expr; } @@ -10203,7 +9631,7 @@ var ts; } function isYieldExpression() { if (token === 114 /* YieldKeyword */) { - // If we have a 'yield' keyword, and htis is a context where yield expressions are + // If we have a 'yield' keyword, and this is a context where yield expressions are // allowed, then definitely parse out a yield expression. if (inYieldContext()) { return true; @@ -10221,7 +9649,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. + // don't accidentally consume something legal. return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); } return false; @@ -10231,7 +9659,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(184 /* YieldExpression */); + var node = createNode(188 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -10245,20 +9673,20 @@ var ts; } else { // if the next token is not on the same line as yield. or we don't have an '*' or - // the start of an expressin, then this is just a simple "yield" expression. + // the start of an expression, then this is just a simple "yield" expression. return finishNode(node); } } function parseSimpleArrowFunctionExpression(identifier) { ts.Debug.assert(token === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(174 /* ArrowFunction */, identifier.pos); - var parameter = createNode(138 /* Parameter */, identifier.pos); + var node = createNode(178 /* ArrowFunction */, identifier.pos); + var parameter = createNode(140 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = [parameter]; node.parameters.pos = parameter.pos; node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, false, ts.Diagnostics._0_expected, "=>"); + node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ false); return finishNode(node); } @@ -10404,7 +9832,7 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(174 /* ArrowFunction */); + var node = createNode(178 /* ArrowFunction */); setModifiers(node, parseModifiersForArrowFunction()); var isAsync = !!(node.flags & 256 /* Async */); // Arrow functions are never generators. @@ -10470,7 +9898,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(182 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(186 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -10483,7 +9911,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 90 /* InKeyword */ || t === 134 /* OfKeyword */; + return t === 90 /* InKeyword */ || t === 136 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -10494,7 +9922,7 @@ var ts; // Check the precedence to see if we should "take" this operator // - For left associative operator (all operator but **), consume the operator, // recursively call the function below, and parse binaryExpression as a rightOperand - // of the caller if the new precendence of the operator is greater then or equal to the current precendence. + // of the caller if the new precedence of the operator is greater then or equal to the current precedence. // For example: // a - b - c; // ^token; leftOperand = b. Return b to the caller as a rightOperand @@ -10503,8 +9931,8 @@ var ts; // a - b * c; // ^token; leftOperand = b. Return b * c to the caller as a rightOperand // - For right associative operator (**), consume the operator, recursively call the function - // and parse binaryExpression as a rightOperand of the caller if the new precendence of - // the operator is strictly grater than the current precendence + // and parse binaryExpression as a rightOperand of the caller if the new precedence of + // the operator is strictly grater than the current precedence // For example: // a ** b ** c; // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand @@ -10591,39 +10019,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(181 /* BinaryExpression */, left.pos); + var node = createNode(185 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(189 /* AsExpression */, left.pos); + var node = createNode(193 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(179 /* PrefixUnaryExpression */); + var node = createNode(183 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(175 /* DeleteExpression */); + var node = createNode(179 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(176 /* TypeOfExpression */); + var node = createNode(180 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(177 /* VoidExpression */); + var node = createNode(181 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -10639,7 +10067,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(178 /* AwaitExpression */); + var node = createNode(182 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -10664,9 +10092,8 @@ var ts; var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === 38 /* AsteriskAsteriskToken */) { - var diagnostic; var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 171 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 175 /* TypeAssertionExpression */) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -10722,7 +10149,7 @@ var ts; */ function isIncrementExpression() { // This function is called inside parseUnaryExpression to decide - // whether to call parseSimpleUnaryExpression or call parseIncrmentExpression directly + // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly switch (token) { case 35 /* PlusToken */: case 36 /* MinusToken */: @@ -10756,7 +10183,7 @@ var ts; */ function parseIncrementExpression() { if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { - var node = createNode(179 /* PrefixUnaryExpression */); + var node = createNode(183 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -10769,7 +10196,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(180 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(184 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -10873,24 +10300,37 @@ 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(166 /* PropertyAccessExpression */, expression.pos); + var node = createNode(170 /* PropertyAccessExpression */, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 69 /* Identifier */) { + return lhs.text === rhs.text; + } + return lhs.right.text === rhs.right.text && + tagNamesAreEquivalent(lhs.left, rhs.left); + } function parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); var result; - if (opening.kind === 235 /* JsxOpeningElement */) { - var node = createNode(233 /* JsxElement */, opening.pos); + if (opening.kind === 239 /* JsxOpeningElement */) { + var node = createNode(237 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 238 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -10905,7 +10345,7 @@ var ts; var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(181 /* BinaryExpression */, result.pos); + var badNode = createNode(185 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -10917,13 +10357,13 @@ var ts; return result; } function parseJsxText() { - var node = createNode(236 /* JsxText */, scanner.getStartPos()); + var node = createNode(240 /* JsxText */, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token) { - case 236 /* JsxText */: + case 240 /* JsxText */: return parseJsxText(); case 15 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); @@ -10940,10 +10380,13 @@ var ts; while (true) { token = scanner.reScanJsxToken(); if (token === 26 /* LessThanSlashToken */) { + // Closing tag break; } else if (token === 1 /* EndOfFileToken */) { - parseErrorAtCurrentToken(ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } result.push(parseJsxChild()); @@ -10962,7 +10405,7 @@ var ts; // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(235 /* JsxOpeningElement */, fullStart); + node = createNode(239 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { @@ -10971,10 +10414,10 @@ var ts; parseExpected(27 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(234 /* JsxSelfClosingElement */, fullStart); + node = createNode(238 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -10985,7 +10428,7 @@ var ts; var elementName = parseIdentifierName(); while (parseOptional(21 /* DotToken */)) { scanJsxIdentifier(); - var node = createNode(135 /* QualifiedName */, elementName.pos); + var node = createNode(137 /* QualifiedName */, elementName.pos); node.left = elementName; node.right = parseIdentifierName(); elementName = finishNode(node); @@ -10993,16 +10436,16 @@ var ts; return elementName; } function parseJsxExpression(inExpressionContext) { - var node = createNode(240 /* JsxExpression */); + var node = createNode(244 /* JsxExpression */); parseExpected(15 /* OpenBraceToken */); if (token !== 16 /* CloseBraceToken */) { - node.expression = parseExpression(); + node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { parseExpected(16 /* CloseBraceToken */); } else { - parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*advance*/ false); + parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); @@ -11012,7 +10455,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(238 /* JsxAttribute */); + var node = createNode(242 /* JsxAttribute */); node.name = parseIdentifierName(); if (parseOptional(56 /* EqualsToken */)) { switch (token) { @@ -11027,7 +10470,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(239 /* JsxSpreadAttribute */); + var node = createNode(243 /* JsxSpreadAttribute */); parseExpected(15 /* OpenBraceToken */); parseExpected(22 /* DotDotDotToken */); node.expression = parseExpression(); @@ -11035,20 +10478,20 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(237 /* JsxClosingElement */); + var node = createNode(241 /* JsxClosingElement */); parseExpected(26 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { parseExpected(27 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(171 /* TypeAssertionExpression */); + var node = createNode(175 /* TypeAssertionExpression */); parseExpected(25 /* LessThanToken */); node.type = parseType(); parseExpected(27 /* GreaterThanToken */); @@ -11059,7 +10502,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(21 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(166 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(170 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -11068,7 +10511,7 @@ var ts; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(19 /* OpenBracketToken */)) { - var indexedAccess = createNode(167 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(171 /* 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. @@ -11084,7 +10527,7 @@ var ts; continue; } if (token === 11 /* NoSubstitutionTemplateLiteral */ || token === 12 /* TemplateHead */) { - var tagExpression = createNode(170 /* TaggedTemplateExpression */, expression.pos); + var tagExpression = createNode(174 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 11 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() @@ -11107,7 +10550,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(168 /* CallExpression */, expression.pos); + var callExpr = createNode(172 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -11115,7 +10558,7 @@ var ts; continue; } else if (token === 17 /* OpenParenToken */) { - var callExpr = createNode(168 /* CallExpression */, expression.pos); + var callExpr = createNode(172 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -11139,7 +10582,7 @@ var ts; // If it doesn't have the closing > then it's definitely not an type argument list. return undefined; } - // If we have a '<', then only parse this as a arugment list if the type arguments + // If we have a '<', then only parse this as a argument list if the type arguments // are complete and we have an open paren. if we don't, rewind and return nothing. return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments @@ -11225,41 +10668,42 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(172 /* ParenthesizedExpression */); + var node = createNode(176 /* ParenthesizedExpression */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(185 /* SpreadElementExpression */); + var node = createNode(189 /* SpreadElementExpression */); parseExpected(22 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token === 24 /* CommaToken */ ? createNode(187 /* OmittedExpression */) : + token === 24 /* CommaToken */ ? createNode(191 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(164 /* ArrayLiteralExpression */); + var node = createNode(168 /* ArrayLiteralExpression */); parseExpected(19 /* OpenBracketToken */); - if (scanner.hasPrecedingLineBreak()) - node.flags |= 1024 /* MultiLine */; + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); parseExpected(20 /* CloseBracketToken */); return finishNode(node); } function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { if (parseContextualModifier(123 /* GetKeyword */)) { - return parseAccessorDeclaration(145 /* GetAccessor */, fullStart, decorators, modifiers); + return parseAccessorDeclaration(147 /* GetAccessor */, fullStart, decorators, modifiers); } - else if (parseContextualModifier(129 /* SetKeyword */)) { - return parseAccessorDeclaration(146 /* SetAccessor */, fullStart, decorators, modifiers); + else if (parseContextualModifier(130 /* SetKeyword */)) { + return parseAccessorDeclaration(148 /* SetAccessor */, fullStart, decorators, modifiers); } return undefined; } @@ -11273,7 +10717,6 @@ var ts; } var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); - var nameToken = token; var propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. var questionToken = parseOptionalToken(53 /* QuestionToken */); @@ -11287,7 +10730,7 @@ var ts; // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 /* CommaToken */ || token === 16 /* CloseBraceToken */ || token === 56 /* EqualsToken */); if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(246 /* ShorthandPropertyAssignment */, fullStart); + var shorthandDeclaration = createNode(250 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; var equalsToken = parseOptionalToken(56 /* EqualsToken */); @@ -11295,24 +10738,25 @@ var ts; shorthandDeclaration.equalsToken = equalsToken; shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return finishNode(shorthandDeclaration); + return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(245 /* PropertyAssignment */, fullStart); + var propertyAssignment = createNode(249 /* PropertyAssignment */, fullStart); + propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(54 /* ColonToken */); propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return finishNode(propertyAssignment); + return addJSDocComment(finishNode(propertyAssignment)); } } function parseObjectLiteralExpression() { - var node = createNode(165 /* ObjectLiteralExpression */); + var node = createNode(169 /* ObjectLiteralExpression */); parseExpected(15 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { - node.flags |= 1024 /* MultiLine */; + node.multiLine = true; } - node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimeter*/ true); + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); parseExpected(16 /* CloseBraceToken */); return finishNode(node); } @@ -11324,9 +10768,9 @@ var ts; // function BindingIdentifier[opt](FormalParameters){ FunctionBody } var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } - var node = createNode(173 /* FunctionExpression */); + var node = createNode(177 /* FunctionExpression */); setModifiers(node, parseModifiers()); parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); @@ -11340,15 +10784,15 @@ var ts; fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(169 /* NewExpression */); + var node = createNode(173 /* NewExpression */); parseExpected(92 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -11359,7 +10803,7 @@ var ts; } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(192 /* Block */); + var node = createNode(196 /* Block */); if (parseExpected(15 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); @@ -11378,23 +10822,23 @@ var ts; // arrow function. The body of the function is not in [Decorator] context. var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return block; } function parseEmptyStatement() { - var node = createNode(194 /* EmptyStatement */); + var node = createNode(198 /* EmptyStatement */); parseExpected(23 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(196 /* IfStatement */); + var node = createNode(200 /* IfStatement */); parseExpected(88 /* IfKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -11404,7 +10848,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(197 /* DoStatement */); + var node = createNode(201 /* DoStatement */); parseExpected(79 /* DoKeyword */); node.statement = parseStatement(); parseExpected(104 /* WhileKeyword */); @@ -11419,7 +10863,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(198 /* WhileStatement */); + var node = createNode(202 /* WhileStatement */); parseExpected(104 /* WhileKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -11442,21 +10886,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(90 /* InKeyword */)) { - var forInStatement = createNode(200 /* ForInStatement */, pos); + var forInStatement = createNode(204 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } - else if (parseOptional(134 /* OfKeyword */)) { - var forOfStatement = createNode(201 /* ForOfStatement */, pos); + else if (parseOptional(136 /* OfKeyword */)) { + var forOfStatement = createNode(205 /* ForOfStatement */, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(18 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(199 /* ForStatement */, pos); + var forStatement = createNode(203 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(23 /* SemicolonToken */); if (token !== 23 /* SemicolonToken */ && token !== 18 /* CloseParenToken */) { @@ -11474,7 +10918,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); + parseExpected(kind === 207 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -11482,7 +10926,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(204 /* ReturnStatement */); + var node = createNode(208 /* ReturnStatement */); parseExpected(94 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -11491,7 +10935,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(205 /* WithStatement */); + var node = createNode(209 /* WithStatement */); parseExpected(105 /* WithKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -11500,7 +10944,7 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(241 /* CaseClause */); + var node = createNode(245 /* CaseClause */); parseExpected(71 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(54 /* ColonToken */); @@ -11508,7 +10952,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(242 /* DefaultClause */); + var node = createNode(246 /* DefaultClause */); parseExpected(77 /* DefaultKeyword */); parseExpected(54 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); @@ -11518,12 +10962,12 @@ var ts; return token === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(206 /* SwitchStatement */); + var node = createNode(210 /* SwitchStatement */); parseExpected(96 /* SwitchKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); - var caseBlock = createNode(220 /* CaseBlock */, scanner.getStartPos()); + var caseBlock = createNode(224 /* CaseBlock */, scanner.getStartPos()); parseExpected(15 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(16 /* CloseBraceToken */); @@ -11538,7 +10982,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(208 /* ThrowStatement */); + var node = createNode(212 /* ThrowStatement */); parseExpected(98 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -11546,7 +10990,7 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(209 /* TryStatement */); + var node = createNode(213 /* TryStatement */); parseExpected(100 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -11559,7 +11003,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(244 /* CatchClause */); + var result = createNode(248 /* CatchClause */); parseExpected(72 /* CatchKeyword */); if (parseExpected(17 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); @@ -11569,7 +11013,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(210 /* DebuggerStatement */); + var node = createNode(214 /* DebuggerStatement */); parseExpected(76 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -11581,16 +11025,16 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 69 /* Identifier */ && parseOptional(54 /* ColonToken */)) { - var labeledStatement = createNode(207 /* LabeledStatement */, fullStart); + var labeledStatement = createNode(211 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); - return finishNode(labeledStatement); + return addJSDocComment(finishNode(labeledStatement)); } else { - var expressionStatement = createNode(195 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(199 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); - return finishNode(expressionStatement); + return addJSDocComment(finishNode(expressionStatement)); } } function nextTokenIsIdentifierOrKeywordOnSameLine() { @@ -11637,7 +11081,7 @@ var ts; // // could be legal, it would add complexity for very little gain. case 107 /* InterfaceKeyword */: - case 132 /* TypeKeyword */: + case 133 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); case 125 /* ModuleKeyword */: case 126 /* NamespaceKeyword */: @@ -11648,12 +11092,15 @@ var ts; case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: case 112 /* PublicKeyword */: + case 127 /* ReadonlyKeyword */: nextToken(); // ASI takes effect for this modifier. if (scanner.hasPrecedingLineBreak()) { return false; } continue; + case 135 /* GlobalKeyword */: + return nextToken() === 15 /* OpenBraceToken */; case 89 /* ImportKeyword */: nextToken(); return token === 9 /* StringLiteral */ || token === 37 /* AsteriskToken */ || @@ -11712,13 +11159,15 @@ var ts; case 107 /* InterfaceKeyword */: case 125 /* ModuleKeyword */: case 126 /* NamespaceKeyword */: - case 132 /* TypeKeyword */: + case 133 /* TypeKeyword */: + case 135 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: case 113 /* StaticKeyword */: + case 127 /* ReadonlyKeyword */: // When these don't start a declaration, they may be the start of a class member if an identifier // immediately follows. Otherwise they're an identifier in an expression statement. return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); @@ -11761,9 +11210,9 @@ var ts; case 86 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 75 /* ContinueKeyword */: - return parseBreakOrContinueStatement(202 /* ContinueStatement */); + return parseBreakOrContinueStatement(206 /* ContinueStatement */); case 70 /* BreakKeyword */: - return parseBreakOrContinueStatement(203 /* BreakStatement */); + return parseBreakOrContinueStatement(207 /* BreakStatement */); case 94 /* ReturnKeyword */: return parseReturnStatement(); case 105 /* WithKeyword */: @@ -11783,7 +11232,7 @@ var ts; return parseDeclaration(); case 118 /* AsyncKeyword */: case 107 /* InterfaceKeyword */: - case 132 /* TypeKeyword */: + case 133 /* TypeKeyword */: case 125 /* ModuleKeyword */: case 126 /* NamespaceKeyword */: case 122 /* DeclareKeyword */: @@ -11796,6 +11245,8 @@ var ts; case 112 /* PublicKeyword */: case 115 /* AbstractKeyword */: case 113 /* StaticKeyword */: + case 127 /* ReadonlyKeyword */: + case 135 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -11818,10 +11269,11 @@ var ts; return parseClassDeclaration(fullStart, decorators, modifiers); case 107 /* InterfaceKeyword */: return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 132 /* TypeKeyword */: + case 133 /* TypeKeyword */: return parseTypeAliasDeclaration(fullStart, decorators, modifiers); case 81 /* EnumKeyword */: return parseEnumDeclaration(fullStart, decorators, modifiers); + case 135 /* GlobalKeyword */: case 125 /* ModuleKeyword */: case 126 /* NamespaceKeyword */: return parseModuleDeclaration(fullStart, decorators, modifiers); @@ -11836,7 +11288,7 @@ var ts; 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(231 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var node = createMissingNode(235 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -11858,17 +11310,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token === 24 /* CommaToken */) { - return createNode(187 /* OmittedExpression */); + return createNode(191 /* OmittedExpression */); } - var node = createNode(163 /* BindingElement */); + var node = createNode(167 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(/*inParameter*/ false); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(163 /* BindingElement */); - // TODO(andersh): Handle computed properties + var node = createNode(167 /* BindingElement */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 54 /* ColonToken */) { @@ -11883,14 +11334,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(161 /* ObjectBindingPattern */); + var node = createNode(165 /* ObjectBindingPattern */); parseExpected(15 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(16 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(162 /* ArrayBindingPattern */); + var node = createNode(166 /* ArrayBindingPattern */); parseExpected(19 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(20 /* CloseBracketToken */); @@ -11909,7 +11360,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(211 /* VariableDeclaration */); + var node = createNode(215 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -11918,15 +11369,15 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(212 /* VariableDeclarationList */); + var node = createNode(216 /* VariableDeclarationList */); switch (token) { case 102 /* VarKeyword */: break; case 108 /* LetKeyword */: - node.flags |= 8192 /* Let */; + node.flags |= 1024 /* Let */; break; case 74 /* ConstKeyword */: - node.flags |= 16384 /* Const */; + node.flags |= 2048 /* Const */; break; default: ts.Debug.fail(); @@ -11941,7 +11392,7 @@ 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 === 134 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token === 136 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -11956,15 +11407,15 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 18 /* CloseParenToken */; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(193 /* VariableStatement */, fullStart); + var node = createNode(197 /* VariableStatement */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(213 /* FunctionDeclaration */, fullStart); + var node = createNode(217 /* FunctionDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(87 /* FunctionKeyword */); @@ -11974,19 +11425,19 @@ var ts; var isAsync = !!(node.flags & 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(144 /* Constructor */, pos); + var node = createNode(146 /* Constructor */, pos); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(121 /* ConstructorKeyword */); fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, ts.Diagnostics.or_expected); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(143 /* MethodDeclaration */, fullStart); + var method = createNode(145 /* MethodDeclaration */, fullStart); method.decorators = decorators; setModifiers(method, modifiers); method.asteriskToken = asteriskToken; @@ -11996,10 +11447,10 @@ var ts; var isAsync = !!(method.flags & 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); - return finishNode(method); + return addJSDocComment(finishNode(method)); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(141 /* PropertyDeclaration */, fullStart); + var property = createNode(143 /* PropertyDeclaration */, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; @@ -12010,13 +11461,13 @@ var ts; // 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]; + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. - property.initializer = modifiers && modifiers.flags & 64 /* Static */ + property.initializer = modifiers && modifiers.flags & 32 /* Static */ ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(2 /* Yield */ | 1 /* DisallowIn */, parseNonParameterInitializer); + : doOutsideOfContext(8388608 /* YieldContext */ | 4194304 /* DisallowInContext */, parseNonParameterInitializer); parseSemicolon(); return finishNode(property); } @@ -12051,6 +11502,7 @@ var ts; case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: case 113 /* StaticKeyword */: + case 127 /* ReadonlyKeyword */: return true; default: return false; @@ -12062,7 +11514,7 @@ var ts; return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { idToken = token; // If the idToken is a class modifier (protected, private, public, and static), it is // certain that we are starting to parse class member. This allows better error recovery @@ -12091,7 +11543,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 === 129 /* SetKeyword */ || idToken === 123 /* GetKeyword */) { + if (!ts.isKeyword(idToken) || idToken === 130 /* SetKeyword */ || idToken === 123 /* GetKeyword */) { return true; } // If it *is* a keyword, but not an accessor, check a little farther along @@ -12123,9 +11575,9 @@ var ts; } if (!decorators) { decorators = []; - decorators.pos = scanner.getStartPos(); + decorators.pos = decoratorStart; } - var decorator = createNode(139 /* Decorator */, decoratorStart); + var decorator = createNode(141 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -12134,14 +11586,30 @@ var ts; } return decorators; } - function parseModifiers() { + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token; - if (!parseAnyContextualModifier()) { - break; + if (token === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } } if (!modifiers) { modifiers = []; @@ -12174,13 +11642,13 @@ var ts; } function parseClassElement() { if (token === 23 /* SemicolonToken */) { - var result = createNode(191 /* SemicolonClassElement */); + var result = createNode(195 /* SemicolonClassElement */); nextToken(); return finishNode(result); } var fullStart = getNodePos(); var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; @@ -12212,10 +11680,10 @@ var ts; return parseClassDeclarationOrExpression( /*fullStart*/ scanner.getStartPos(), /*decorators*/ undefined, - /*modifiers*/ undefined, 186 /* ClassExpression */); + /*modifiers*/ undefined, 190 /* ClassExpression */); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 214 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 218 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); @@ -12240,8 +11708,8 @@ var ts; // implements is a future reserved word so // 'class implements' might mean either // - class expression with omitted name, 'implements' starts heritage clause - // - class with name 'implements' - // 'isImplementsClause' helps to disambiguate between these two cases + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases return isIdentifier() && !isImplementsClause() ? parseIdentifier() : undefined; @@ -12257,12 +11725,9 @@ var ts; } return undefined; } - function parseHeritageClausesWorker() { - return parseList(20 /* HeritageClauses */, parseHeritageClause); - } function parseHeritageClause() { if (token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */) { - var node = createNode(243 /* HeritageClause */); + var node = createNode(247 /* HeritageClause */); node.token = token; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); @@ -12271,7 +11736,7 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(188 /* ExpressionWithTypeArguments */); + var node = createNode(192 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); @@ -12285,7 +11750,7 @@ var ts; return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(215 /* InterfaceDeclaration */, fullStart); + var node = createNode(219 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(107 /* InterfaceKeyword */); @@ -12296,10 +11761,10 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216 /* TypeAliasDeclaration */, fullStart); + var node = createNode(220 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - parseExpected(132 /* TypeKeyword */); + parseExpected(133 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); parseExpected(56 /* EqualsToken */); @@ -12312,13 +11777,13 @@ 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(247 /* EnumMember */, scanner.getStartPos()); + var node = createNode(251 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(217 /* EnumDeclaration */, fullStart); + var node = createNode(221 /* EnumDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(81 /* EnumKeyword */); @@ -12333,7 +11798,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(219 /* ModuleBlock */, scanner.getStartPos()); + var node = createNode(223 /* ModuleBlock */, scanner.getStartPos()); if (parseExpected(15 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); @@ -12344,31 +11809,42 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(218 /* ModuleDeclaration */, fullStart); + var node = createNode(222 /* ModuleDeclaration */, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. - var namespaceFlag = flags & 65536 /* Namespace */; + var namespaceFlag = flags & 4096 /* Namespace */; node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21 /* DotToken */) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 2 /* Export */ | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 1 /* Export */ | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(218 /* ModuleDeclaration */, fullStart); + var node = createNode(222 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.name = parseLiteralNode(/*internName*/ true); + if (token === 135 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation + node.name = parseIdentifier(); + node.flags |= 131072 /* GlobalAugmentation */; + } + else { + node.name = parseLiteralNode(/*internName*/ true); + } node.body = parseModuleBlock(); return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; - if (parseOptional(126 /* NamespaceKeyword */)) { - flags |= 65536 /* Namespace */; + if (token === 135 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(126 /* NamespaceKeyword */)) { + flags |= 4096 /* Namespace */; } else { parseExpected(125 /* ModuleKeyword */); @@ -12379,7 +11855,7 @@ var ts; return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); } function isExternalModuleReference() { - return token === 127 /* RequireKeyword */ && + return token === 128 /* RequireKeyword */ && lookAhead(nextTokenIsOpenParen); } function nextTokenIsOpenParen() { @@ -12388,22 +11864,17 @@ var ts; function nextTokenIsSlash() { return nextToken() === 39 /* SlashToken */; } - function nextTokenIsCommaOrFromKeyword() { - nextToken(); - return token === 24 /* CommaToken */ || - token === 133 /* FromKeyword */; - } function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { parseExpected(89 /* ImportKeyword */); var afterImportPos = scanner.getStartPos(); var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token !== 24 /* CommaToken */ && token !== 133 /* FromKeyword */) { + if (token !== 24 /* CommaToken */ && token !== 134 /* FromKeyword */) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - var importEqualsDeclaration = createNode(221 /* ImportEqualsDeclaration */, fullStart); + var importEqualsDeclaration = createNode(225 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -12414,7 +11885,7 @@ var ts; } } // Import statement - var importDeclaration = createNode(222 /* ImportDeclaration */, fullStart); + var importDeclaration = createNode(226 /* ImportDeclaration */, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); // ImportDeclaration: @@ -12424,7 +11895,7 @@ var ts; token === 37 /* AsteriskToken */ || token === 15 /* OpenBraceToken */) { importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(133 /* FromKeyword */); + parseExpected(134 /* FromKeyword */); } importDeclaration.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); @@ -12437,7 +11908,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(223 /* ImportClause */, fullStart); + var importClause = createNode(227 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -12447,7 +11918,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(24 /* CommaToken */)) { - importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(225 /* NamedImports */); + importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(229 /* NamedImports */); } return finishNode(importClause); } @@ -12457,29 +11928,30 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(232 /* ExternalModuleReference */); - parseExpected(127 /* RequireKeyword */); + var node = createNode(236 /* ExternalModuleReference */); + parseExpected(128 /* RequireKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = parseModuleSpecifier(); parseExpected(18 /* CloseParenToken */); return finishNode(node); } function parseModuleSpecifier() { - // We allow arbitrary expressions here, even though the grammar only allows string - // literals. We check to ensure that it is only a string literal later in the grammar - // walker. - var result = parseExpression(); - // Ensure the string being required is in our 'identifier' table. This will ensure - // that features like 'find refs' will look inside this file when search for its name. - if (result.kind === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */) { + var result = parseLiteralNode(); internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); } - return result; } function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(224 /* NamespaceImport */); + var namespaceImport = createNode(228 /* NamespaceImport */); parseExpected(37 /* AsteriskToken */); parseExpected(116 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -12494,21 +11966,21 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 225 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); + node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 229 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(230 /* ExportSpecifier */); + return parseImportOrExportSpecifier(234 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(226 /* ImportSpecifier */); + return parseImportOrExportSpecifier(230 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); // ImportSpecifier: // BindingIdentifier // IdentifierName as BindingIdentifier - // ExportSpecififer: + // ExportSpecifier: // IdentifierName // IdentifierName as IdentifierName var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); @@ -12526,27 +11998,27 @@ var ts; else { node.name = identifierName; } - if (kind === 226 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 230 /* 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(228 /* ExportDeclaration */, fullStart); + var node = createNode(232 /* ExportDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(37 /* AsteriskToken */)) { - parseExpected(133 /* FromKeyword */); + parseExpected(134 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(229 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(233 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token === 133 /* FromKeyword */ || (token === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(133 /* FromKeyword */); + if (token === 134 /* FromKeyword */ || (token === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(134 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -12554,7 +12026,7 @@ var ts; return finishNode(node); } function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(227 /* ExportAssignment */, fullStart); + var node = createNode(231 /* ExportAssignment */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(56 /* EqualsToken */)) { @@ -12577,11 +12049,13 @@ var ts; // reference comment. while (true) { var kind = triviaScanner.scan(); - if (kind === 5 /* WhitespaceTrivia */ || kind === 4 /* NewLineTrivia */ || kind === 3 /* MultiLineCommentTrivia */) { - continue; - } if (kind !== 2 /* SingleLineCommentTrivia */) { - break; + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } } var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; var comment = sourceText.substring(range.pos, range.end); @@ -12626,11 +12100,11 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 2 /* Export */ - || node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */ - || node.kind === 222 /* ImportDeclaration */ - || node.kind === 227 /* ExportAssignment */ - || node.kind === 228 /* ExportDeclaration */ + return node.flags & 1 /* Export */ + || node.kind === 225 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 236 /* ExternalModuleReference */ + || node.kind === 226 /* ImportDeclaration */ + || node.kind === 231 /* ExportAssignment */ + || node.kind === 232 /* ExportDeclaration */ ? node : undefined; }); @@ -12691,21 +12165,19 @@ var ts; } JSDocParser.isJSDocType = isJSDocType; function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined); - var jsDocTypeExpression = parseJSDocTypeExpression(start, length); + initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + scanner.setText(content, start, length); + token = scanner.scan(); + var jsDocTypeExpression = parseJSDocTypeExpression(); 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. + // Parses out a JSDoc type expression. /* @internal */ - function parseJSDocTypeExpression(start, length) { - scanner.setText(sourceText, start, length); - // Prime the first token for us to start processing. - token = nextToken(); - var result = createNode(249 /* JSDocTypeExpression */); + function parseJSDocTypeExpression() { + var result = createNode(253 /* JSDocTypeExpression */, scanner.getTokenPos()); parseExpected(15 /* OpenBraceToken */); result.type = parseJSDocTopLevelType(); parseExpected(16 /* CloseBraceToken */); @@ -12716,12 +12188,12 @@ var ts; function parseJSDocTopLevelType() { var type = parseJSDocType(); if (token === 47 /* BarToken */) { - var unionType = createNode(253 /* JSDocUnionType */, type.pos); + var unionType = createNode(257 /* JSDocUnionType */, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === 56 /* EqualsToken */) { - var optionalType = createNode(260 /* JSDocOptionalType */, type.pos); + var optionalType = createNode(264 /* JSDocOptionalType */, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -12732,20 +12204,20 @@ var ts; var type = parseBasicTypeExpression(); while (true) { if (token === 19 /* OpenBracketToken */) { - var arrayType = createNode(252 /* JSDocArrayType */, type.pos); + var arrayType = createNode(256 /* JSDocArrayType */, type.pos); arrayType.elementType = type; nextToken(); parseExpected(20 /* CloseBracketToken */); type = finishNode(arrayType); } else if (token === 53 /* QuestionToken */) { - var nullableType = createNode(255 /* JSDocNullableType */, type.pos); + var nullableType = createNode(259 /* JSDocNullableType */, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } else if (token === 49 /* ExclamationToken */) { - var nonNullableType = createNode(256 /* JSDocNonNullableType */, type.pos); + var nonNullableType = createNode(260 /* JSDocNonNullableType */, type.pos); nonNullableType.type = type; nextToken(); type = finishNode(nonNullableType); @@ -12779,37 +12251,38 @@ var ts; case 97 /* ThisKeyword */: return parseJSDocThisType(); case 117 /* AnyKeyword */: - case 130 /* StringKeyword */: - case 128 /* NumberKeyword */: + case 131 /* StringKeyword */: + case 129 /* NumberKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: case 103 /* VoidKeyword */: return parseTokenNode(); } + // TODO (drosen): Parse string literal types in JSDoc as well. return parseJSDocTypeReference(); } function parseJSDocThisType() { - var result = createNode(264 /* JSDocThisType */); + var result = createNode(268 /* JSDocThisType */); nextToken(); parseExpected(54 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocConstructorType() { - var result = createNode(263 /* JSDocConstructorType */); + var result = createNode(267 /* JSDocConstructorType */); nextToken(); parseExpected(54 /* ColonToken */); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocVariadicType() { - var result = createNode(262 /* JSDocVariadicType */); + var result = createNode(266 /* JSDocVariadicType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType() { - var result = createNode(261 /* JSDocFunctionType */); + var result = createNode(265 /* JSDocFunctionType */); nextToken(); parseExpected(17 /* OpenParenToken */); result.parameters = parseDelimitedList(22 /* JSDocFunctionParameters */, parseJSDocParameter); @@ -12822,26 +12295,28 @@ var ts; return finishNode(result); } function parseJSDocParameter() { - var parameter = createNode(138 /* Parameter */); + var parameter = createNode(140 /* Parameter */); parameter.type = parseJSDocType(); + if (parseOptional(56 /* EqualsToken */)) { + parameter.questionToken = createNode(56 /* EqualsToken */); + } return finishNode(parameter); } - function parseJSDocOptionalType(type) { - var result = createNode(260 /* JSDocOptionalType */, type.pos); - nextToken(); - result.type = type; - return finishNode(result); - } function parseJSDocTypeReference() { - var result = createNode(259 /* JSDocTypeReference */); + var result = createNode(263 /* JSDocTypeReference */); result.name = parseSimplePropertyName(); - while (parseOptional(21 /* DotToken */)) { - if (token === 25 /* LessThanToken */) { - result.typeArguments = parseTypeArguments(); - break; - } - else { - result.name = parseQualifiedName(result.name); + if (token === 25 /* LessThanToken */) { + result.typeArguments = parseTypeArguments(); + } + else { + while (parseOptional(21 /* DotToken */)) { + if (token === 25 /* LessThanToken */) { + result.typeArguments = parseTypeArguments(); + break; + } + else { + result.name = parseQualifiedName(result.name); + } } } return finishNode(result); @@ -12863,13 +12338,13 @@ var ts; } } function parseQualifiedName(left) { - var result = createNode(135 /* QualifiedName */, left.pos); + var result = createNode(137 /* QualifiedName */, left.pos); result.left = left; result.right = parseIdentifierName(); return finishNode(result); } function parseJSDocRecordType() { - var result = createNode(257 /* JSDocRecordType */); + var result = createNode(261 /* JSDocRecordType */); nextToken(); result.members = parseDelimitedList(24 /* JSDocRecordMembers */, parseJSDocRecordMember); checkForTrailingComma(result.members); @@ -12877,7 +12352,7 @@ var ts; return finishNode(result); } function parseJSDocRecordMember() { - var result = createNode(258 /* JSDocRecordMember */); + var result = createNode(262 /* JSDocRecordMember */); result.name = parseSimplePropertyName(); if (token === 54 /* ColonToken */) { nextToken(); @@ -12886,13 +12361,13 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(256 /* JSDocNonNullableType */); + var result = createNode(260 /* JSDocNonNullableType */); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType() { - var result = createNode(254 /* JSDocTupleType */); + var result = createNode(258 /* JSDocTupleType */); nextToken(); result.types = parseDelimitedList(25 /* JSDocTupleTypes */, parseJSDocType); checkForTrailingComma(result.types); @@ -12906,7 +12381,7 @@ var ts; } } function parseJSDocUnionType() { - var result = createNode(253 /* JSDocUnionType */); + var result = createNode(257 /* JSDocUnionType */); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); parseExpected(18 /* CloseParenToken */); @@ -12924,7 +12399,7 @@ var ts; return types; } function parseJSDocAllType() { - var result = createNode(250 /* JSDocAllType */); + var result = createNode(254 /* JSDocAllType */); nextToken(); return finishNode(result); } @@ -12947,29 +12422,35 @@ var ts; token === 27 /* GreaterThanToken */ || token === 56 /* EqualsToken */ || token === 47 /* BarToken */) { - var result = createNode(251 /* JSDocUnknownType */, pos); + var result = createNode(255 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(255 /* JSDocNullableType */, pos); + var result = createNode(259 /* JSDocNullableType */, pos); result.type = parseJSDocType(); return finishNode(result); } } function parseIsolatedJSDocComment(content, start, length) { - initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined); - var jsDocComment = parseJSDocComment(/*parent:*/ undefined, start, length); + initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = { languageVariant: 0 /* Standard */, text: content }; + var jsDocComment = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; clearState(); return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var saveToken = token; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; var comment = parseJSDocCommentWorker(start, length); if (comment) { - fixupParentReferences(comment); comment.parent = parent; } + token = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; } JSDocParser.parseJSDocComment = parseJSDocComment; @@ -12982,77 +12463,75 @@ var ts; 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 */) { + var result; + // Check for /** (JSDoc opening part) + if (content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */) { + // + 3 for leading /**, - 5 in total for /** */ + scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. var 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. + nextJSDocToken(); + while (token !== 1 /* EndOfFileToken */) { + switch (token) { + case 55 /* AtToken */: + if (canParseTag) { + parseTag(); + } + // This will take us to the end of the line, so it's OK to parse a tag on the next pass through the loop + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + // After a line break, we can parse a tag, and we haven't seen an asterisk on the next line yet + canParseTag = true; + seenAsterisk = false; + break; + case 37 /* AsteriskToken */: + if (seenAsterisk) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + canParseTag = false; + } + // Ignore the first asterisk on a line + seenAsterisk = true; + break; + case 69 /* Identifier */: + // 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; - } - seenAsterisk = true; - continue; + break; + case 1 /* EndOfFileToken */: + break; } - // 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; + nextJSDocToken(); } - } + result = createJSDocComment(); + }); } - return createJSDocComment(); + return result; function createJSDocComment() { if (!tags) { return undefined; } - var result = createNode(265 /* JSDocComment */, start); + var result = createNode(269 /* JSDocComment */, start); result.tags = tags; return finishNode(result, end); } function skipWhitespace() { - while (pos < end && ts.isWhiteSpace(content.charCodeAt(pos))) { - pos++; + while (token === 5 /* WhitespaceTrivia */ || token === 4 /* NewLineTrivia */) { + nextJSDocToken(); } } function parseTag() { - ts.Debug.assert(content.charCodeAt(pos - 1) === 64 /* at */); - var atToken = createNode(55 /* AtToken */, pos - 1); - atToken.end = pos; - var tagName = scanIdentifier(); + ts.Debug.assert(token === 55 /* AtToken */); + var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifier(); if (!tagName) { return; } @@ -13076,10 +12555,10 @@ var ts; return undefined; } function handleUnknownTag(atToken, tagName) { - var result = createNode(266 /* JSDocTag */, atToken.pos); + var result = createNode(270 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - return finishNode(result, pos); + return finishNode(result); } function addTag(tag) { if (tag) { @@ -13092,12 +12571,10 @@ var ts; } } function tryParseTypeExpression() { - skipWhitespace(); - if (content.charCodeAt(pos) !== 123 /* openBrace */) { + if (token !== 15 /* OpenBraceToken */) { return undefined; } - var typeExpression = parseJSDocTypeExpression(pos, end - pos); - pos = typeExpression.end; + var typeExpression = parseJSDocTypeExpression(); return typeExpression; } function handleParamTag(atToken, tagName) { @@ -13105,17 +12582,22 @@ var ts; skipWhitespace(); var name; var isBracketed; - if (content.charCodeAt(pos) === 91 /* openBracket */) { - pos++; - skipWhitespace(); - name = scanIdentifier(); + // Looking for something like '[foo]' or 'foo' + if (parseOptionalToken(19 /* OpenBracketToken */)) { + name = parseJSDocIdentifier(); isBracketed = true; + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(56 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(20 /* CloseBracketToken */); } - else { - name = scanIdentifier(); + else if (token === 69 /* Identifier */) { + name = parseJSDocIdentifier(); } if (!name) { - parseErrorAtPosition(pos, 0, ts.Diagnostics.Identifier_expected); + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; } var preName, postName; if (typeExpression) { @@ -13127,84 +12609,82 @@ var ts; if (!typeExpression) { typeExpression = tryParseTypeExpression(); } - var result = createNode(267 /* JSDocParameterTag */, atToken.pos); + var result = createNode(271 /* 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); + return finishNode(result); } function handleReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 268 /* JSDocReturnTag */; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 272 /* JSDocReturnTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(268 /* JSDocReturnTag */, atToken.pos); + var result = createNode(272 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); - return finishNode(result, pos); + return finishNode(result); } function handleTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 269 /* JSDocTypeTag */; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 273 /* JSDocTypeTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } - var result = createNode(269 /* JSDocTypeTag */, atToken.pos); + var result = createNode(273 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); - return finishNode(result, pos); + return finishNode(result); } function handleTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 270 /* JSDocTemplateTag */; })) { - parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + if (ts.forEach(tags, function (t) { return t.kind === 274 /* JSDocTemplateTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); } + // Type parameter list looks like '@template T,U,V' var typeParameters = []; - typeParameters.pos = pos; + typeParameters.pos = scanner.getStartPos(); while (true) { - skipWhitespace(); - var startPos = pos; - var name_8 = scanIdentifier(); + var name_8 = parseJSDocIdentifier(); if (!name_8) { - parseErrorAtPosition(startPos, 0, ts.Diagnostics.Identifier_expected); + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(137 /* TypeParameter */, name_8.pos); + var typeParameter = createNode(139 /* TypeParameter */, name_8.pos); typeParameter.name = name_8; - finishNode(typeParameter, pos); + finishNode(typeParameter); typeParameters.push(typeParameter); - skipWhitespace(); - if (content.charCodeAt(pos) !== 44 /* comma */) { + if (token === 24 /* CommaToken */) { + nextJSDocToken(); + } + else { break; } - pos++; } - typeParameters.end = pos; - var result = createNode(270 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(274 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; - return finishNode(result, pos); + finishNode(result); + typeParameters.end = result.end; + return result; } - 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) { + function nextJSDocToken() { + return token = scanner.scanJSDocToken(); + } + function parseJSDocIdentifier() { + if (token !== 69 /* Identifier */) { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); return undefined; } - var result = createNode(69 /* Identifier */, startPos); - result.text = content.substring(startPos, pos); - return finishNode(result, pos); + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(69 /* Identifier */, pos); + result.text = content.substring(pos, end); + finishNode(result, end); + nextJSDocToken(); + return result; } } JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; @@ -13222,10 +12702,10 @@ var ts; if (sourceFile.statements.length === 0) { // If we don't have any statements in the current source file, then there's no real // way to incrementally parse. So just do a full parse instead. - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true); + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); } // Make sure we're not trying to incrementally update a source file more than once. Once - // we do an update the original source file is considered unusbale from that point onwards. + // we do an update the original source file is considered unusable from that point onwards. // // This is because we do incremental parsing in-place. i.e. we take nodes from the old // tree and give them new positions and parents. From that point on, trusting the old @@ -13278,7 +12758,7 @@ var ts; // inconsistent tree. Setting the parents on the new tree should be very fast. We // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); return result; } IncrementalParser.updateSourceFile = updateSourceFile; @@ -13337,7 +12817,7 @@ var ts; // We have an element that intersects the change range in some way. It may have its // start, or its end (or both) in the changed range. We want to adjust any part // that intersects such that the final tree is in a consistent state. i.e. all - // chlidren have spans within the span of their parent, and all siblings are ordered + // children have spans within the span of their parent, and all siblings are ordered // properly. // We may need to update both the 'pos' and the 'end' of the element. // If the 'pos' is before the start of the change, then we don't need to touch it. @@ -13357,7 +12837,7 @@ var ts; // -------------------ZZZ----------------- // // In this case, any element that started in the 'X' range will keep its position. - // However any element htat started after that will have their pos adjusted to be + // However any element that started after that will have their pos adjusted to be // at the end of the new range. i.e. any node that started in the 'Y' range will // be adjusted to have their start at the end of the 'Z' range. // @@ -13381,7 +12861,7 @@ var ts; // -------------------ZZZ----------------- // // In this case, any element that ended in the 'X' range will keep its position. - // However any element htat ended after that will have their pos adjusted to be + // However any element that ended after that will have their pos adjusted to be // at the end of the new range. i.e. any node that ended in the 'Y' range will // be adjusted to have their end at the end of the 'Z' range. if (element.end >= changeRangeOldEnd) { @@ -13401,12 +12881,12 @@ var ts; } function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { - var pos = node.pos; + var pos_2 = node.pos; forEachChild(node, function (child) { - ts.Debug.assert(child.pos >= pos); - pos = child.end; + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; }); - ts.Debug.assert(pos <= node.end); + ts.Debug.assert(pos_2 <= node.end); } } function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { @@ -13640,7 +13120,7 @@ var ts; if (position >= node.pos && position < node.end) { // Position was within this node. Keep searching deeper to find the node. forEachChild(node, visitNode, visitArray); - // don't procede any futher in the search. + // don't proceed any further in the search. return true; } // position wasn't in this node, have to keep searching. @@ -13682,6 +13162,1533 @@ var ts; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); })(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + ts.bindTime = 0; + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); + var ModuleInstanceState = ts.ModuleInstanceState; + var Reachability; + (function (Reachability) { + Reachability[Reachability["Uninitialized"] = 1] = "Uninitialized"; + Reachability[Reachability["Reachable"] = 2] = "Reachable"; + Reachability[Reachability["Unreachable"] = 4] = "Unreachable"; + Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable"; + })(Reachability || (Reachability = {})); + function or(state1, state2) { + return (state1 | state2) & 2 /* Reachable */ + ? 2 /* Reachable */ + : (state1 & state2) & 8 /* ReportedUnreachable */ + ? 8 /* ReportedUnreachable */ + : 4 /* Unreachable */; + } + function getModuleInstanceState(node) { + // A module is uninstantiated if it contains only + // 1. interface declarations, type alias declarations + if (node.kind === 219 /* InterfaceDeclaration */ || node.kind === 220 /* TypeAliasDeclaration */) { + return 0 /* NonInstantiated */; + } + else if (ts.isConstEnumDeclaration(node)) { + return 2 /* ConstEnumOnly */; + } + else if ((node.kind === 226 /* ImportDeclaration */ || node.kind === 225 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { + return 0 /* NonInstantiated */; + } + else if (node.kind === 223 /* ModuleBlock */) { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + switch (getModuleInstanceState(n)) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return false; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return false; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + } + }); + return state_1; + } + else if (node.kind === 222 /* ModuleDeclaration */) { + return getModuleInstanceState(node.body); + } + else { + return 1 /* Instantiated */; + } + } + ts.getModuleInstanceState = getModuleInstanceState; + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + 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 = {})); + var binder = createBinder(); + function bindSourceFile(file, options) { + var start = new Date().getTime(); + binder(file, options); + ts.bindTime += new Date().getTime() - start; + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var parent; + var container; + var blockScopeContainer; + var lastContainer; + var seenThisKeyword; + // state used by reachability checks + var hasExplicitReturn; + var currentReachabilityState; + var labelStack; + var labelIndexMap; + var implicitLabels; + // state used for emit helpers + var hasClassExtends; + var hasAsyncFunctions; + var hasDecorators; + var hasParameterDecorators; + // 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; + var symbolCount = 0; + var Symbol; + var classifiableNames; + function bindSourceFile(f, opts) { + file = f; + options = opts; + inStrictMode = !!file.externalModuleIndicator; + classifiableNames = {}; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + file = undefined; + options = undefined; + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + hasExplicitReturn = false; + labelStack = undefined; + labelIndexMap = undefined; + implicitLabels = undefined; + hasClassExtends = false; + hasAsyncFunctions = false; + hasDecorators = false; + hasParameterDecorators = false; + } + return bindSourceFile; + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { + symbol.exports = {}; + } + if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + symbol.members = {}; + } + if (symbolFlags & 107455 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 222 /* ModuleDeclaration */)) { + // other kinds of value declarations take precedence over modules + symbol.valueDeclaration = node; + } + } + } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. + function getDeclarationName(node) { + if (node.name) { + if (ts.isAmbientModule(node)) { + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + } + if (node.name.kind === 138 /* ComputedPropertyName */) { + var nameExpression = node.name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteral(nameExpression.kind)) { + return nameExpression.text; + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); + } + return node.name.text; + } + switch (node.kind) { + case 146 /* Constructor */: + return "__constructor"; + case 154 /* FunctionType */: + case 149 /* CallSignature */: + return "__call"; + case 155 /* ConstructorType */: + case 150 /* ConstructSignature */: + return "__new"; + case 151 /* IndexSignature */: + return "__index"; + case 232 /* ExportDeclaration */: + return "__export"; + case 231 /* ExportAssignment */: + return node.isExportEquals ? "export=" : "default"; + case 185 /* BinaryExpression */: + switch (ts.getSpecialPropertyAssignmentKind(node)) { + case 2 /* ModuleExports */: + // module.exports = ... + return "export="; + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + // exports.x = ... or this.y = ... + return node.left.name.text; + case 3 /* PrototypeProperty */: + // className.prototype.methodName = ... + return node.left.expression.name.text; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 217 /* FunctionDeclaration */: + case 218 /* ClassDeclaration */: + return node.flags & 512 /* Default */ ? "default" : undefined; + case 265 /* JSDocFunctionType */: + return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; + case 140 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 265 /* JSDocFunctionType */); + var functionType = node.parent; + var index = ts.indexOf(functionType.parameters, node); + return "p" + index; + } + } + function getDisplayName(node) { + return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = node.flags & 512 /* Default */; + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" : getDeclarationName(node); + var symbol; + if (name !== undefined) { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // 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; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.flags & 512 /* Default */) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + symbol = createSymbol(0 /* None */, name); + } + } + else { + symbol = createSymbol(0 /* None */, "__missing"); + } + addDeclarationToSymbol(symbol, node, includes); + symbol.parent = parent; + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedNodeFlags(node) & 1 /* Export */; + if (symbolFlags & 8388608 /* Alias */) { + if (node.kind === 234 /* ExportSpecifier */ || (node.kind === 225 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue, + // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set + // on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 8192 /* ExportContext */)) { + 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, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + 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) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var 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; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we proactively initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + var containerFlags = getContainerFlags(node); + if (containerFlags & 1 /* IsContainer */) { + container = blockScopeContainer = node; + if (containerFlags & 4 /* HasLocals */) { + container.locals = {}; + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + var savedReachabilityState; + var savedLabelStack; + var savedLabels; + var savedImplicitLabels; + var savedHasExplicitReturn; + var kind = node.kind; + var flags = node.flags; + // reset all reachability check related flags on node (for incremental scenarios) + flags &= ~98304 /* ReachabilityCheckFlags */; + // reset all emit helper flags on node (for incremental scenarios) + flags &= ~3932160 /* EmitHelperFlags */; + if (kind === 219 /* InterfaceDeclaration */) { + seenThisKeyword = false; + } + var saveState = kind === 252 /* SourceFile */ || kind === 223 /* ModuleBlock */ || ts.isFunctionLikeKind(kind); + if (saveState) { + savedReachabilityState = currentReachabilityState; + savedLabelStack = labelStack; + savedLabels = labelIndexMap; + savedImplicitLabels = implicitLabels; + savedHasExplicitReturn = hasExplicitReturn; + currentReachabilityState = 2 /* Reachable */; + hasExplicitReturn = false; + labelStack = labelIndexMap = implicitLabels = undefined; + } + if (ts.isInJavaScriptFile(node) && node.jsDocComment) { + bind(node.jsDocComment); + } + bindReachableStatement(node); + if (currentReachabilityState === 2 /* Reachable */ && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { + flags |= 32768 /* HasImplicitReturn */; + if (hasExplicitReturn) { + flags |= 65536 /* HasExplicitReturn */; + } + } + if (kind === 219 /* InterfaceDeclaration */) { + flags = seenThisKeyword ? flags | 16384 /* ContainsThis */ : flags & ~16384 /* ContainsThis */; + } + if (kind === 252 /* SourceFile */) { + if (hasClassExtends) { + flags |= 262144 /* HasClassExtends */; + } + if (hasDecorators) { + flags |= 524288 /* HasDecorators */; + } + if (hasParameterDecorators) { + flags |= 1048576 /* HasParamDecorators */; + } + if (hasAsyncFunctions) { + flags |= 2097152 /* HasAsyncFunctions */; + } + } + node.flags = flags; + if (saveState) { + hasExplicitReturn = savedHasExplicitReturn; + currentReachabilityState = savedReachabilityState; + labelStack = savedLabelStack; + labelIndexMap = savedLabels; + implicitLabels = savedImplicitLabels; + } + container = saveContainer; + parent = saveParent; + blockScopeContainer = savedBlockScopeContainer; + } + /** + * Returns true if node and its subnodes were successfully traversed. + * Returning false means that node was not examined and caller needs to dive into the node himself. + */ + function bindReachableStatement(node) { + if (checkUnreachable(node)) { + ts.forEachChild(node, bind); + return; + } + switch (node.kind) { + case 202 /* WhileStatement */: + bindWhileStatement(node); + break; + case 201 /* DoStatement */: + bindDoStatement(node); + break; + case 203 /* ForStatement */: + bindForStatement(node); + break; + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 200 /* IfStatement */: + bindIfStatement(node); + break; + case 208 /* ReturnStatement */: + case 212 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 207 /* BreakStatement */: + case 206 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 213 /* TryStatement */: + bindTryStatement(node); + break; + case 210 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 224 /* CaseBlock */: + bindCaseBlock(node); + break; + case 211 /* LabeledStatement */: + bindLabeledStatement(node); + break; + default: + ts.forEachChild(node, bind); + break; + } + } + function bindWhileStatement(n) { + var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + // bind expressions (don't affect reachability) + bind(n.expression); + currentReachabilityState = preWhileState; + var postWhileLabel = pushImplicitLabel(); + bind(n.statement); + popImplicitLabel(postWhileLabel, postWhileState); + } + function bindDoStatement(n) { + var preDoState = currentReachabilityState; + var postDoLabel = pushImplicitLabel(); + bind(n.statement); + var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState; + popImplicitLabel(postDoLabel, postDoState); + // bind expressions (don't affect reachability) + bind(n.expression); + } + function bindForStatement(n) { + var preForState = currentReachabilityState; + var postForLabel = pushImplicitLabel(); + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.condition); + bind(n.incrementor); + bind(n.statement); + // for statement is considered infinite when it condition is either omitted or is true keyword + // - for(..;;..) + // - for(..;true;..) + var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */); + var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState; + popImplicitLabel(postForLabel, postForState); + } + function bindForInOrForOfStatement(n) { + var preStatementState = currentReachabilityState; + var postStatementLabel = pushImplicitLabel(); + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.expression); + bind(n.statement); + popImplicitLabel(postStatementLabel, preStatementState); + } + function bindIfStatement(n) { + // denotes reachability state when entering 'thenStatement' part of the if statement: + // i.e. if condition is false then thenStatement is unreachable + var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + // denotes reachability state when entering 'elseStatement': + // i.e. if condition is true then elseStatement is unreachable + var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + currentReachabilityState = ifTrueState; + // bind expression (don't affect reachability) + bind(n.expression); + bind(n.thenStatement); + if (n.elseStatement) { + var preElseState = currentReachabilityState; + currentReachabilityState = ifFalseState; + bind(n.elseStatement); + currentReachabilityState = or(currentReachabilityState, preElseState); + } + else { + currentReachabilityState = or(currentReachabilityState, ifFalseState); + } + } + function bindReturnOrThrow(n) { + // bind expression (don't affect reachability) + bind(n.expression); + if (n.kind === 208 /* ReturnStatement */) { + hasExplicitReturn = true; + } + currentReachabilityState = 4 /* Unreachable */; + } + function bindBreakOrContinueStatement(n) { + // call bind on label (don't affect reachability) + bind(n.label); + // for continue case touch label so it will be marked a used + var isValidJump = jumpToLabel(n.label, n.kind === 207 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); + if (isValidJump) { + currentReachabilityState = 4 /* Unreachable */; + } + } + function bindTryStatement(n) { + // catch\finally blocks has the same reachability as try block + var preTryState = currentReachabilityState; + bind(n.tryBlock); + var postTryState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.catchClause); + var postCatchState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.finallyBlock); + // post catch/finally state is reachable if + // - post try state is reachable - control flow can fall out of try block + // - post catch state is reachable - control flow can fall out of catch block + currentReachabilityState = or(postTryState, postCatchState); + } + function bindSwitchStatement(n) { + var preSwitchState = currentReachabilityState; + var postSwitchLabel = pushImplicitLabel(); + // bind expression (don't affect reachability) + bind(n.expression); + bind(n.caseBlock); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 246 /* DefaultClause */; }); + // post switch state is unreachable if switch is exhaustive (has a default case ) and does not have fallthrough from the last case + var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState; + popImplicitLabel(postSwitchLabel, postSwitchState); + } + function bindCaseBlock(n) { + var startState = currentReachabilityState; + for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + currentReachabilityState = startState; + bind(clause); + if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + } + function bindLabeledStatement(n) { + // call bind on label (don't affect reachability) + bind(n.label); + var ok = pushNamedLabel(n.label); + bind(n.statement); + if (ok) { + popNamedLabel(n.label, currentReachabilityState); + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 190 /* ClassExpression */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 169 /* ObjectLiteralExpression */: + case 157 /* TypeLiteral */: + case 261 /* JSDocRecordType */: + return 1 /* IsContainer */; + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 217 /* FunctionDeclaration */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 222 /* ModuleDeclaration */: + case 252 /* SourceFile */: + case 220 /* TypeAliasDeclaration */: + return 5 /* IsContainerWithLocals */; + case 248 /* CatchClause */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 224 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 196 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + // Just call this directly so that the return type of this function stays "void". + 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 222 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 252 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 190 /* ClassExpression */: + case 218 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 221 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 157 /* TypeLiteral */: + case 169 /* ObjectLiteralExpression */: + case 219 /* InterfaceDeclaration */: + case 261 /* JSDocRecordType */: + // 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 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 265 /* JSDocFunctionType */: + case 220 /* 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 & 32 /* Static */ + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 252 /* SourceFile */ ? node : node.body; + if (body.kind === 252 /* SourceFile */ || body.kind === 223 /* ModuleBlock */) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 232 /* ExportDeclaration */ || stat.kind === 231 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 8192 /* ExportContext */; + } + else { + node.flags &= ~8192 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (node.flags & 1 /* Export */) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); + } + else { + var state = getModuleInstanceState(node); + if (state === 0 /* NonInstantiated */) { + declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); + if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { + // if module was already merged with some function, class or non-const enum + // treat is a non-const-enum-only + node.symbol.constEnumOnlyModule = false; + } + else { + var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; + if (node.symbol.constEnumOnlyModule === undefined) { + // non-merged case - use the current state + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + } + else { + // merged case: module is const enum only if all its pieces are non-instantiated or const enum + node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + } + } + } + } + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; + } + 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 !== 69 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 249 /* PropertyAssignment */ || prop.kind === 250 /* ShorthandPropertyAssignment */ || prop.kind === 145 /* 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 bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 222 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 252 /* SourceFile */: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // fall through. + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = {}; + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 114 /* 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.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 69 /* 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 === 69 /* Identifier */ && + (node.text === "eval" || node.text === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 69 /* 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.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.isOctalLiteral) { + 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 === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function getDestructuringParameterName(node) { + return "__" + ts.indexOf(node.parent.parameters, node); + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var 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 252 /* SourceFile */: + case 223 /* ModuleBlock */: + updateStrictModeStatementList(node.statements); + return; + case 196 /* Block */: + if (ts.isFunctionLike(node.parent)) { + updateStrictModeStatementList(node.statements); + } + return; + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return; + } + } + function updateStrictModeStatementList(statements) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === "\"use strict\"" || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 69 /* Identifier */: + return checkStrictModeIdentifier(node); + case 185 /* BinaryExpression */: + if (ts.isInJavaScriptFile(node)) { + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + } + return checkStrictModeBinaryExpression(node); + case 248 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 179 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 184 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 183 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 209 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 163 /* ThisType */: + seenThisKeyword = true; + return; + case 152 /* TypePredicate */: + return checkTypePredicate(node); + case 139 /* TypeParameter */: + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); + case 140 /* Parameter */: + return bindParameter(node); + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: + return bindVariableDeclarationOrBindingElement(node); + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 262 /* JSDocRecordMember */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); + case 249 /* PropertyAssignment */: + case 250 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); + case 251 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + case 217 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 146 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 147 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + case 148 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 265 /* JSDocFunctionType */: + return bindFunctionOrConstructorType(node); + case 157 /* TypeLiteral */: + case 261 /* JSDocRecordType */: + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); + case 169 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + return bindFunctionExpression(node); + case 172 /* CallExpression */: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 190 /* ClassExpression */: + case 218 /* ClassDeclaration */: + return bindClassLikeDeclaration(node); + case 219 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); + case 220 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); + case 221 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 222 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Imports and exports + case 225 /* ImportEqualsDeclaration */: + case 228 /* NamespaceImport */: + case 230 /* ImportSpecifier */: + case 234 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); + case 227 /* ImportClause */: + return bindImportClause(node); + case 232 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 231 /* ExportAssignment */: + return bindExportAssignment(node); + case 252 /* SourceFile */: + return bindSourceFileIfExternalModule(); + } + } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 69 /* Identifier */) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 163 /* ThisType */) { + seenThisKeyword = true; + } + bind(type); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + var boundExpression = node.kind === 231 /* ExportAssignment */ ? node.expression : node.right; + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); + } + else if (boundExpression.kind === 69 /* Identifier */ && node.kind === 231 /* ExportAssignment */) { + // 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 setCommonJsModuleIndicator(node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 7340032 /* Export */, 0 /* None */); + } + function bindModuleExportsAssignment(node) { + // 'module.exports = expr' assignment + setCommonJsModuleIndicator(node); + bindExportAssignment(node); + } + function bindThisPropertyAssignment(node) { + // Declare a 'member' in case it turns out the container was an ES5 class + if (container.kind === 177 /* FunctionExpression */ || container.kind === 217 /* FunctionDeclaration */) { + container.symbol.members = container.symbol.members || {}; + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ & ~4 /* Property */); + } + } + function bindPrototypePropertyAssignment(node) { + // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var leftSideOfAssignment = node.left; + var classPrototype = leftSideOfAssignment.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + var funcSymbol = container.locals[constructorFunction.text]; + if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */)) { + return; + } + // Set up the members collection if it doesn't exist already + if (!funcSymbol.members) { + funcSymbol.members = {}; + } + // Declare the method/property + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 107455 /* PropertyExcludes */); + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { + hasClassExtends = true; + } + if (ts.nodeIsDecorated(node)) { + hasDecorators = true; + } + } + if (node.kind === 218 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.text : "__class"; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames[node.name.text] = node.name.text; + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 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 (!ts.isDeclarationFile(file) && + !ts.isInAmbientContext(node) && + ts.nodeIsDecorated(node)) { + hasDecorators = true; + hasParameterDecorators = true; + } + 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)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + } + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + } + function bindFunctionExpression(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.text : "__function"; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + if (ts.nodeIsDecorated(node)) { + hasDecorators = true; + } + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + // reachability checks + function pushNamedLabel(name) { + initializeReachabilityStateIfNecessary(); + if (ts.hasProperty(labelIndexMap, name.text)) { + return false; + } + labelIndexMap[name.text] = labelStack.push(1 /* Uninitialized */) - 1; + return true; + } + function pushImplicitLabel() { + initializeReachabilityStateIfNecessary(); + var index = labelStack.push(1 /* Uninitialized */) - 1; + implicitLabels.push(index); + return index; + } + function popNamedLabel(label, outerState) { + var index = labelIndexMap[label.text]; + ts.Debug.assert(index !== undefined); + ts.Debug.assert(labelStack.length == index + 1); + labelIndexMap[label.text] = undefined; + setCurrentStateAtLabel(labelStack.pop(), outerState, label); + } + function popImplicitLabel(implicitLabelIndex, outerState) { + if (labelStack.length !== implicitLabelIndex + 1) { + ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); + } + var i = implicitLabels.pop(); + if (implicitLabelIndex !== i) { + ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); + } + setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined); + } + function setCurrentStateAtLabel(innerMergedState, outerState, label) { + if (innerMergedState === 1 /* Uninitialized */) { + if (label && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); + } + currentReachabilityState = outerState; + } + else { + currentReachabilityState = or(innerMergedState, outerState); + } + } + function jumpToLabel(label, outerState) { + initializeReachabilityStateIfNecessary(); + var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); + if (index === undefined) { + // reference to unknown label or + // break/continue used outside of loops + return false; + } + var stateAtLabel = labelStack[index]; + labelStack[index] = stateAtLabel === 1 /* Uninitialized */ ? outerState : or(stateAtLabel, outerState); + return true; + } + function checkUnreachable(node) { + switch (currentReachabilityState) { + case 4 /* Unreachable */: + var reportError = + // report error on all statements except empty ones + (ts.isStatement(node) && node.kind !== 198 /* EmptyStatement */) || + // report error on class declarations + node.kind === 218 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 222 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (node.kind === 221 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentReachabilityState = 8 /* ReportedUnreachable */; + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 197 /* VariableStatement */ || + ts.getCombinedNodeFlags(node.declarationList) & 3072 /* BlockScoped */ || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + case 8 /* ReportedUnreachable */: + return true; + default: + return false; + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); + } + } + function initializeReachabilityStateIfNecessary() { + if (labelIndexMap) { + return; + } + currentReachabilityState = 2 /* Reachable */; + labelIndexMap = {}; + labelStack = []; + implicitLabels = []; + } + } +})(ts || (ts = {})); /// /* @internal */ var ts; @@ -13690,15 +14697,18 @@ var ts; var nextNodeId = 1; var nextMergeId = 1; function getNodeId(node) { - if (!node.id) - node.id = nextNodeId++; + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } return node.id; } ts.getNodeId = getNodeId; ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { - symbol.id = nextSymbolId++; + symbol.id = nextSymbolId; + nextSymbolId++; } return symbol.id; } @@ -13723,9 +14733,11 @@ var ts; var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || 0 /* ES3 */; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + var modulekind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; var emitResolver = createResolver(); var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined"); + undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -13734,11 +14746,13 @@ var ts; getTypeCount: function () { return typeCount; }, isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, getDiagnostics: getDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, // The language service will always care about the narrowed type of a symbol, because that is // the type the language says the symbol should have. getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, + getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: getPropertyOfType, @@ -13749,6 +14763,7 @@ var ts; getSymbolsInScope: getSymbolsInScope, getSymbolAtLocation: getSymbolAtLocation, getShorthandAssignmentValueSymbol: getShorthandAssignmentValueSymbol, + getExportSpecifierLocalTargetSymbol: getExportSpecifierLocalTargetSymbol, getTypeAtLocation: getTypeOfNode, typeToString: typeToString, getSymbolDisplayBuilder: getSymbolDisplayBuilder, @@ -13780,8 +14795,8 @@ var ts; var undefinedType = createIntrinsicType(32 /* Undefined */ | 2097152 /* ContainsUndefinedOrNull */, "undefined"); var nullType = createIntrinsicType(64 /* Null */ | 2097152 /* ContainsUndefinedOrNull */, "null"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var circularType = createIntrinsicType(1 /* Any */, "__circular__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyUnionType = emptyObjectType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -13789,27 +14804,27 @@ var ts; // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = {}; var globalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; var globalObjectType; var globalFunctionType; var globalArrayType; + var globalReadonlyArrayType; var globalStringType; var globalNumberType; var globalBooleanType; var globalRegExpType; var globalTemplateStringsArrayType; var globalESSymbolType; - var jsxElementType; - /** Lazily loaded, use getJsxIntrinsicElementType() */ - var jsxIntrinsicElementsType; var globalIterableType; var globalIteratorType; var globalIterableIteratorType; var anyArrayType; + var anyReadonlyArrayType; var getGlobalClassDecoratorType; var getGlobalParameterDecoratorType; var getGlobalPropertyDecoratorType; @@ -13822,15 +14837,11 @@ var ts; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; var jsxElementClassType; + var deferredNodes; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; var stringLiteralTypes = {}; - var emitExtends = false; - var emitDecorate = false; - var emitParam = false; - var emitAwaiter = false; - var emitGenerator = false; var resolutionTargets = []; var resolutionResults = []; var resolutionPropertyNames = []; @@ -13856,14 +14867,23 @@ var ts; "symbol": { type: esSymbolType, flags: 16777216 /* ESSymbol */ + }, + "undefined": { + type: undefinedType, + flags: 2097152 /* ContainsUndefinedOrNull */ } }; + var jsxElementType; + /** Things we lazy load from the JSX namespace */ + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", ElementClass: "ElementClass", ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - Element: "Element" + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" }; var subtypeRelation = {}; var assignableRelation = {}; @@ -13877,6 +14897,10 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -13932,8 +14956,10 @@ var ts; return result; } function recordMergedSymbol(target, source) { - if (!source.mergeId) - source.mergeId = nextMergeId++; + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { @@ -13958,8 +14984,12 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (!target.valueDeclaration && source.valueDeclaration) + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 222 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 222 /* ModuleDeclaration */))) { + // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; + } ts.forEach(source.declarations, function (node) { target.declarations.push(node); }); @@ -13976,13 +15006,13 @@ var ts; recordMergedSymbol(target, source); } else { - var message = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ + var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message, symbolToString(source)); + error(node.name ? node.name : node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message, symbolToString(source)); + error(node.name ? node.name : node, message_2, symbolToString(source)); }); } } @@ -14011,6 +15041,53 @@ var ts; } } } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.valueDeclaration !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1536 /* Namespace */) { + // if module symbol has already been merged - it is safe to use it. + // otherwise clone it + mainModule = mainModule.flags & 33554432 /* Merged */ ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + for (var id in source) { + if (ts.hasProperty(source, id)) { + if (ts.hasProperty(target, id)) { + // Error on redeclarations + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } + } + } + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } function getSymbolLinks(symbol) { if (symbol.flags & 67108864 /* Transient */) return symbol; @@ -14021,11 +15098,8 @@ var ts; var nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } - function getSourceFile(node) { - return ts.getAncestor(node, 248 /* SourceFile */); - } function isGlobalSourceFile(node) { - return node.kind === 248 /* SourceFile */ && !ts.isExternalModule(node); + return node.kind === 252 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -14044,6 +15118,22 @@ var ts; } // return undefined if we can't find a symbol. } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); @@ -14058,7 +15148,7 @@ var ts; if (declaration.pos <= usage.pos) { // declaration is before usage // still might be illegal if usage is in the initializer of the variable declaration - return declaration.kind !== 211 /* VariableDeclaration */ || + return declaration.kind !== 215 /* VariableDeclaration */ || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } // declaration is after usage @@ -14066,14 +15156,14 @@ var ts; return isUsedInFunctionOrNonStaticProperty(declaration, usage); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); - if (declaration.parent.parent.kind === 193 /* VariableStatement */ || - declaration.parent.parent.kind === 199 /* ForStatement */) { + if (declaration.parent.parent.kind === 197 /* VariableStatement */ || + declaration.parent.parent.kind === 203 /* ForStatement */) { // variable statement/for statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) return isSameScopeDescendentOf(usage, declaration, container); } - else if (declaration.parent.parent.kind === 201 /* ForOfStatement */ || - declaration.parent.parent.kind === 200 /* ForInStatement */) { + else if (declaration.parent.parent.kind === 205 /* ForOfStatement */ || + declaration.parent.parent.kind === 204 /* ForInStatement */) { // ForIn/ForOf case - use site should not be used in expression part var expression = declaration.parent.parent.expression; return isSameScopeDescendentOf(usage, expression, container); @@ -14090,8 +15180,8 @@ var ts; return true; } var initializerOfNonStaticProperty = current.parent && - current.parent.kind === 141 /* PropertyDeclaration */ && - (current.parent.flags & 64 /* Static */) === 0 && + current.parent.kind === 143 /* PropertyDeclaration */ && + (current.parent.flags & 32 /* Static */) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -14114,28 +15204,59 @@ 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)) { - // 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) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 793056 /* Type */ && lastLocation.kind !== 269 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + ? lastLocation === location.type || + lastLocation.kind === 140 /* Parameter */ || + lastLocation.kind === 139 /* TypeParameter */ + : false; + } + if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 140 /* Parameter */ || + (lastLocation === location.type && + result.valueDeclaration.kind === 140 /* Parameter */); + } + } + if (useResult) { break loop; } - result = undefined; + else { + result = undefined; + } } } switch (location.kind) { - case 248 /* SourceFile */: - if (!ts.isExternalModule(location)) + case 252 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) break; - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 248 /* SourceFile */ || - (location.kind === 218 /* ModuleDeclaration */ && location.name.kind === 9 /* 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. + if (location.kind === 252 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports["default"]) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { + break loop; + } + result = undefined; + } + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. // Two things to note about this: // 1. We have to check this without calling getSymbol. The problem with calling getSymbol // on an export specifier is that it might find the export specifier itself, and try to @@ -14146,34 +15267,28 @@ var ts; // which is not the desired behavior. if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 /* Alias */ && - ts.getDeclarationOfKind(moduleExports[name], 230 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExports[name], 234 /* ExportSpecifier */)) { break; } - 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 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (ts.isClassLike(location.parent) && !(location.flags & 64 /* Static */)) { + if (ts.isClassLike(location.parent) && !(location.flags & 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -14183,11 +15298,11 @@ var ts; } } break; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 219 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { - if (lastLocation && lastLocation.flags & 64 /* Static */) { + if (lastLocation && lastLocation.flags & 32 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. @@ -14196,7 +15311,7 @@ var ts; } break loop; } - if (location.kind === 186 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 190 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -14212,9 +15327,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 136 /* ComputedPropertyName */: + case 138 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 215 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 219 /* 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); @@ -14222,19 +15337,19 @@ var ts; } } break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 178 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 173 /* FunctionExpression */: + case 177 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -14247,7 +15362,7 @@ var ts; } } break; - case 139 /* Decorator */: + case 141 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -14256,7 +15371,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 === 138 /* Parameter */) { + if (location.parent && location.parent.kind === 140 /* Parameter */) { location = location.parent; } // @@ -14278,7 +15393,9 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } return undefined; } @@ -14297,7 +15414,7 @@ var ts; // declare module foo { // interface bar {} // } - // let foo/*1*/: foo/*2*/.bar; + // const foo/*1*/: foo/*2*/.bar; // The foo at /*1*/ and /*2*/ will share same symbol with two meaning // block - scope variable and namespace module. However, only when we // try to resolve name in /*1*/ which is used in variable position, @@ -14311,12 +15428,44 @@ var ts; } return result; } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!errorLocation || (errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + return false; + } + var container = ts.getThisContainer(errorLocation, /* includeArrowFunctions */ true); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + // Check to see if a static member exists. + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); + return true; + } + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !(location.flags & 32 /* Static */)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); // Block-scoped variables cannot be used before their definition var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); - if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 211 /* VariableDeclaration */), errorLocation)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 215 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -14337,10 +15486,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 225 /* ImportEqualsDeclaration */) { return node; } - while (node && node.kind !== 222 /* ImportDeclaration */) { + while (node && node.kind !== 226 /* ImportDeclaration */) { node = node.parent; } return node; @@ -14350,7 +15499,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 232 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 236 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -14359,9 +15508,12 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); - if (!exportDefaultSymbol) { + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } return exportDefaultSymbol; } } @@ -14369,14 +15521,6 @@ var ts; var moduleSpecifier = node.parent.parent.moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } - function getMemberOfModuleVariable(moduleSymbol, name) { - if (moduleSymbol.flags & 3 /* Variable */) { - var typeAnnotation = moduleSymbol.valueDeclaration.type; - if (typeAnnotation) { - return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); - } - } - } // This function creates a synthetic symbol that combines the value side of one symbol with the // type/namespace side of another symbol. Consider this example: // @@ -14457,17 +15601,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node); - case 223 /* ImportClause */: + case 227 /* ImportClause */: return getTargetOfImportClause(node); - case 224 /* NamespaceImport */: + case 228 /* NamespaceImport */: return getTargetOfNamespaceImport(node); - case 226 /* ImportSpecifier */: + case 230 /* ImportSpecifier */: return getTargetOfImportSpecifier(node); - case 230 /* ExportSpecifier */: + case 234 /* ExportSpecifier */: return getTargetOfExportSpecifier(node); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return getTargetOfExportAssignment(node); } } @@ -14512,11 +15656,11 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 227 /* ExportAssignment */) { + if (node.kind === 231 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 230 /* ExportSpecifier */) { + else if (node.kind === 234 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -14529,7 +15673,7 @@ var ts; // This function is only for imports with entity names function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 221 /* ImportEqualsDeclaration */); + importDeclaration = ts.getAncestor(entityName, 225 /* ImportEqualsDeclaration */); ts.Debug.assert(importDeclaration !== undefined); } // There are three things we might try to look for. In the following examples, @@ -14542,13 +15686,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 135 /* QualifiedName */) { + if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 137 /* 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 === 221 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 225 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } } @@ -14568,9 +15712,9 @@ var ts; return undefined; } } - else if (name.kind === 135 /* QualifiedName */ || name.kind === 166 /* PropertyAccessExpression */) { - var left = name.kind === 135 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 135 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 137 /* QualifiedName */ || name.kind === 170 /* PropertyAccessExpression */) { + var left = name.kind === 137 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 137 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors); if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) { return undefined; @@ -14590,11 +15734,13 @@ var ts; return symbol.flags & meaning ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError) { if (moduleReferenceExpression.kind !== 9 /* StringLiteral */) { return; } var moduleReferenceLiteral = moduleReferenceExpression; - var searchPath = ts.getDirectoryPath(getSourceFile(location).fileName); // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); @@ -14605,24 +15751,33 @@ var ts; if (!isRelative) { var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); if (symbol) { - return symbol; + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(symbol); } } - var resolvedModule = ts.getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReferenceLiteral.text); var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - return sourceFile.symbol; + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); } - error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - return; + if (moduleNotFoundError) { + // report errors only if it was requested + error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; } - error(moduleReferenceLiteral, ts.Diagnostics.Cannot_find_module_0, moduleName); + if (moduleNotFoundError) { + // report errors only if it was requested + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + } + return undefined; } // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, // and an external module with no 'export =' declaration resolves to the module itself. function resolveExternalModuleSymbol(moduleSymbol) { - return moduleSymbol && resolveSymbol(moduleSymbol.exports["export="]) || moduleSymbol; + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports["export="])) || moduleSymbol; } // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may @@ -14635,8 +15790,8 @@ var ts; } return symbol; } - function getExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports["export="]; + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports["export="] !== undefined; } function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); @@ -14648,38 +15803,66 @@ var ts; var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } - function extendExportSymbols(target, source) { + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; + if (lookupTable && exportNode) { + lookupTable[id] = { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }; + } + } + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + if (!lookupTable[id].exportsWithDuplicate) { + lookupTable[id].exportsWithDuplicate = [exportNode]; + } + else { + lookupTable[id].exportsWithDuplicate.push(exportNode); + } } } } function getExportsForModule(moduleSymbol) { - var result; var visitedSymbols = []; - visit(moduleSymbol); - return result || moduleSymbol.exports; + return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. function visit(symbol) { - if (symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol)) { - visitedSymbols.push(symbol); - if (symbol !== moduleSymbol) { - if (!result) { - result = cloneSymbolTable(moduleSymbol.exports); - } - extendExportSymbols(result, symbol.exports); - } - // All export * declarations are collected in an __export symbol by the binder - var exportStars = symbol.exports["__export"]; - if (exportStars) { - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - visit(resolveExternalModuleName(node, node.moduleSpecifier)); - } - } + if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { + return; } + visitedSymbols.push(symbol); + var symbols = cloneSymbolTable(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports["__export"]; + if (exportStars) { + var nestedSymbols = {}; + var lookupTable = {}; + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); + } + for (var id in lookupTable) { + var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + continue; + } + for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { + var node = exportsWithDuplicate_1[_b]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable[id].specifierText, id)); + } + } + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; } } function getMergedSymbol(symbol) { @@ -14717,14 +15900,15 @@ var ts; var members = node.members; for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { var member = members_1[_i]; - if (member.kind === 144 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 146 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount++; + result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -14763,19 +15947,19 @@ var ts; } return result || emptyArray; } - function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { + function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; type.properties = getNamedMembers(members); type.callSignatures = callSignatures; type.constructSignatures = constructSignatures; - if (stringIndexType) - type.stringIndexType = stringIndexType; - if (numberIndexType) - type.numberIndexType = numberIndexType; + if (stringIndexInfo) + type.stringIndexInfo = stringIndexInfo; + if (numberIndexInfo) + type.numberIndexInfo = numberIndexInfo; return type; } - function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { - return setObjectTypeMembers(createObjectType(65536 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setObjectTypeMembers(createObjectType(65536 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; @@ -14787,17 +15971,17 @@ var ts; } } switch (location_1.kind) { - case 248 /* SourceFile */: - if (!ts.isExternalModule(location_1)) { + case 252 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -14824,7 +16008,7 @@ var ts; function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) - // and if symbolfrom symbolTable or alias resolution matches the symbol, + // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && canQualifySymbol(symbolFromSymbolTable, meaning); @@ -14838,7 +16022,7 @@ var ts; return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 /* Alias */ && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) { + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 234 /* ExportSpecifier */)) { if (!useOnlyExternalAliasing || // Is this external alias, then use it to name ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { @@ -14875,7 +16059,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 234 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -14910,7 +16094,7 @@ var ts; // export class c { // } // } - // let x: typeof m.c + // const x: typeof m.c // In the above example when we start with checking if typeof m.c symbol is accessible, // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible @@ -14948,8 +16132,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 218 /* ModuleDeclaration */ && declaration.name.kind === 9 /* StringLiteral */) || - (declaration.kind === 248 /* SourceFile */ && ts.isExternalModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 252 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -14963,7 +16146,7 @@ var ts; // because these kind of aliases can be used to name types in declaration file var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 2 /* Export */) && + !(anyImportSyntax.flags & 1 /* Export */) && isDeclarationVisible(anyImportSyntax.parent)) { getNodeLinks(declaration).isVisible = true; if (aliasesToMakeVisible) { @@ -14985,12 +16168,12 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 154 /* TypeQuery */) { + if (entityName.parent.kind === 156 /* TypeQuery */) { // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 135 /* QualifiedName */ || entityName.kind === 166 /* PropertyAccessExpression */ || - entityName.parent.kind === 221 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 137 /* QualifiedName */ || entityName.kind === 170 /* PropertyAccessExpression */ || + entityName.parent.kind === 225 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1536 /* Namespace */; @@ -15024,9 +16207,9 @@ var ts; ts.releaseStringWriter(writer); return result; } - function signatureToString(signature, enclosingDeclaration, flags) { + function signatureToString(signature, enclosingDeclaration, flags, kind) { var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); var result = writer.string(); ts.releaseStringWriter(writer); return result; @@ -15042,18 +16225,39 @@ var ts; } return result; } + function typePredicateToString(typePredicate, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + return result; + } + function visibilityToString(flags) { + if (flags === 8 /* Private */) { + return "private"; + } + if (flags === 16 /* Protected */) { + return "protected"; + } + return "public"; + } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { var node = type.symbol.declarations[0].parent; - while (node.kind === 160 /* ParenthesizedType */) { + while (node.kind === 162 /* ParenthesizedType */) { node = node.parent; } - if (node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 220 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } return undefined; } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 223 /* ModuleBlock */ && + ts.isExternalModuleAugmentation(node.parent.parent); + } function getSymbolDisplayBuilder() { function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { @@ -15062,10 +16266,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: return "(Anonymous class)"; - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return "(Anonymous function)"; } } @@ -15100,7 +16304,7 @@ var ts; parentSymbol = symbol; appendSymbolNameOnly(symbol, writer); } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses + // const the writer know we just wrote out a symbol. The declaration emitter writer uses // this to determine if an import it has previously seen (and not written out) needs // to be written to the file once the walk of the tree is complete. // @@ -15181,7 +16385,7 @@ var ts; writeAnonymousType(type, flags); } else if (type.flags & 256 /* StringLiteral */) { - writer.writeStringLiteral(type.text); + writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } else { // Should never get here @@ -15212,11 +16416,13 @@ var ts; } if (pos < end) { writePunctuation(writer, 25 /* LessThanToken */); - writeType(typeArguments[pos++], 0 /* None */); + writeType(typeArguments[pos], 0 /* None */); + pos++; while (pos < end) { writePunctuation(writer, 24 /* CommaToken */); writeSpace(writer); - writeType(typeArguments[pos++], 0 /* None */); + writeType(typeArguments[pos], 0 /* None */); + pos++; } writePunctuation(writer, 27 /* GreaterThanToken */); } @@ -15239,14 +16445,14 @@ var ts; 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]); + var parent_4 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_3); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_4); // 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, flags); + writeSymbolTypeReference(parent_4, typeArguments, start, i, flags); writePunctuation(writer, 21 /* DotToken */); } } @@ -15308,11 +16514,11 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 64 /* Static */; })); + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 32 /* Static */; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 248 /* SourceFile */ || declaration.parent.kind === 219 /* ModuleBlock */; + return declaration.parent.kind === 252 /* SourceFile */ || declaration.parent.kind === 223 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -15326,19 +16532,38 @@ var ts; writeSpace(writer); buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); } - function getIndexerParameterName(type, indexKind, fallbackName) { - var declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); - if (!declaration) { - // declaration might not be found if indexer was added from the contextual type. - // in this case use fallback name - return fallbackName; + function writeIndexSignature(info, keyword) { + if (info) { + if (info.isReadonly) { + writeKeyword(writer, 127 /* ReadonlyKeyword */); + writeSpace(writer); + } + writePunctuation(writer, 19 /* OpenBracketToken */); + writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); + writePunctuation(writer, 54 /* ColonToken */); + writeSpace(writer); + writeKeyword(writer, keyword); + writePunctuation(writer, 20 /* CloseBracketToken */); + writePunctuation(writer, 54 /* ColonToken */); + writeSpace(writer); + writeType(info.type, 0 /* None */); + writePunctuation(writer, 23 /* SemicolonToken */); + writer.writeLine(); + } + } + function writePropertyWithModifiers(prop) { + if (isReadonlySymbol(prop)) { + writeKeyword(writer, 127 /* ReadonlyKeyword */); + writeSpace(writer); + } + buildSymbolDisplay(prop, writer); + if (prop.flags & 536870912 /* Optional */) { + writePunctuation(writer, 53 /* QuestionToken */); } - ts.Debug.assert(declaration.parameters.length !== 0); - return ts.declarationNameToString(declaration.parameters[0].name); } function writeLiteralType(type, flags) { var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) { + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { writePunctuation(writer, 15 /* OpenBraceToken */); writePunctuation(writer, 16 /* CloseBraceToken */); @@ -15348,7 +16573,7 @@ var ts; if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* OpenParenToken */); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -15360,7 +16585,7 @@ var ts; } writeKeyword(writer, 92 /* NewKeyword */); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -15374,46 +16599,18 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - writeKeyword(writer, 92 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); - writePunctuation(writer, 23 /* SemicolonToken */); - writer.writeLine(); - } - if (resolved.stringIndexType) { - // [x: string]: - writePunctuation(writer, 19 /* OpenBracketToken */); - writer.writeParameter(getIndexerParameterName(resolved, 0 /* String */, /*fallbackName*/ "x")); - writePunctuation(writer, 54 /* ColonToken */); - writeSpace(writer); - writeKeyword(writer, 130 /* StringKeyword */); - writePunctuation(writer, 20 /* CloseBracketToken */); - writePunctuation(writer, 54 /* ColonToken */); - writeSpace(writer); - writeType(resolved.stringIndexType, 0 /* None */); - writePunctuation(writer, 23 /* SemicolonToken */); - writer.writeLine(); - } - if (resolved.numberIndexType) { - // [x: number]: - writePunctuation(writer, 19 /* OpenBracketToken */); - writer.writeParameter(getIndexerParameterName(resolved, 1 /* Number */, /*fallbackName*/ "x")); - writePunctuation(writer, 54 /* ColonToken */); - writeSpace(writer); - writeKeyword(writer, 128 /* NumberKeyword */); - writePunctuation(writer, 20 /* CloseBracketToken */); - writePunctuation(writer, 54 /* ColonToken */); - writeSpace(writer); - writeType(resolved.numberIndexType, 0 /* None */); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } + writeIndexSignature(resolved.stringIndexInfo, 131 /* StringKeyword */); + writeIndexSignature(resolved.numberIndexInfo, 129 /* NumberKeyword */); for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); @@ -15421,20 +16618,14 @@ var ts; var signatures = getSignaturesOfType(t, 0 /* Call */); for (var _f = 0, signatures_1 = signatures; _f < signatures_1.length; _f++) { var signature = signatures_1[_f]; - buildSymbolDisplay(p, writer); - if (p.flags & 536870912 /* Optional */) { - writePunctuation(writer, 53 /* QuestionToken */); - } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + writePropertyWithModifiers(p); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } } else { - buildSymbolDisplay(p, writer); - if (p.flags & 536870912 /* Optional */) { - writePunctuation(writer, 53 /* QuestionToken */); - } + writePropertyWithModifiers(p); writePunctuation(writer, 54 /* ColonToken */); writeSpace(writer); writeType(t, 0 /* None */); @@ -15447,10 +16638,10 @@ var ts; inObjectTypeLiteral = saveInObjectTypeLiteral; } } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaraiton, flags) { + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { var targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); } } function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { @@ -15513,6 +16704,18 @@ var ts; } writePunctuation(writer, 18 /* CloseParenToken */); } + function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 97 /* ThisKeyword */); + } + writeSpace(writer); + writeKeyword(writer, 124 /* IsKeyword */); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8 /* WriteArrowStyleSignature */) { writeSpace(writer); @@ -15522,20 +16725,19 @@ var ts; writePunctuation(writer, 54 /* ColonToken */); } writeSpace(writer); - var returnType; if (signature.typePredicate) { - writer.writeParameter(signature.typePredicate.parameterName); - writeSpace(writer); - writeKeyword(writer, 124 /* IsKeyword */); - writeSpace(writer); - returnType = signature.typePredicate.type; + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); } else { - returnType = getReturnTypeOfSignature(signature); + var returnType = getReturnTypeOfSignature(signature); + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1 /* Construct */) { + writeKeyword(writer, 92 /* NewKeyword */); + writeSpace(writer); + } if (signature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */)) { // Instantiated signature, write type arguments instead // This is achieved by passing in the mapper separately @@ -15551,6 +16753,7 @@ var ts; buildSymbolDisplay: buildSymbolDisplay, buildTypeDisplay: buildTypeDisplay, buildTypeParameterDisplay: buildTypeParameterDisplay, + buildTypePredicateDisplay: buildTypePredicateDisplay, buildParameterDisplay: buildParameterDisplay, buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, @@ -15560,131 +16763,6 @@ var ts; }); } function isDeclarationVisible(node) { - function getContainingExternalModule(node) { - for (; node; node = node.parent) { - if (node.kind === 218 /* ModuleDeclaration */) { - if (node.name.kind === 9 /* StringLiteral */) { - return node; - } - } - else if (node.kind === 248 /* SourceFile */) { - return ts.isExternalModule(node) ? node : undefined; - } - } - ts.Debug.fail("getContainingModule cant reach here"); - } - function isUsedInExportAssignment(node) { - // Get source File and see if it is external module and has export assigned symbol - var externalModule = getContainingExternalModule(node); - var exportAssignmentSymbol; - var resolvedExportSymbol; - if (externalModule) { - // This is export assigned symbol node - var externalModuleSymbol = getSymbolOfNode(externalModule); - exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - var symbolOfNode = getSymbolOfNode(node); - if (isSymbolUsedInExportAssignment(symbolOfNode)) { - return true; - } - // if symbolOfNode is alias declaration, resolve the symbol declaration and check - if (symbolOfNode.flags & 8388608 /* Alias */) { - return isSymbolUsedInExportAssignment(resolveAlias(symbolOfNode)); - } - } - // Check if the symbol is used in export assignment - function isSymbolUsedInExportAssignment(symbol) { - if (exportAssignmentSymbol === symbol) { - return true; - } - if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608 /* Alias */)) { - // if export assigned symbol is alias declaration, resolve the alias - resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol); - if (resolvedExportSymbol === symbol) { - return true; - } - // Container of resolvedExportSymbol is visible - return ts.forEach(resolvedExportSymbol.declarations, function (current) { - while (current) { - if (current === node) { - return true; - } - current = current.parent; - } - }); - } - } - } - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 163 /* BindingElement */: - return isDeclarationVisible(node.parent.parent); - case 211 /* 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 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 213 /* FunctionDeclaration */: - case 217 /* EnumDeclaration */: - case 221 /* 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) & 2 /* Export */) && - !(node.kind !== 221 /* ImportEqualsDeclaration */ && parent_4.kind !== 248 /* 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_4); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - if (node.flags & (16 /* Private */ | 32 /* 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 144 /* Constructor */: - case 148 /* ConstructSignature */: - case 147 /* CallSignature */: - case 149 /* IndexSignature */: - case 138 /* Parameter */: - case 219 /* ModuleBlock */: - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 155 /* TypeLiteral */: - case 151 /* TypeReference */: - case 156 /* ArrayType */: - case 157 /* TupleType */: - case 158 /* UnionType */: - case 159 /* IntersectionType */: - case 160 /* 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 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - return false; - // Type parameters are always visible - case 137 /* TypeParameter */: - // Source file is always visible - case 248 /* SourceFile */: - return true; - // Export assignements do not create name bindings outside the module - case 227 /* ExportAssignment */: - return false; - default: - ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); - } - } if (node) { var links = getNodeLinks(node); if (links.isVisible === undefined) { @@ -15692,13 +16770,89 @@ var ts; } return links.isVisible; } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 167 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 215 /* 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 222 /* ModuleDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 217 /* FunctionDeclaration */: + case 221 /* EnumDeclaration */: + case 225 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent_5 = 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 !== 225 /* ImportEqualsDeclaration */ && parent_5.kind !== 252 /* SourceFile */ && ts.isInAmbientContext(parent_5))) { + return isGlobalSourceFile(parent_5); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent_5); + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + if (node.flags & (8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so const it fall into next case statement + case 146 /* Constructor */: + case 150 /* ConstructSignature */: + case 149 /* CallSignature */: + case 151 /* IndexSignature */: + case 140 /* Parameter */: + case 223 /* ModuleBlock */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 157 /* TypeLiteral */: + case 153 /* TypeReference */: + case 158 /* ArrayType */: + case 159 /* TupleType */: + case 160 /* UnionType */: + case 161 /* IntersectionType */: + case 162 /* 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 227 /* ImportClause */: + case 228 /* NamespaceImport */: + case 230 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 139 /* TypeParameter */: + // Source file is always visible + case 252 /* SourceFile */: + return true; + // Export assignments do not create name bindings outside the module + case 231 /* ExportAssignment */: + return false; + default: + ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); + } + } } function collectLinkedAliases(node) { var exportSymbol; - if (node.parent && node.parent.kind === 227 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 231 /* ExportAssignment */) { exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); } - else if (node.parent.kind === 230 /* ExportSpecifier */) { + else if (node.parent.kind === 234 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -15721,7 +16875,9 @@ var ts; var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, ts.Diagnostics.Cannot_find_name_0, firstIdentifier); - buildVisibleNodeList(importSymbol.declarations); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } } }); } @@ -15748,7 +16904,7 @@ var ts; return false; } resolutionTargets.push(target); - resolutionResults.push(true); + resolutionResults.push(/*items*/ true); resolutionPropertyNames.push(propertyName); return true; } @@ -15788,16 +16944,27 @@ var ts; } function getDeclarationContainer(node) { node = ts.getRootDeclaration(node); - // Parent chain: - // VaribleDeclaration -> VariableDeclarationList -> VariableStatement -> 'Declaration Container' - return node.kind === 211 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; + while (node) { + switch (node.kind) { + case 215 /* VariableDeclaration */: + case 216 /* VariableDeclarationList */: + case 230 /* ImportSpecifier */: + case 229 /* NamedImports */: + case 228 /* NamespaceImport */: + case 227 /* ImportClause */: + node = node.parent; + break; + default: + return node.parent; + } + } } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 // Every class automatically contains a static property member named 'prototype', // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. // It is an error to explicitly declare a static property member with the name 'prototype'. - var classType = getDeclaredTypeOfSymbol(prototype.parent); + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; } // Return the type of the given property in the given type, or undefined if no such property exists @@ -15814,6 +16981,23 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); } + function getTextOfPropertyName(name) { + switch (name.kind) { + case 69 /* Identifier */: + return name.text; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + case 138 /* ComputedPropertyName */: + if (ts.isStringOrNumericLiteral(name.expression.kind)) { + return name.expression.text; + } + } + return undefined; + } + function isComputedNonLiteralName(name) { + return name.kind === 138 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression.kind); + } // Return the inferred type for a binding element function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -15832,13 +17016,18 @@ var ts; return parentType; } var type; - if (pattern.kind === 161 /* ObjectBindingPattern */) { + if (pattern.kind === 165 /* ObjectBindingPattern */) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name_10 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_10)) { + // computed properties with non-literal names are treated as 'any' + return anyType; + } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - type = getTypeOfPropertyOfType(parentType, name_10.text) || - isNumericLiteralName(name_10.text) && getIndexTypeOfType(parentType, 1 /* Number */) || + var text = getTextOfPropertyName(name_10); + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10)); @@ -15873,13 +17062,53 @@ var ts; } return type; } + function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return getTypeFromTypeNode(jsDocType); + } + } + function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + // First, see if this node has an @type annotation on it directly. + var typeTag = ts.getJSDocTypeTag(declaration); + if (typeTag && typeTag.typeExpression) { + return typeTag.typeExpression.type; + } + if (declaration.kind === 215 /* VariableDeclaration */ && + declaration.parent.kind === 216 /* VariableDeclarationList */ && + declaration.parent.parent.kind === 197 /* VariableStatement */) { + // @type annotation might have been on the variable statement, try that instead. + var annotation = ts.getJSDocTypeTag(declaration.parent.parent); + if (annotation && annotation.typeExpression) { + return annotation.typeExpression.type; + } + } + else if (declaration.kind === 140 /* Parameter */) { + // If it's a parameter, see if the parent has a jsdoc comment with an @param + // annotation. + var paramTag = ts.getCorrespondingJSDocParameterTag(declaration); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type; + } + } + return undefined; + } // 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 === 200 /* ForInStatement */) { - return anyType; + if (declaration.flags & 134217728 /* JavaScriptFile */) { + // If this is a variable in a JavaScript file, then use the JSDoc type (if it has + // one as its type), otherwise fallback to the below standard TS codepaths to + // try to figure it out. + var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (type && type !== unknownType) { + return type; + } } - if (declaration.parent.parent.kind === 201 /* ForOfStatement */) { + // A variable declared in a for..in statement is always of type string + if (declaration.parent.parent.kind === 204 /* ForInStatement */) { + return stringType; + } + if (declaration.parent.parent.kind === 205 /* 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, @@ -15893,11 +17122,11 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 138 /* Parameter */) { + if (declaration.kind === 140 /* 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 === 146 /* SetAccessor */ && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 145 /* GetAccessor */); + if (func.kind === 148 /* SetAccessor */ && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 147 /* GetAccessor */); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } @@ -15913,7 +17142,7 @@ var ts; return checkExpressionCached(declaration.initializer); } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 246 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 250 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // If the declaration specifies a binding pattern, use the type implied by the binding pattern @@ -15938,10 +17167,17 @@ var ts; // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType) { var members = {}; + var hasComputedProperties = false; ts.forEach(pattern.elements, function (e) { - var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); var name = e.propertyName || e.name; - var symbol = createSymbol(flags, name.text); + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + hasComputedProperties = true; + return; + } + var text = getTextOfPropertyName(name); + var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); + var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; @@ -15950,6 +17186,9 @@ var ts; if (includePatternInType) { result.pattern = pattern; } + if (hasComputedProperties) { + result.flags |= 67108864 /* ObjectLiteralPatternWithComputedProperties */; + } return result; } // Return the type implied by an array binding pattern @@ -15959,7 +17198,7 @@ var ts; return languageVersion >= 2 /* ES6 */ ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - var elementTypes = ts.map(elements, function (e) { return e.kind === 187 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + var elementTypes = ts.map(elements, function (e) { return e.kind === 191 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { var result = createNewTupleType(elementTypes); result.pattern = pattern; @@ -15975,7 +17214,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, includePatternInType) { - return pattern.kind === 161 /* ObjectBindingPattern */ + return pattern.kind === 165 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType) : getTypeFromArrayBindingPattern(pattern, includePatternInType); } @@ -15997,14 +17236,17 @@ 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 !== 245 /* PropertyAssignment */ ? getWidenedType(type) : type; + if (declaration.kind === 249 /* PropertyAssignment */) { + return type; + } + return getWidenedType(type); } // Rest parameters default to type any[], other parameters default to type any type = declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && compilerOptions.noImplicitAny) { var root = ts.getRootDeclaration(declaration); - if (!isPrivateWithinAmbient(root) && !(root.kind === 138 /* Parameter */ && isPrivateWithinAmbient(root.parent))) { + if (!isPrivateWithinAmbient(root) && !(root.kind === 140 /* Parameter */ && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } } @@ -16019,13 +17261,25 @@ var ts; } // Handle catch clause variables var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 244 /* CatchClause */) { + if (declaration.parent.kind === 248 /* CatchClause */) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 227 /* ExportAssignment */) { + if (declaration.kind === 231 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } + // Handle module.exports = expr + if (declaration.kind === 185 /* BinaryExpression */) { + return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + if (declaration.kind === 170 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 185 /* BinaryExpression */) { + // Handle exports.p = expr or this.p = expr or className.prototype.method = expr + return links.type = checkExpressionCached(declaration.parent.right); + } + } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; @@ -16051,7 +17305,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 145 /* GetAccessor */) { + if (accessor.kind === 147 /* GetAccessor */) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -16067,9 +17321,9 @@ var ts; if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var getter = ts.getDeclarationOfKind(symbol, 145 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 146 /* SetAccessor */); - var type; + var getter = ts.getDeclarationOfKind(symbol, 147 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 148 /* SetAccessor */); + var type = void 0; // First try to see if the user specified a return type on the get-accessor. var getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { @@ -16097,7 +17351,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 145 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 147 /* 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)); } } @@ -16197,9 +17451,9 @@ var ts; if (!node) { return typeParameters; } - if (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */ || - node.kind === 213 /* FunctionDeclaration */ || node.kind === 173 /* FunctionExpression */ || - node.kind === 143 /* MethodDeclaration */ || node.kind === 174 /* ArrowFunction */) { + if (node.kind === 218 /* ClassDeclaration */ || node.kind === 190 /* ClassExpression */ || + node.kind === 217 /* FunctionDeclaration */ || node.kind === 177 /* FunctionExpression */ || + node.kind === 145 /* MethodDeclaration */ || node.kind === 178 /* ArrowFunction */) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -16209,7 +17463,7 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 215 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 219 /* InterfaceDeclaration */); return appendOuterTypeParameters(undefined, declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -16218,8 +17472,8 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 214 /* ClassDeclaration */ || - node.kind === 186 /* ClassExpression */ || node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 219 /* InterfaceDeclaration */ || node.kind === 218 /* ClassDeclaration */ || + node.kind === 190 /* ClassExpression */ || node.kind === 220 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -16246,8 +17500,8 @@ var ts; 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); }); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); + signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; } @@ -16283,9 +17537,6 @@ var ts; } return type.resolvedBaseConstructorType; } - function hasClassBaseType(type) { - return !!ts.forEach(getBaseTypes(type), function (t) { return !!(t.symbol.flags & 32 /* Class */); }); - } function getBaseTypes(type) { var isClass = type.symbol.flags & 32 /* Class */; var isInterface = type.symbol.flags & 64 /* Interface */; @@ -16304,23 +17555,25 @@ var ts; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - var baseContructorType = getBaseConstructorTypeOfClass(type); - if (!(baseContructorType.flags & 80896 /* ObjectType */)) { + var baseConstructorType = getBaseConstructorTypeOfClass(type); + if (!(baseConstructorType.flags & 80896 /* 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 + var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. - baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.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); + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return; @@ -16345,11 +17598,22 @@ var ts; type.resolvedBaseTypes.push(baseType); } } + function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 219 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -16381,8 +17645,8 @@ var ts; function isIndependentInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 215 /* InterfaceDeclaration */) { - if (declaration.flags & 262144 /* ContainsThis */) { + if (declaration.kind === 219 /* InterfaceDeclaration */) { + if (declaration.flags & 16384 /* ContainsThis */) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); @@ -16424,7 +17688,7 @@ var ts; type.typeArguments = type.typeParameters; type.thisType = createType(512 /* TypeParameter */ | 33554432 /* ThisType */); type.thisType.symbol = symbol; - type.thisType.constraint = getTypeWithThisArgument(type); + type.thisType.constraint = type; } } return links.declaredType; @@ -16437,7 +17701,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 216 /* TypeAliasDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 220 /* TypeAliasDeclaration */); var type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -16470,7 +17734,7 @@ var ts; if (!links.declaredType) { var type = createType(512 /* TypeParameter */); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).constraint) { + if (!ts.getDeclarationOfKind(symbol, 139 /* TypeParameter */).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -16521,16 +17785,16 @@ var ts; function isIndependentType(node) { switch (node.kind) { case 117 /* AnyKeyword */: - case 130 /* StringKeyword */: - case 128 /* NumberKeyword */: + case 131 /* StringKeyword */: + case 129 /* NumberKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 9 /* StringLiteral */: + case 164 /* StringLiteralType */: return true; - case 156 /* ArrayType */: + case 158 /* ArrayType */: return isIndependentType(node.elementType); - case 151 /* TypeReference */: + case 153 /* TypeReference */: return isIndependentTypeReference(node); } return false; @@ -16543,7 +17807,7 @@ var ts; // A function-like declaration is considered independent (free of this references) if it has a return type // annotation that is considered independent and if each parameter is considered independent. function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 144 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { + if (node.kind !== 146 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { return false; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -16557,19 +17821,19 @@ var ts; // Returns true if the class or interface member given by the symbol is free of "this" references. The // function may return false for symbols that are actually free of "this" references because it is not // feasible to perform a complete analysis in all cases. In particular, property members with types - // inferred from their initializers and function members with inferred return types are convervatively + // inferred from their initializers and function members with inferred return types are conservatively // assumed not to be free of "this" references. function isIndependentMember(symbol) { if (symbol.declarations && symbol.declarations.length === 1) { var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return isIndependentVariableLikeDeclaration(declaration); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: return isIndependentFunctionLikeDeclaration(declaration); } } @@ -16602,22 +17866,14 @@ var ts; } } } - function addInheritedSignatures(signatures, baseSignatures) { - if (baseSignatures) { - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var signature = baseSignatures_1[_i]; - signatures.push(signature); - } - } - } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { var symbol = type.symbol; type.declaredProperties = getNamedMembers(symbol.members); type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]); type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]); - type.declaredStringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); - type.declaredNumberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); } return type; } @@ -16632,15 +17888,15 @@ var ts; var members = source.symbol.members; var callSignatures = source.declaredCallSignatures; var constructSignatures = source.declaredConstructSignatures; - var stringIndexType = source.declaredStringIndexType; - var numberIndexType = source.declaredNumberIndexType; + var stringIndexInfo = source.declaredStringIndexInfo; + var numberIndexInfo = source.declaredNumberIndexInfo; if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); - stringIndexType = instantiateType(source.declaredStringIndexType, mapper); - numberIndexType = instantiateType(source.declaredNumberIndexType, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } var baseTypes = getBaseTypes(source); if (baseTypes.length) { @@ -16654,11 +17910,11 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); - stringIndexType = stringIndexType || getIndexTypeOfType(instantiatedBaseType, 0 /* String */); - numberIndexType = numberIndexType || getIndexTypeOfType(instantiatedBaseType, 1 /* Number */); + stringIndexInfo = stringIndexInfo || getIndexInfoOfType(instantiatedBaseType, 0 /* String */); + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type) { resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); @@ -16686,17 +17942,17 @@ var ts; return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType) { - if (!hasClassBaseType(classType)) { - return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; - } var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; + } var baseTypeNode = getBaseTypeNodeOfClass(classType); var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { - var baseSig = baseSignatures_2[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -16722,12 +17978,12 @@ var ts; var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); var members = createTupleTypeMemberSymbols(type.elementTypes); addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); } function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { var s = signatureList_1[_i]; - if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreReturnTypes, compareTypesIdentical)) { return s; } } @@ -16788,78 +18044,76 @@ var ts; } return result || emptyArray; } - function getUnionIndexType(types, kind) { + function getUnionIndexInfo(types, kind) { var indexTypes = []; + var isAnyReadonly = false; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; - var indexType = getIndexTypeOfType(type, kind); - if (!indexType) { + var indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { return undefined; } - indexTypes.push(indexType); + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return getUnionType(indexTypes); + return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); } function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union // type use getPropertiesOfType (only the language service uses this). var callSignatures = getUnionSignatures(type.types, 0 /* Call */); var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */); - var stringIndexType = getUnionIndexType(type.types, 0 /* String */); - var numberIndexType = getUnionIndexType(type.types, 1 /* Number */); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); + var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1, type2) { return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } function resolveIntersectionTypeMembers(type) { // The members and properties collections are empty for intersection types. To get all properties of an // intersection type use getPropertiesOfType (only the language service uses this). var callSignatures = emptyArray; var constructSignatures = emptyArray; - var stringIndexType = undefined; - var numberIndexType = undefined; + var stringIndexInfo = undefined; + var numberIndexInfo = undefined; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(t, 1 /* Construct */)); - stringIndexType = intersectTypes(stringIndexType, getIndexTypeOfType(t, 0 /* String */)); - numberIndexType = intersectTypes(numberIndexType, getIndexTypeOfType(t, 1 /* Number */)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; - var members; - var callSignatures; - var constructSignatures; - var stringIndexType; - var numberIndexType; if (type.target) { - members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); - callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); - constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); - stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0 /* String */), type.mapper); - numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1 /* Number */), type.mapper); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); + var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048 /* TypeLiteral */) { - members = symbol.members; - callSignatures = getSignaturesOfSymbol(members["__call"]); - constructSignatures = getSignaturesOfSymbol(members["__new"]); - stringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); - numberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members["__call"]); + var constructSignatures = getSignaturesOfSymbol(members["__new"]); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { // Combinations of function, class, enum and module - members = emptySymbols; - callSignatures = emptyArray; - constructSignatures = emptyArray; + var members = emptySymbols; + var constructSignatures = emptyArray; if (symbol.flags & 1952 /* HasExports */) { members = getExportsOfSymbol(symbol); } - if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { - callSignatures = getSignaturesOfSymbol(symbol); - } if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); @@ -16872,10 +18126,16 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } - stringIndexType = undefined; - numberIndexType = (symbol.flags & 384 /* Enum */) ? stringType : undefined; + var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; + setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -16900,15 +18160,15 @@ var ts; } return type; } - // Return properties of an object type or an empty array for other types + /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { if (type.flags & 80896 /* ObjectType */) { return resolveStructuredTypeMembers(type).properties; } return emptyArray; } - // If the given type is an object type and that type has a property by the given name, - // return the symbol for that property.Otherwise return undefined. + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); @@ -16939,6 +18199,20 @@ var ts; type = getApparentType(type); return type.flags & 49152 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + /** + * The apparent type of a type parameter is the base constraint instantiated with the type parameter + * as the type argument for the 'this' type. + */ + function getApparentTypeOfTypeParameter(type) { + if (!type.resolvedApparentType) { + var constraintType = getConstraintOfTypeParameter(type); + while (constraintType && constraintType.flags & 512 /* TypeParameter */) { + constraintType = getConstraintOfTypeParameter(constraintType); + } + type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); + } + return type.resolvedApparentType; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -16946,12 +18220,7 @@ var ts; */ function getApparentType(type) { if (type.flags & 512 /* TypeParameter */) { - do { - type = getConstraintOfTypeParameter(type); - } while (type && type.flags & 512 /* TypeParameter */); - if (!type) { - type = emptyObjectType; - } + type = getApparentTypeOfTypeParameter(type); } if (type.flags & 258 /* StringLike */) { type = globalStringType; @@ -16970,12 +18239,15 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = (containingType.flags & 32768 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 /* Private */ | 32 /* Protected */))) { + if (prop && !(getDeclarationFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))) { + commonFlags &= prop.flags; if (!props) { props = [prop]; } @@ -17004,7 +18276,10 @@ var ts; } propTypes.push(getTypeOfSymbol(prop)); } - var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */, name); + var result = createSymbol(4 /* Property */ | + 67108864 /* Transient */ | + 268435456 /* SyntheticProperty */ | + commonFlags, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & 16384 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -17061,33 +18336,48 @@ var ts; function getSignaturesOfType(type, kind) { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function typeHasConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & (80896 /* ObjectType */ | 16384 /* Union */)) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.constructSignatures.length > 0; - } - return false; - } - function typeHasCallOrConstructSignatures(type) { - var apparentType = getApparentType(type); - if (apparentType.flags & 130048 /* StructuredType */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; - } - return false; - } - function getIndexTypeOfStructuredType(type, kind) { + function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 130048 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); - return kind === 0 /* String */ ? resolved.stringIndexType : resolved.numberIndexType; + return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexTypeOfType(type, kind) { return getIndexTypeOfStructuredType(getApparentType(type), kind); } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectLiteralType(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.name)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + return getUnionType(propTypes); + } + return undefined; + } + function getTypeParametersFromJSDocTemplate(declaration) { + if (declaration.flags & 134217728 /* JavaScriptFile */) { + var templateTag = ts.getJSDocTemplateTag(declaration); + if (templateTag) { + return getTypeParametersFromDeclaration(templateTag.typeParameters); + } + } + return undefined; + } // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(typeParameterDeclarations) { @@ -17110,33 +18400,77 @@ var ts; return result; } function isOptionalParameter(node) { + if (node.flags & 134217728 /* JavaScriptFile */) { + if (node.type && node.type.kind === 264 /* JSDocOptionalType */) { + return true; + } + var paramTag = ts.getCorrespondingJSDocParameterTag(node); + if (paramTag) { + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 264 /* JSDocOptionalType */; + } + } + } if (ts.hasQuestionToken(node)) { return true; } if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = signatureDeclaration.parameters.indexOf(node); + var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } return false; } + function createTypePredicateFromTypePredicateNode(node) { + if (node.parameterName.kind === 69 /* Identifier */) { + var parameterName = node.parameterName; + return { + kind: 1 /* Identifier */, + parameterName: parameterName ? parameterName.text : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0 /* This */, + type: getTypeFromTypeNode(node.type) + }; + } + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { - var classType = declaration.kind === 144 /* Constructor */ ? + var classType = declaration.kind === 146 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; + declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : + getTypeParametersFromJSDocTemplate(declaration); var parameters = []; var hasStringLiterals = false; var minArgumentCount = -1; - for (var i = 0, n = declaration.parameters.length; i < n; i++) { + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var returnType = undefined; + var typePredicate = undefined; + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (var i = isJSConstructSignature ? 1 : 0, n = declaration.parameters.length; i < n; i++) { var param = declaration.parameters[i]; - parameters.push(param.symbol); - if (param.type && param.type.kind === 9 /* StringLiteral */) { + var paramSymbol = param.symbol; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.name, 107455 /* Value */, undefined, undefined); + paramSymbol = resolvedSymbol; + } + parameters.push(paramSymbol); + if (param.type && param.type.kind === 164 /* StringLiteralType */) { hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken) { @@ -17152,27 +18486,30 @@ var ts; if (minArgumentCount < 0) { minArgumentCount = declaration.parameters.length; } - var returnType; - var typePredicate; - if (classType) { + if (isJSConstructSignature) { + minArgumentCount--; + returnType = getTypeFromTypeNode(declaration.parameters[0].type); + } + else if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); - if (declaration.type.kind === 150 /* 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) - }; + if (declaration.type.kind === 152 /* TypePredicate */) { + typePredicate = createTypePredicateFromTypePredicateNode(declaration.type); } } else { + if (declaration.flags & 134217728 /* JavaScriptFile */) { + var type = getReturnTypeFromJSDocComment(declaration); + if (type && type !== unknownType) { + returnType = type; + } + } // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 145 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 146 /* SetAccessor */); + if (declaration.kind === 147 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 148 /* SetAccessor */); returnType = getAnnotatedAccessorType(setter); } if (!returnType && ts.nodeIsMissing(declaration.body)) { @@ -17190,19 +18527,20 @@ var ts; for (var i = 0, len = symbol.declarations.length; i < len; i++) { var node = symbol.declarations[i]; switch (node.kind) { - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 265 /* JSDocFunctionType */: // Don't include signature if node is the implementation of an overloaded function. A node is considered // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). @@ -17217,12 +18555,22 @@ var ts; } return result; } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return unknownType; } - var type; + var type = void 0; if (signature.target) { type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } @@ -17258,7 +18606,7 @@ var ts; return anyType; } function getSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature) { if (!signature.typeParameters) @@ -17268,7 +18616,7 @@ var ts; signature.erasedSignatureCache = instantiateSignature(getErasedSignature(signature.target), signature.mapper); } else { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); } } return signature.erasedSignatureCache; @@ -17279,7 +18627,7 @@ 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 === 144 /* Constructor */ || signature.declaration.kind === 148 /* ConstructSignature */; + var isConstructor = signature.declaration.kind === 146 /* Constructor */ || signature.declaration.kind === 150 /* ConstructSignature */; var type = createObjectType(65536 /* Anonymous */ | 262144 /* FromSignature */); type.members = emptySymbols; type.properties = emptyArray; @@ -17293,7 +18641,7 @@ var ts; return symbol.members["__index"]; } function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 128 /* NumberKeyword */ : 130 /* StringKeyword */; + var syntaxKind = kind === 1 /* Number */ ? 129 /* NumberKeyword */ : 131 /* StringKeyword */; var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -17309,26 +18657,51 @@ var ts; } return undefined; } - function getIndexTypeOfSymbol(symbol, kind) { - var declaration = getIndexDeclarationOfSymbol(symbol, kind); - return declaration - ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType - : undefined; + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; } - function getConstraintOfTypeParameter(type) { - if (!type.constraint) { - if (type.target) { - var targetConstraint = getConstraintOfTypeParameter(type.target); - type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (declaration.flags & 64 /* Readonly */) !== 0, declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 139 /* TypeParameter */).constraint; + } + function hasConstraintReferenceTo(type, target) { + var checked; + while (type && !(type.flags & 33554432 /* ThisType */) && type.flags & 512 /* TypeParameter */ && !ts.contains(checked, type)) { + if (type === target) { + return true; + } + (checked || (checked = [])).push(type); + var constraintDeclaration = getConstraintDeclaration(type); + type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration); + } + return false; + } + function getConstraintOfTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 137 /* TypeParameter */).constraint); + var constraintDeclaration = getConstraintDeclaration(typeParameter); + var constraint = getTypeFromTypeNode(constraintDeclaration); + if (hasConstraintReferenceTo(constraint, typeParameter)) { + error(constraintDeclaration, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + constraint = unknownType; + } + typeParameter.constraint = constraint; } } - return type.constraint === noConstraintType ? undefined : type.constraint; + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 137 /* TypeParameter */).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 139 /* TypeParameter */).parent); } function getTypeListId(types) { if (types) { @@ -17373,50 +18746,6 @@ var ts; } return type; } - function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode, typeParameterSymbol) { - var links = getNodeLinks(typeReferenceNode); - if (links.isIllegalTypeReferenceInConstraint !== undefined) { - return links.isIllegalTypeReferenceInConstraint; - } - // bubble up to the declaration - var currentNode = typeReferenceNode; - // forEach === exists - while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { - 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 === 137 /* TypeParameter */; - return links.isIllegalTypeReferenceInConstraint; - } - function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { - var typeParameterSymbol; - function check(n) { - if (n.kind === 151 /* TypeReference */ && n.typeName.kind === 69 /* Identifier */) { - var links = getNodeLinks(n); - if (links.isIllegalTypeReferenceInConstraint === undefined) { - var symbol = resolveName(typeParameter, n.typeName.text, 793056 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (symbol && (symbol.flags & 262144 /* TypeParameter */)) { - // 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 - // symbol.declaration.parent === typeParameter.parent - // -> 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; }); - } - } - if (links.isIllegalTypeReferenceInConstraint) { - error(typeParameter, ts.Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); - } - } - ts.forEachChild(n, check); - } - if (typeParameter.constraint) { - typeParameterSymbol = getSymbolOfNode(typeParameter); - check(typeParameter.constraint); - } - } // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node, symbol) { var type = getDeclaredTypeOfSymbol(symbol); @@ -17461,31 +18790,74 @@ var ts; } // 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 getTypeReferenceName(node) { + switch (node.kind) { + case 153 /* TypeReference */: + return node.typeName; + case 263 /* JSDocTypeReference */: + return node.name; + case 192 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + if (ts.isSupportedExpressionWithTypeArguments(node)) { + return node.expression; + } + } + return undefined; + } + function resolveTypeReferenceName(node, typeReferenceName) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, 793056 /* Type */) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + if (symbol === unknownSymbol) { + return unknownType; + } + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getTypeFromClassOrInterfaceReference(node, symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol); + } + if (symbol.flags & 107455 /* Value */ && node.kind === 263 /* JSDocTypeReference */) { + // A JSDocTypeReference may have resolved to a value (as opposed to a type). In + // that case, the type of this reference is just the type of the value we resolved + // to. + return getTypeOfSymbol(symbol); + } + return getTypeFromNonGenericTypeReference(node, symbol); + } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - // We only support expressions that are simple qualified names. For other expressions this produces undefined. - var typeNameOrExpression = node.kind === 151 /* 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); + var symbol = void 0; + var type = void 0; + if (node.kind === 263 /* JSDocTypeReference */) { + var typeReferenceName = getTypeReferenceName(node); + symbol = resolveTypeReferenceName(node, typeReferenceName); + type = getTypeReferenceType(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + else { + // We only support expressions that are simple qualified names. For other expressions this produces undefined. + var typeNameOrExpression = node.kind === 153 /* TypeReference */ ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056 /* Type */) || unknownSymbol; + type = symbol === unknownSymbol ? unknownType : + symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : + symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : + getTypeFromNonGenericTypeReference(node, symbol); + } // 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; @@ -17510,9 +18882,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: return declaration; } } @@ -17544,10 +18916,6 @@ var ts; if (arity === void 0) { arity = 0; } return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } - function tryGetGlobalType(name, arity) { - if (arity === void 0) { arity = 0; } - return getTypeOfGlobalSymbol(getGlobalSymbol(name, 793056 /* Type */, /*diagnostic*/ undefined), arity); - } /** * Returns a type that is inside a namespace at the global scope, e.g. * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type @@ -17667,7 +19035,7 @@ var ts; // a named type that circularly references itself. function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { - return emptyObjectType; + return emptyUnionType; } var typeSet = []; addTypesToSet(typeSet, types, 16384 /* Union */); @@ -17739,27 +19107,43 @@ var ts; } return links.resolvedType; } - function getStringLiteralType(node) { - if (ts.hasProperty(stringLiteralTypes, node.text)) { - return stringLiteralTypes[node.text]; + function getStringLiteralTypeForText(text) { + if (ts.hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; } - var type = stringLiteralTypes[node.text] = createType(256 /* StringLiteral */); - type.text = ts.getTextOfNode(node); + var type = stringLiteralTypes[text] = createType(256 /* StringLiteral */); + type.text = text; return type; } - function getTypeFromStringLiteral(node) { + function getTypeFromStringLiteralTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralType(node); + links.resolvedType = getStringLiteralTypeForText(node.text); + } + return links.resolvedType; + } + function getTypeFromJSDocVariadicType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + function getTypeFromJSDocTupleType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var types = ts.map(node.types, getTypeFromTypeNode); + links.resolvedType = createTupleType(types); } return links.resolvedType; } function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 215 /* InterfaceDeclaration */)) { - if (!(container.flags & 64 /* Static */) && - (container.kind !== 144 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { + if (parent && (ts.isClassLike(parent) || parent.kind === 219 /* InterfaceDeclaration */)) { + if (!(container.flags & 32 /* Static */) && + (container.kind !== 146 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -17776,49 +19160,65 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 117 /* AnyKeyword */: + case 254 /* JSDocAllType */: + case 255 /* JSDocUnknownType */: return anyType; - case 130 /* StringKeyword */: + case 131 /* StringKeyword */: return stringType; - case 128 /* NumberKeyword */: + case 129 /* NumberKeyword */: return numberType; case 120 /* BooleanKeyword */: return booleanType; - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: return esSymbolType; case 103 /* VoidKeyword */: return voidType; - case 97 /* ThisKeyword */: + case 163 /* ThisType */: return getTypeFromThisTypeNode(node); - case 9 /* StringLiteral */: - return getTypeFromStringLiteral(node); - case 151 /* TypeReference */: + case 164 /* StringLiteralType */: + return getTypeFromStringLiteralTypeNode(node); + case 153 /* TypeReference */: + case 263 /* JSDocTypeReference */: return getTypeFromTypeReference(node); - case 150 /* TypePredicate */: + case 152 /* TypePredicate */: return booleanType; - case 188 /* ExpressionWithTypeArguments */: + case 192 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 154 /* TypeQuery */: + case 156 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 156 /* ArrayType */: + case 158 /* ArrayType */: + case 256 /* JSDocArrayType */: return getTypeFromArrayTypeNode(node); - case 157 /* TupleType */: + case 159 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 158 /* UnionType */: + case 160 /* UnionType */: + case 257 /* JSDocUnionType */: return getTypeFromUnionTypeNode(node); - case 159 /* IntersectionType */: + case 161 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 160 /* ParenthesizedType */: + case 162 /* ParenthesizedType */: + case 259 /* JSDocNullableType */: + case 260 /* JSDocNonNullableType */: + case 267 /* JSDocConstructorType */: + case 268 /* JSDocThisType */: + case 264 /* JSDocOptionalType */: return getTypeFromTypeNode(node.type); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 155 /* TypeLiteral */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 157 /* TypeLiteral */: + case 265 /* JSDocFunctionType */: + case 261 /* JSDocRecordType */: 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 69 /* Identifier */: - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); + case 258 /* JSDocTupleType */: + return getTypeFromJSDocTupleType(node); + case 266 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -17875,18 +19275,22 @@ var ts; return t; }; } - function createInferenceMapper(context) { - var mapper = function (t) { - for (var i = 0; i < context.typeParameters.length; i++) { - if (t === context.typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); + function getInferenceMapper(context) { + if (!context.mapper) { + var mapper = function (t) { + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (t === typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } } - } - return t; - }; - mapper.context = context; - return mapper; + return t; + }; + mapper.context = context; + context.mapper = mapper; + } + return context.mapper; } function identityMapper(type) { return type; @@ -17894,31 +19298,44 @@ var ts; function combineTypeMappers(mapper1, mapper2) { return function (t) { return instantiateType(mapper1(t), mapper2); }; } - function instantiateTypeParameter(typeParameter, mapper) { + function cloneTypeParameter(typeParameter) { var result = createType(512 /* TypeParameter */); result.symbol = typeParameter.symbol; - if (typeParameter.constraint) { - result.constraint = instantiateType(typeParameter.constraint, mapper); + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; } else { - result.target = typeParameter; - result.mapper = mapper; + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; } - return result; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } } if (signature.typePredicate) { - freshTypePredicate = { - parameterName: signature.typePredicate.parameterName, - parameterIndex: signature.typePredicate.parameterIndex, - type: instantiateType(signature.typePredicate.type, mapper) - }; + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; @@ -17987,30 +19404,33 @@ var ts; } return type; } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return isContextSensitiveFunctionLikeDeclaration(node); - case 165 /* ObjectLiteralExpression */: + case 169 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return node.operatorToken.kind === 52 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 245 /* PropertyAssignment */: + case 249 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return isContextSensitive(node.expression); } return false; @@ -18036,9 +19456,12 @@ var ts; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); } - function compareTypes(source, target) { + function compareTypesIdentical(source, target) { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; } + function compareTypesAssignable(source, target) { + return checkTypeRelatedTo(source, target, assignableRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; + } function isTypeSubtypeOf(source, target) { return checkTypeSubtypeOf(source, target, /*errorNode*/ undefined); } @@ -18051,10 +19474,127 @@ var ts; function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } - function isSignatureAssignableTo(source, target) { - var sourceType = getOrCreateTypeFromSignature(source); - var targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, /*errorNode*/ undefined); + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return 0 /* False */; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1 /* True */; + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + var sourceParams = source.parameters; + var targetParams = target.parameters; + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(sourceParams[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(targetParams[i]) : getRestTypeOfSignature(target); + var related = compareTypes(t, s, /*reportErrors*/ false) || compareTypes(s, t, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name); + } + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } + else { + result &= compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */) { + var sourceIdentifierPredicate = source; + var targetIdentifierPredicate = target; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 /* False */ && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, /*errorNode*/ undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, /*errorNode*/ undefined)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + // If both have rest parameters, get the max and add 1 to + // compensate for the rest parameter. + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + // Return the count for whichever signature doesn't have rest parameters. + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). @@ -18074,22 +19614,12 @@ var ts; var expandingFlags; var depth = 0; var overflow = false; - var elaborateErrors = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, errorNode !== undefined, headMessage); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (overflow) { error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { - // If we already computed this relation, but in a context where we didn't want to report errors (e.g. overload resolution), - // then we'll only have a top-level error (e.g. 'Class X does not implement interface Y') without any details. If this happened, - // request a recompuation to get a complete error message. This will be skipped if we've already done this computation in a context - // where errors were being reported. - if (errorInfo.next === undefined) { - errorInfo = undefined; - elaborateErrors = true; - isRelatedTo(source, target, errorNode !== undefined, headMessage); - } if (containingMessageChain) { errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } @@ -18097,6 +19627,7 @@ var ts; } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { + ts.Debug.assert(!!errorNode); errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } function reportRelationError(message, source, target) { @@ -18128,6 +19659,11 @@ var ts; return -1 /* True */; if (source.flags & 128 /* Enum */ && target === numberType) return -1 /* True */; + if (source.flags & 128 /* Enum */ && target.flags & 128 /* Enum */) { + if (result = enumRelatedTo(source, target)) { + return result; + } + } if (source.flags & 256 /* StringLiteral */ && target === stringType) return -1 /* True */; if (relation === assignableRelation) { @@ -18136,6 +19672,9 @@ var ts; if (source === numberType && target.flags & 128 /* Enum */) return -1 /* True */; } + if (source.flags & 8 /* Boolean */ && target.flags & 8 /* Boolean */) { + return -1 /* True */; + } if (source.flags & 1048576 /* FreshObjectLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -18200,14 +19739,14 @@ var ts; } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var apparentType = getApparentType(source); + var apparentSource = getApparentType(source); // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (apparentType.flags & (80896 /* ObjectType */ | 32768 /* Intersection */) && target.flags & 80896 /* ObjectType */) { + if (apparentSource.flags & (80896 /* ObjectType */ | 32768 /* Intersection */) && target.flags & 80896 /* ObjectType */) { // Report structural errors only if we haven't reported any errors yet - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; - if (result = objectTypeRelatedTo(apparentType, source, target, reportStructuralErrors)) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726 /* Primitive */); + if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; } @@ -18229,9 +19768,6 @@ var ts; } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & 512 /* TypeParameter */ && target.flags & 512 /* TypeParameter */) { - return typeParameterIdenticalTo(source, target); - } if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -18250,7 +19786,7 @@ var ts; if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (relation === assignableRelation && (type === globalObjectType || resolved.properties.length === 0) || - resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) { + resolved.stringIndexInfo || resolved.numberIndexInfo || getPropertyOfType(type, name)) { return true; } } @@ -18265,7 +19801,7 @@ var ts; return false; } function hasExcessProperties(source, target, reportErrors) { - if (someConstituentTypeHasKind(target, 80896 /* ObjectType */)) { + if (!(target.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 80896 /* ObjectType */)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -18273,6 +19809,7 @@ var ts; // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. + ts.Debug.assert(!!errorNode); errorNode = prop.valueDeclaration; reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } @@ -18287,7 +19824,7 @@ var ts; var sourceTypes = source.types; for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { var sourceType = sourceTypes_1[_i]; - var related = typeRelatedToSomeType(sourceType, target, false); + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); if (!related) { return 0 /* False */; } @@ -18347,8 +19884,9 @@ var ts; if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } + var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1 /* True */; - for (var i = 0; i < targets.length; i++) { + for (var i = 0; i < length; i++) { var related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return 0 /* False */; @@ -18357,34 +19895,24 @@ var ts; } return result; } - function typeParameterIdenticalTo(source, target) { - if (source.symbol.name !== target.symbol.name) { - return 0 /* False */; - } - // covers case when both type parameters does not have constraint (both equal to noConstraintType) - if (source.constraint === target.constraint) { - return -1 /* True */; - } - if (source.constraint === noConstraintType || target.constraint === noConstraintType) { - return 0 /* False */; - } - return isIdenticalTo(source.constraint, target.constraint); - } // Determine if two object types are related by structure. First, check if the result is already available in the global cache. // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function objectTypeRelatedTo(apparentSource, originalSource, target, reportErrors) { + function objectTypeRelatedTo(source, originalSource, target, reportErrors) { if (overflow) { return 0 /* False */; } - var id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { - // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate - // errors, we can use the cached value. Otherwise, recompute the relation - if (!elaborateErrors || (related === 3 /* FailedAndReported */)) { + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported + // failure and continue computing the relation such that errors get reported. + relation[id] = 3 /* FailedAndReported */; + } + else { return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; } } @@ -18406,13 +19934,13 @@ var ts; maybeStack = []; expandingFlags = 0; } - sourceStack[depth] = apparentSource; + sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; @@ -18421,15 +19949,15 @@ var ts; result = 1 /* Maybe */; } else { - result = propertiesRelatedTo(apparentSource, target, reportErrors); + result = propertiesRelatedTo(source, target, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 0 /* Call */, reportErrors); + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, 1 /* Construct */, reportErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportErrors); if (result) { - result &= stringIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= indexTypesRelatedTo(source, originalSource, target, 0 /* String */, reportErrors); if (result) { - result &= numberIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= indexTypesRelatedTo(source, originalSource, target, 1 /* Number */, reportErrors); } } } @@ -18472,23 +20000,23 @@ var ts; else if (!(targetProp.flags & 134217728 /* Prototype */)) { var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); - if (sourcePropFlags & 16 /* Private */ || targetPropFlags & 16 /* Private */) { + if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & 16 /* Private */ && targetPropFlags & 16 /* Private */) { + if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 16 /* Private */ ? source : target), typeToString(sourcePropFlags & 16 /* Private */ ? target : source)); + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); } } return 0 /* False */; } } - else if (targetPropFlags & 32 /* Protected */) { + else if (targetPropFlags & 16 /* Protected */) { var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32 /* Class */; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; - var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); + var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; + var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); @@ -18496,7 +20024,7 @@ var ts; return 0 /* False */; } } - else if (sourcePropFlags & 32 /* Protected */) { + else if (sourcePropFlags & 16 /* Protected */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -18561,154 +20089,49 @@ var ts; } var sourceSignatures = getSignaturesOfType(source, kind); var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0 /* False */; + } + } var result = -1 /* True */; var saveErrorInfo = errorInfo; - if (kind === 1 /* Construct */) { - // Only want to compare the construct signatures for abstractness guarantees. - // Because the "abstractness" of a class is the same across all construct signatures - // (internally we are checking the corresponding declaration), it is enough to perform - // the check and report an error once over all pairs of source and target construct signatures. - // - // sourceSig and targetSig are (possibly) undefined. - // - // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. - var sourceSig = sourceSignatures[0]; - var targetSig = targetSignatures[0]; - result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); - if (result !== -1 /* True */) { - return result; - } - } outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; - if (!t.hasStringLiterals || target.flags & 262144 /* FromSignature */) { - var localErrors = reportErrors; - var checkedAbstractAssignability = false; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { - var related = signatureRelatedTo(s, t, localErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; - } - // Only report errors from the first failure - localErrors = false; - } + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; } - return 0 /* False */; + shouldElaborateErrors = false; } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; } return result; - function abstractSignatureRelatedTo(source, sourceSig, target, targetSig) { - if (sourceSig && targetSig) { - var sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - var targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); - if (!sourceDecl) { - // If the source object isn't itself a class declaration, it can be freely assigned, regardless - // of whether the constructed object is abstract or not. - return -1 /* True */; - } - var sourceErasedSignature = getErasedSignature(sourceSig); - var targetErasedSignature = getErasedSignature(targetSig); - var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128 /* Abstract */; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128 /* Abstract */; - if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { - // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0 /* False */; - } - } - return -1 /* True */; - } } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ function signatureRelatedTo(source, target, reportErrors) { - if (source === target) { - return -1 /* True */; - } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return 0 /* False */; - } - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var checkCount; - if (source.hasRestParameter && target.hasRestParameter) { - checkCount = sourceMax > targetMax ? sourceMax : targetMax; - sourceMax--; - targetMax--; - } - else if (source.hasRestParameter) { - sourceMax--; - checkCount = targetMax; - } - else if (target.hasRestParameter) { - targetMax--; - checkCount = sourceMax; - } - else { - checkCount = sourceMax < targetMax ? sourceMax : targetMax; - } - // Spec 1.0 Section 3.8.3 & 3.8.4: - // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1 /* True */; - for (var i = 0; i < checkCount; i++) { - var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); - var saveErrorInfo = errorInfo; - var related = isRelatedTo(s, t, reportErrors); - if (!related) { - related = isRelatedTo(t, s, false); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); - } - return 0 /* False */; - } - errorInfo = saveErrorInfo; - } - 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 targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) - return result; - var sourceReturnType = getReturnTypeOfSignature(source); - return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); + return compareSignaturesRelated(source, target, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -18717,8 +20140,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var i = 0, len = sourceSignatures.length; i < len; ++i) { - var related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + for (var i = 0, len = sourceSignatures.length; i < len; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); if (!related) { return 0 /* False */; } @@ -18726,83 +20149,128 @@ var ts; } return result; } - function stringIndexTypesRelatedTo(source, originalSource, target, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(0 /* String */, source, target); - } - var targetType = getIndexTypeOfType(target, 0 /* String */); - if (targetType) { - if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { - // non-primitive assignment to any is always allowed, eg - // `var x: { [index: string]: any } = { property: 12 };` - return -1 /* True */; - } - var sourceType = getIndexTypeOfType(source, 0 /* String */); - if (!sourceType) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1 /* True */; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.name)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0 /* False */; } - return 0 /* False */; + result &= related; } - var related = isRelatedTo(sourceType, targetType, reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return 0 /* False */; - } - return related; } - return -1 /* True */; + return result; } - function numberIndexTypesRelatedTo(source, originalSource, target, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(1 /* Number */, source, target); + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); } - var targetType = getIndexTypeOfType(target, 1 /* Number */); - if (targetType) { - if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { - // non-primitive assignment to any is always allowed, eg - // `var x: { [index: number]: any } = { property: 12 };` - return -1 /* True */; - } - var sourceStringType = getIndexTypeOfType(source, 0 /* String */); - var sourceNumberType = getIndexTypeOfType(source, 1 /* Number */); - if (!(sourceStringType || sourceNumberType)) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); - } - return 0 /* False */; - } - var related; - if (sourceStringType && sourceNumberType) { - // If we know for sure we're testing both string and numeric index types then only report errors from the second one - related = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors); - } - else { - related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); - } - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return 0 /* False */; - } - return related; - } - return -1 /* True */; + return related; } - function indexTypesIdenticalTo(indexKind, source, target) { - var targetType = getIndexTypeOfType(target, indexKind); - var sourceType = getIndexTypeOfType(source, indexKind); - if (!sourceType && !targetType) { + function indexTypesRelatedTo(source, originalSource, target, kind, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */))) { + // Index signature of type any permits assignment from everything but primitives return -1 /* True */; } - if (sourceType && targetType) { - return isRelatedTo(sourceType, targetType); + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isObjectLiteralType(source)) { + var related = -1 /* True */; + if (kind === 0 /* String */) { + var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } return 0 /* False */; } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1 /* True */; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0 /* False */; + } + function enumRelatedTo(source, target) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & 128 /* ConstEnum */ || + target.symbol.flags & 128 /* ConstEnum */) { + return 0 /* False */; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + return 0 /* False */; + } + } + } + return -1 /* True */; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = sourceSignature.declaration.flags & (8 /* Private */ | 16 /* Protected */); + var targetAccessibility = targetSignature.declaration.flags & (8 /* Private */ | 16 /* Protected */); + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === 8 /* Private */) { + return true; + } + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { + return true; + } + // Only a public signature is assignable to public signature. + if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type) { + if (type.flags & 65536 /* Anonymous */) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && declaration.flags & 128 /* Abstract */) { + return true; + } + } + } + return 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, @@ -18826,7 +20294,7 @@ var ts; return false; } function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypes) !== 0 /* False */; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; } function compareProperties(sourceProp, targetProp, compareTypes) { // Two members are considered identical when @@ -18835,8 +20303,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (16 /* Private */ | 32 /* Protected */); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (16 /* Private */ | 32 /* Protected */); + var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (8 /* Private */ | 16 /* Protected */); + var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (8 /* Private */ | 16 /* Protected */); if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -18850,41 +20318,52 @@ var ts; return 0 /* False */; } } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0 /* False */; + } return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } - function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + function isMatchingSignature(source, target, partialMatch) { + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters and no more overall parameters than the source signature (where a signature with a rest + // parameter is always considered to have more overall parameters than one without). + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. if (source === target) { return -1 /* True */; } - if (source.parameters.length !== target.parameters.length || - source.minArgumentCount !== target.minArgumentCount || - source.hasRestParameter !== target.hasRestParameter) { - if (!partialMatch || - source.parameters.length < target.parameters.length && !source.hasRestParameter || - source.minArgumentCount > target.minArgumentCount) { - return 0 /* False */; - } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0 /* False */; } - var result = -1 /* True */; - if (source.typeParameters && target.typeParameters) { - if (source.typeParameters.length !== target.typeParameters.length) { - return 0 /* False */; - } - for (var i = 0, len = source.typeParameters.length; i < len; ++i) { - var related = compareTypes(source.typeParameters[i], target.typeParameters[i]); - if (!related) { - return 0 /* False */; - } - result &= related; - } - } - else if (source.typeParameters || target.typeParameters) { + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) { return 0 /* False */; } // Spec 1.0 Section 3.8.3 & 3.8.4: // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N source = getErasedSignature(source); target = getErasedSignature(target); + var result = -1 /* True */; var targetLen = target.parameters.length; for (var i = 0; i < targetLen; i++) { var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); @@ -18951,12 +20430,17 @@ var ts; return type.flags & 4096 /* Reference */ && type.target === globalArrayType; } function isArrayLikeType(type) { - // A type is array-like if it is not the undefined or null type and if it is assignable to any[] - return !(type.flags & (32 /* Undefined */ | 64 /* Null */)) && isTypeAssignableTo(type, anyArrayType); + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return type.flags & 4096 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & (32 /* Undefined */ | 64 /* Null */)) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } + function isStringLiteralType(type) { + return type.flags & 256 /* StringLiteral */; + } /** * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. @@ -18964,6 +20448,15 @@ var ts; function isTupleType(type) { return !!(type.flags & 8192 /* Tuple */); } + /** + * Return true if type was inferred from an object literal or written as an object type literal + * with no call or construct signatures. + */ + function isObjectLiteralType(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && + getSignaturesOfType(type, 0 /* Call */).length === 0 && + getSignaturesOfType(type, 1 /* Construct */).length === 0; + } function getRegularTypeOfObjectLiteral(type) { if (type.flags & 1048576 /* FreshObjectLiteral */) { var regularType = type.regularType; @@ -18974,8 +20467,8 @@ var ts; regularType.properties = type.properties; regularType.callSignatures = type.callSignatures; regularType.constructSignatures = type.constructSignatures; - regularType.stringIndexType = type.stringIndexType; - regularType.numberIndexType = type.numberIndexType; + regularType.stringIndexInfo = type.stringIndexInfo; + regularType.numberIndexInfo = type.numberIndexInfo; type.regularType = regularType; } return regularType; @@ -19000,13 +20493,9 @@ var ts; } members[p.name] = p; }); - var stringIndexType = getIndexTypeOfType(type, 0 /* String */); - var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); - if (stringIndexType) - stringIndexType = getWidenedType(stringIndexType); - if (numberIndexType) - numberIndexType = getWidenedType(numberIndexType); - return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); + var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); } function getWidenedType(type) { if (type.flags & 6291456 /* RequiresWidening */) { @@ -19078,22 +20567,22 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 138 /* Parameter */: + case 140 /* 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 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -19140,13 +20629,7 @@ var ts; } } function createInferenceContext(typeParameters, inferUnionTypes) { - var inferences = []; - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var unused = typeParameters_1[_i]; - inferences.push({ - primary: undefined, secondary: undefined, isFixed: false - }); - } + var inferences = ts.map(typeParameters, createTypeInferencesObject); return { typeParameters: typeParameters, inferUnionTypes: inferUnionTypes, @@ -19154,11 +20637,19 @@ var ts; inferredTypes: new Array(typeParameters.length) }; } + function createTypeInferencesObject() { + return { + primary: undefined, + secondary: undefined, + isFixed: false + }; + } function inferTypes(context, source, target) { var sourceStack; var targetStack; var depth = 0; var inferiority = 0; + var visited = {}; inferFromTypes(source, target); function isInProcess(source, target) { for (var i = 0; i < depth; i++) { @@ -19169,6 +20660,29 @@ var ts; return false; } function inferFromTypes(source, target) { + if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || + source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { + // Source and target are both unions or both intersections. First, find each + // target constituent type that has an identically matching source constituent + // type, and for each such target constituent type infer from the type to itself. + // When inferring from a type to itself we effectively find all type parameter + // occurrences within that type and infer themselves as their type arguments. + var matchingTypes = void 0; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (typeIdenticalToSomeType(t, source.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } if (target.flags & 512 /* TypeParameter */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). @@ -19221,10 +20735,10 @@ var ts; else if (target.flags & 49152 /* UnionOrIntersection */) { var targetTypes = target.types; var typeParameterCount = 0; - var typeParameter; + var typeParameter = void 0; // First infer to each type in union or intersection that isn't a type parameter - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var t = targetTypes_2[_i]; + for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { + var t = targetTypes_2[_b]; if (t.flags & 512 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -19244,24 +20758,31 @@ var ts; } } else if (source.flags & 49152 /* UnionOrIntersection */) { - // Source is a union or intersection type, infer from each consituent type + // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { - var sourceType = sourceTypes_3[_a]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } else { source = getApparentType(source); - if (source.flags & 80896 /* ObjectType */ && (target.flags & (4096 /* Reference */ | 8192 /* Tuple */) || - (target.flags & 65536 /* Anonymous */) && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { - // 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 (source.flags & 80896 /* ObjectType */ && (target.flags & 4096 /* Reference */ && target.typeArguments || + target.flags & 8192 /* Tuple */ || + target.flags & 65536 /* Anonymous */ && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { + // If source is an object type, and target is a type reference with type arguments, a tuple type, + // the type of a method, or a type literal, infer from members if (isInProcess(source, target)) { return; } if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { return; } + var key = source.id + "," + target.id; + if (ts.hasProperty(visited, key)) { + return; + } + visited[key] = true; if (depth === 0) { sourceStack = []; targetStack = []; @@ -19272,9 +20793,7 @@ var ts; 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 */); + inferFromIndexTypes(source, target); depth--; } } @@ -19301,28 +20820,56 @@ var ts; } function inferFromSignature(source, target) { forEachMatchingParameterType(source, target, inferFromTypes); - 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); - } + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } } - function inferFromIndexTypes(source, target, sourceKind, targetKind) { - var targetIndexType = getIndexTypeOfType(target, targetKind); - if (targetIndexType) { - var sourceIndexType = getIndexTypeOfType(source, sourceKind); + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 0 /* String */); if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetIndexType); + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || + getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 1 /* Number */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); } } } } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 16384 /* Union */ ? getUnionType(reducedTypes, /*noSubtypeReduction*/ true) : getIntersectionType(reducedTypes); + } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; @@ -19346,10 +20893,16 @@ var ts; inferredType = emptyObjectType; inferenceSucceeded = true; } + context.inferredTypes[index] = inferredType; // Only do the constraint check if inference succeeded (to prevent cascading errors) if (inferenceSucceeded) { var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + context.inferredTypes[index] = inferredType = instantiatedConstraint; + } + } } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { // If inference failed, it is necessary to record the index of the failed type parameter (the one we are on). @@ -19357,7 +20910,6 @@ var ts; // So if this failure is on preceding type parameter, this type parameter is the new failure index. context.failedTypeParameterIndex = index; } - context.inferredTypes[index] = inferredType; } return inferredType; } @@ -19367,9 +20919,6 @@ var ts; } return context.inferredTypes; } - function hasAncestor(node, kind) { - return ts.getAncestor(node, kind) !== undefined; - } // EXPRESSION TYPE CHECKING function getResolvedSymbol(node) { var links = getNodeLinks(node); @@ -19384,10 +20933,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 154 /* TypeQuery */: + case 156 /* TypeQuery */: return true; case 69 /* Identifier */: - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: node = node.parent; continue; default: @@ -19396,26 +20945,6 @@ var ts; } ts.Debug.fail("should not get here"); } - // For a union type, remove all constituent types that are of the given type kind (when isOfTypeKind is true) - // or not of the given type kind (when isOfTypeKind is false) - function removeTypesFromUnionType(type, typeKind, isOfTypeKind, allowEmptyUnionResult) { - if (type.flags & 16384 /* Union */) { - var types = type.types; - if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { - // Above we checked if we have anything to remove, now use the opposite test to do the removal - var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); - if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { - return narrowedType; - } - } - } - else if (allowEmptyUnionResult && !!(type.flags & typeKind) === isOfTypeKind) { - // Use getUnionType(emptyArray) instead of emptyObjectType in case the way empty union types - // are represented ever changes. - return getUnionType(emptyArray); - } - return type; - } function hasInitializer(node) { return !!(node.initializer || ts.isBindingPattern(node.parent) && hasInitializer(node.parent.parent)); } @@ -19434,10 +20963,7 @@ var ts; return links.assignmentChecks[symbol.id] = isAssignedIn(node); function isAssignedInBinaryExpression(node) { if (node.operatorToken.kind >= 56 /* FirstAssignment */ && node.operatorToken.kind <= 68 /* LastAssignment */) { - var n = node.left; - while (n.kind === 172 /* ParenthesizedExpression */) { - n = n.expression; - } + var n = skipParenthesizedNodes(node.left); if (n.kind === 69 /* Identifier */ && getResolvedSymbol(n) === symbol) { return true; } @@ -19452,55 +20978,55 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return isAssignedInBinaryExpression(node); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: return isAssignedInVariableDeclaration(node); - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: - case 172 /* ParenthesizedExpression */: - case 179 /* PrefixUnaryExpression */: - case 175 /* DeleteExpression */: - case 178 /* AwaitExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 180 /* PostfixUnaryExpression */: - case 184 /* YieldExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 192 /* Block */: - case 193 /* VariableStatement */: - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 204 /* ReturnStatement */: - case 205 /* WithStatement */: - case 206 /* SwitchStatement */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - case 235 /* JsxOpeningElement */: - case 240 /* JsxExpression */: + case 165 /* ObjectBindingPattern */: + case 166 /* ArrayBindingPattern */: + case 168 /* ArrayLiteralExpression */: + case 169 /* ObjectLiteralExpression */: + case 170 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 175 /* TypeAssertionExpression */: + case 193 /* AsExpression */: + case 176 /* ParenthesizedExpression */: + case 183 /* PrefixUnaryExpression */: + case 179 /* DeleteExpression */: + case 182 /* AwaitExpression */: + case 180 /* TypeOfExpression */: + case 181 /* VoidExpression */: + case 184 /* PostfixUnaryExpression */: + case 188 /* YieldExpression */: + case 186 /* ConditionalExpression */: + case 189 /* SpreadElementExpression */: + case 196 /* Block */: + case 197 /* VariableStatement */: + case 199 /* ExpressionStatement */: + case 200 /* IfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 208 /* ReturnStatement */: + case 209 /* WithStatement */: + case 210 /* SwitchStatement */: + case 245 /* CaseClause */: + case 246 /* DefaultClause */: + case 211 /* LabeledStatement */: + case 212 /* ThrowStatement */: + case 213 /* TryStatement */: + case 248 /* CatchClause */: + case 237 /* JsxElement */: + case 238 /* JsxSelfClosingElement */: + case 242 /* JsxAttribute */: + case 243 /* JsxSpreadAttribute */: + case 239 /* JsxOpeningElement */: + case 244 /* JsxExpression */: return ts.forEachChild(node, isAssignedIn); } return false; @@ -19512,59 +21038,73 @@ var ts; // Only narrow when symbol is variable of type any or an object, union, or type parameter type if (node && symbol.flags & 3 /* Variable */) { if (isTypeAny(type) || type.flags & (80896 /* ObjectType */ | 16384 /* Union */ | 512 /* TypeParameter */)) { + var declaration = ts.getDeclarationOfKind(symbol, 215 /* VariableDeclaration */); + var top_1 = declaration && getDeclarationContainer(declaration); + var originalType = type; + var nodeStack = []; loop: while (node.parent) { var child = node; node = node.parent; - var narrowedType = type; switch (node.kind) { - case 196 /* 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); - } + case 200 /* IfStatement */: + case 186 /* ConditionalExpression */: + case 185 /* BinaryExpression */: + nodeStack.push({ node: node, child: child }); break; - case 182 /* 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 181 /* BinaryExpression */: - // In the right operand of an && or ||, narrow based on left operand - if (child === node.right) { - if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { - narrowedType = narrowType(type, node.left, /*assumeTrue*/ true); - } - else if (node.operatorToken.kind === 52 /* BarBarToken */) { - narrowedType = narrowType(type, node.left, /*assumeTrue*/ false); - } - } - break; - case 248 /* SourceFile */: - case 218 /* ModuleDeclaration */: - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 144 /* Constructor */: - // Stop at the first containing function or module declaration + case 252 /* SourceFile */: + case 222 /* ModuleDeclaration */: + // Stop at the first containing file 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; + if (node === top_1) { + break; } } + var nodes = void 0; + while (nodes = nodeStack.pop()) { + var node_1 = nodes.node, child = nodes.child; + switch (node_1.kind) { + case 200 /* IfStatement */: + // In a branch of an if statement, narrow based on controlling expression + if (child !== node_1.expression) { + type = narrowType(type, node_1.expression, /*assumeTrue*/ child === node_1.thenStatement); + } + break; + case 186 /* ConditionalExpression */: + // In a branch of a conditional expression, narrow based on controlling condition + if (child !== node_1.condition) { + type = narrowType(type, node_1.condition, /*assumeTrue*/ child === node_1.whenTrue); + } + break; + case 185 /* BinaryExpression */: + // In the right operand of an && or ||, narrow based on left operand + if (child === node_1.right) { + if (node_1.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + type = narrowType(type, node_1.left, /*assumeTrue*/ true); + } + else if (node_1.operatorToken.kind === 52 /* BarBarToken */) { + type = narrowType(type, node_1.left, /*assumeTrue*/ false); + } + } + break; + default: + ts.Debug.fail("Unreachable!"); + } + // Use original type if construct contains assignments to variable + if (type !== originalType && isVariableAssignedWithin(symbol, node_1)) { + type = originalType; + } + } + // Preserve old top-level behavior - if the branch is really an empty set, revert to prior type + if (type === emptyUnionType) { + type = originalType; + } } } 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 !== 176 /* TypeOfExpression */ || expr.right.kind !== 9 /* StringLiteral */) { + if (expr.left.kind !== 180 /* TypeOfExpression */ || expr.right.kind !== 9 /* StringLiteral */) { return type; } var left = expr.left; @@ -19572,31 +21112,34 @@ var ts; if (left.expression.kind !== 69 /* Identifier */ || getResolvedSymbol(left.expression) !== symbol) { return type; } - var typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue) { - // Assumed result is true. If check was not for a primitive type, remove all primitive types - if (!typeInfo) { - return removeTypesFromUnionType(type, /*typeKind*/ 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */ | 16777216 /* ESSymbol */, - /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); - } - // Check was for a primitive type, return that primitive type if it is a subtype - if (isTypeSubtypeOf(typeInfo.type, type)) { - return typeInfo.type; - } - // Otherwise, remove all types that aren't of the primitive type kind. This can happen when the type is - // union of enum types and other types. - return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ false, /*allowEmptyUnionResult*/ false); + var typeInfo = primitiveTypeInfo[right.text]; + // Don't narrow `undefined` + if (typeInfo && typeInfo.type === undefinedType) { + return type; + } + var flags; + if (typeInfo) { + flags = typeInfo.flags; } else { - // Assumed result is false. If check was for a primitive type, remove that primitive type - if (typeInfo) { - return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); + assumeTrue = !assumeTrue; + flags = 132 /* NumberLike */ | 258 /* StringLike */ | 16777216 /* ESSymbol */ | 8 /* Boolean */; + } + // At this point we can bail if it's not a union + if (!(type.flags & 16384 /* Union */)) { + // If we're on the true branch and the type is a subtype, we should return the primitive type + if (assumeTrue && typeInfo && isTypeSubtypeOf(typeInfo.type, type)) { + return typeInfo.type; } - // Otherwise we don't have enough information to do anything. - return type; + // If the active non-union type would be removed from a union by this type guard, return an empty union + return filterUnion(type) ? type : emptyUnionType; + } + return getUnionType(ts.filter(type.types, filterUnion), /*noSubtypeReduction*/ true); + function filterUnion(type) { + return assumeTrue === !!(type.flags & flags); } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -19609,7 +21152,7 @@ var ts; // and the second operand was false. We narrow with those assumptions and union the two resulting types. return getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ false), - narrowType(narrowType(type, expr.left, /*assumeTrue*/ true), expr.right, /*assumeTrue*/ false) + narrowType(type, expr.right, /*assumeTrue*/ false) ]); } } @@ -19619,7 +21162,7 @@ var ts; // and the second operand was true. We narrow with those assumptions and union the two resulting types. return getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ true), - narrowType(narrowType(type, expr.left, /*assumeTrue*/ false), expr.right, /*assumeTrue*/ true) + narrowType(type, expr.right, /*assumeTrue*/ true) ]); } else { @@ -19629,7 +21172,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 (isTypeAny(type) || !assumeTrue || expr.left.kind !== 69 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) { + if (isTypeAny(type) || expr.left.kind !== 69 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) { return type; } // Check that right operand is a function type with a prototype property @@ -19648,7 +21191,7 @@ var ts; } if (!targetType) { // Target type is type of construct signature - var constructSignatures; + var constructSignatures = void 0; if (rightType.flags & 2048 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } @@ -19660,11 +21203,17 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType); + return getNarrowedType(type, targetType, assumeTrue); } return type; } - function getNarrowedType(originalType, narrowedTypeCandidate) { + function getNarrowedType(originalType, narrowedTypeCandidate, assumeTrue) { + if (!assumeTrue) { + if (originalType.flags & 16384 /* Union */) { + return getUnionType(ts.filter(originalType.types, function (t) { return !isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } // If the current type is a union type, remove all constituents that aren't assignable to target. If that produces // 0 candidates, fall back to the assignability check if (originalType.flags & 16384 /* Union */) { @@ -19679,33 +21228,54 @@ var ts; } return originalType; } - function narrowTypeByTypePredicate(type, expr, assumeTrue) { + function narrowTypeByTypePredicate(type, callExpression, 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; + var signature = getResolvedSignature(callExpression); + var predicate = signature.typePredicate; + if (!predicate) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + if (callExpression.arguments[predicate.parameterIndex] && + getSymbolAtTypePredicatePosition(callExpression.arguments[predicate.parameterIndex]) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); } - return getNarrowedType(type, signature.typePredicate.type); + } + else { + var invokedExpression = skipParenthesizedNodes(callExpression.expression); + return narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue); } return type; } + function narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue) { + if (invokedExpression.kind === 171 /* ElementAccessExpression */ || invokedExpression.kind === 170 /* PropertyAccessExpression */) { + var accessExpression = invokedExpression; + var possibleIdentifier = skipParenthesizedNodes(accessExpression.expression); + if (possibleIdentifier.kind === 69 /* Identifier */ && getSymbolAtTypePredicatePosition(possibleIdentifier) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); + } + } + return type; + } + function getSymbolAtTypePredicatePosition(expr) { + expr = skipParenthesizedNodes(expr); + switch (expr.kind) { + case 69 /* Identifier */: + case 170 /* PropertyAccessExpression */: + return getSymbolOfEntityNameOrPropertyAccessExpression(expr); + } + } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { switch (expr.kind) { - case 168 /* CallExpression */: + case 172 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: var operator = expr.operatorToken.kind; if (operator === 32 /* EqualsEqualsEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -19720,7 +21290,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: if (expr.operator === 49 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -19729,6 +21299,12 @@ var ts; return type; } } + function skipParenthesizedNodes(expression) { + while (expression.kind === 176 /* ParenthesizedExpression */) { + expression = expression.expression; + } + return expression; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. @@ -19739,23 +21315,40 @@ var ts; // can explicitly bound arguments objects if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 174 /* ArrowFunction */) { + if (container.kind === 178 /* ArrowFunction */) { if (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 (node.parserContextFlags & 8 /* Await */) { - getNodeLinks(container).flags |= 4096 /* CaptureArguments */; - getNodeLinks(node).flags |= 2048 /* LexicalArguments */; + if (node.flags & 33554432 /* AwaitContext */) { + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; } } if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (languageVersion === 2 /* ES6 */ + && localOrExportSymbol.flags & 32 /* Class */ + && localOrExportSymbol.valueDeclaration.kind === 218 /* ClassDeclaration */ + && ts.nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { + getNodeLinks(container).flags |= 524288 /* ClassWithBodyScopedClassBinding */; + getNodeLinks(node).flags |= 1048576 /* BodyScopedClassBinding */; + break; + } + container = ts.getContainingClass(container); + } + } checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); - checkBlockScopedBindingCapturedInLoop(node, symbol); - return getNarrowedTypeOfSymbol(getExportSymbolOfValueSymbolIfExported(symbol), node); + checkNestedBlockScopedBinding(node, symbol); + return getNarrowedTypeOfSymbol(localOrExportSymbol, node); } function isInsideFunction(node, threshold) { var current = node; @@ -19767,52 +21360,79 @@ var ts; } return false; } - function checkBlockScopedBindingCapturedInLoop(node, symbol) { + function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES6 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 244 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 248 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check // if there is anything function like between declaration and use-site (is binding/class is captured in function). // 2. walk from the declaration up to the boundary of lexical environment and check // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) - var container; - if (symbol.flags & 32 /* Class */) { - // get parent of class declaration - container = getClassLikeDeclarationOfSymbol(symbol).parent; - } - else { - // nesting structure: - // (variable declaration or binding element) -> variable declaration list -> container - container = symbol.valueDeclaration; - while (container.kind !== 212 /* VariableDeclarationList */) { - container = container.parent; - } - // get the parent of variable declaration list - container = container.parent; - if (container.kind === 193 /* VariableStatement */) { - // if parent is variable statement - get its parent - container = container.parent; - } - } - var inFunction = isInsideFunction(node.parent, container); + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); var current = container; + var containedInIterationStatement = false; while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - if (inFunction) { - getNodeLinks(current).flags |= 65536 /* LoopWithBlockScopedBindingCapturedInFunction */; - } - // mark value declaration so during emit they can have a special handling - getNodeLinks(symbol.valueDeclaration).flags |= 16384 /* BlockScopedBindingInLoop */; + containedInIterationStatement = true; break; } current = current.parent; } + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 203 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 216 /* VariableDeclarationList */).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + } + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + } + } + function isAssignedInBodyOfForStatement(node, container) { + var current = node; + // skip parenthesized nodes + while (current.parent.kind === 176 /* ParenthesizedExpression */) { + current = current.parent; + } + // check if node is used as LHS in some assignment expression + var isAssigned = false; + if (current.parent.kind === 185 /* BinaryExpression */) { + isAssigned = current.parent.left === current && ts.isAssignmentOperator(current.parent.operatorToken.kind); + } + if ((current.parent.kind === 183 /* PrefixUnaryExpression */ || current.parent.kind === 184 /* PostfixUnaryExpression */)) { + var expr = current.parent; + isAssigned = expr.operator === 41 /* PlusPlusToken */ || expr.operator === 42 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + while (current !== container) { + if (current === container.statement) { + return true; + } + else { + current = current.parent; + } + } + return false; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 141 /* PropertyDeclaration */ || container.kind === 144 /* Constructor */) { + if (container.kind === 143 /* PropertyDeclaration */ || container.kind === 146 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -19820,38 +21440,93 @@ var ts; getNodeLinks(container).flags |= 4 /* CaptureThis */; } } + function findFirstSuperCall(n) { + if (ts.isSuperCallExpression(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullType; + } function checkThisExpression(node) { // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; + if (container.kind === 146 /* Constructor */) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + } + } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 174 /* ArrowFunction */) { + if (container.kind === 178 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code needToCaptureLexicalThis = (languageVersion < 2 /* ES6 */); } switch (container.kind) { - case 218 /* ModuleDeclaration */: + case 222 /* 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 217 /* EnumDeclaration */: + case 221 /* 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 144 /* Constructor */: + case 146 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - if (container.flags & 64 /* Static */) { + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + if (container.flags & 32 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 136 /* ComputedPropertyName */: + case 138 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -19860,69 +21535,183 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - return container.flags & 64 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return container.flags & 32 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + } + if (ts.isInJavaScriptFile(node)) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + // If this is a function in a JS file, it might be a class method. Check if it's the RHS + // of a x.prototype.y = function [name]() { .... } + if (container.kind === 177 /* FunctionExpression */) { + if (ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') + var className = container.parent // x.prototype.y = f + .left // x.prototype.y + .expression // x.prototype + .expression; // x + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + return getInferredClassType(classSymbol); + } + } + } } return anyType; } + function getTypeForThisExpressionFromJSDoc(node) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === 265 /* JSDocFunctionType */) { + var jsDocFunctionType = typeTag.typeExpression.type; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 268 /* JSDocThisType */) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 138 /* Parameter */) { + if (n.kind === 140 /* Parameter */) { return true; } } return false; } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 168 /* CallExpression */ && node.parent.expression === node; - var classDeclaration = ts.getContainingClass(node); - var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - var container = ts.getSuperContainer(node, /*includeFunctions*/ true); + var isCallExpression = node.parent.kind === 172 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; if (!isCallExpression) { // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting - while (container && container.kind === 174 /* ArrowFunction */) { - container = ts.getSuperContainer(container, /*includeFunctions*/ true); + while (container && container.kind === 178 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; } } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; - // always set NodeCheckFlags for 'super' expression node - if (canUseSuperExpression) { - if ((container.flags & 64 /* Static */) || isCallExpression) { - nodeCheckFlag = 512 /* SuperStatic */; - } - else { - nodeCheckFlag = 256 /* SuperInstance */; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (needToCaptureLexicalThis) { - // call expressions are allowed only in constructors so they should always capture correct 'this' - // super property access expressions can also appear in arrow functions - - // in this case they should also use correct lexical this - captureLexicalThis(node.parent, container); - } - } - if (!baseClassType) { - if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } if (!canUseSuperExpression) { - if (container && container.kind === 136 /* ComputedPropertyName */) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = node; + while (current && current !== container && current.kind !== 138 /* ComputedPropertyName */) { + current = current.parent; + } + if (current && current.kind === 138 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 169 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } else { error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } return unknownType; } - if (container.kind === 144 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if ((container.flags & 32 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = name => super[name]; + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super("asyncMethod").call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + // return __awaiter(this, arguments, Promise, function *() { + // [_super("a").value, _super("b").value] = yield ar; + // }); + // } + // ... + // + // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. + // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment + // while a property access can. + if (container.kind === 145 /* MethodDeclaration */ && container.flags & 256 /* Async */) { + if (ts.isSuperPropertyOrElementAccess(node.parent) && isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; + } + else { + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; + } + } + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 169 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES6 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } + if (container.kind === 146 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return unknownType; @@ -19937,29 +21726,29 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 144 /* Constructor */; + return container.kind === 146 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) // 'super' property access is allowed // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor - // topmost container must be something that is directly nested in the class declaration - if (container && ts.isClassLike(container.parent)) { - if (container.flags & 64 /* Static */) { - return container.kind === 143 /* MethodDeclaration */ || - container.kind === 142 /* MethodSignature */ || - container.kind === 145 /* GetAccessor */ || - container.kind === 146 /* SetAccessor */; + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 169 /* ObjectLiteralExpression */) { + if (container.flags & 32 /* Static */) { + return container.kind === 145 /* MethodDeclaration */ || + container.kind === 144 /* MethodSignature */ || + container.kind === 147 /* GetAccessor */ || + container.kind === 148 /* SetAccessor */; } else { - return container.kind === 143 /* MethodDeclaration */ || - container.kind === 142 /* MethodSignature */ || - container.kind === 145 /* GetAccessor */ || - container.kind === 146 /* SetAccessor */ || - container.kind === 141 /* PropertyDeclaration */ || - container.kind === 140 /* PropertySignature */ || - container.kind === 144 /* Constructor */; + return container.kind === 145 /* MethodDeclaration */ || + container.kind === 144 /* MethodSignature */ || + container.kind === 147 /* GetAccessor */ || + container.kind === 148 /* SetAccessor */ || + container.kind === 143 /* PropertyDeclaration */ || + container.kind === 142 /* PropertySignature */ || + container.kind === 146 /* Constructor */; } } } @@ -20001,7 +21790,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 138 /* Parameter */) { + if (declaration.kind === 140 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -20034,7 +21823,7 @@ var ts; } function isInParameterInitializerBeforeContainingFunction(node) { while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 138 /* Parameter */ && node.parent.initializer === node) { + if (node.parent.kind === 140 /* Parameter */ && node.parent.initializer === node) { return true; } node = node.parent; @@ -20045,8 +21834,8 @@ var ts; // 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 === 144 /* Constructor */ || - functionDecl.kind === 145 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 146 /* SetAccessor */))) { + functionDecl.kind === 146 /* Constructor */ || + functionDecl.kind === 147 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 148 /* SetAccessor */))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature @@ -20068,7 +21857,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 170 /* TaggedTemplateExpression */) { + if (template.parent.kind === 174 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -20091,6 +21880,11 @@ var ts; } return type; } + else if (operator === 51 /* AmpersandAmpersandToken */ || operator === 24 /* CommaToken */) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } return undefined; } // Apply a mapping function to a contextual type and return the resulting type. If the contextual type @@ -20103,8 +21897,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var current = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -20129,14 +21923,13 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } + function contextualTypeIsStringLiteralType(type) { + return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); + } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } - // Return true if the given contextual type provides an index signature of the given kind - function contextualTypeHasIndexSignature(type, kind) { - return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, function (t) { return getIndexTypeOfStructuredType(t, kind); }) : getIndexTypeOfStructuredType(type, kind)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -20150,7 +21943,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element) { var objectLiteral = element.parent; - var type = getContextualType(objectLiteral); + var type = getApparentTypeOfContextualType(objectLiteral); if (type) { if (!ts.hasDynamicName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name @@ -20173,7 +21966,7 @@ var ts; // type of T. function getContextualTypeForElementExpression(node) { var arrayLiteral = node.parent; - var type = getContextualType(arrayLiteral); + var type = getApparentTypeOfContextualType(arrayLiteral); if (type) { var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) @@ -20187,30 +21980,45 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForJsxExpression(expr) { - // Contextual type only applies to JSX expressions that are in attribute assignments (not in 'Children' positions) - if (expr.parent.kind === 238 /* JsxAttribute */) { - var attrib = expr.parent; - var attrsType = getJsxElementAttributesType(attrib.parent); + function getContextualTypeForJsxAttribute(attribute) { + var kind = attribute.kind; + var jsxElement = attribute.parent; + var attrsType = getJsxElementAttributesType(jsxElement); + if (attribute.kind === 242 /* JsxAttribute */) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } - else { - return getTypeOfPropertyOfType(attrsType, attrib.name.text); - } + return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - if (expr.kind === 239 /* JsxSpreadAttribute */) { - return getJsxElementAttributesType(expr.parent); + else if (attribute.kind === 243 /* JsxSpreadAttribute */) { + return attrsType; } - return undefined; + ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. - function getContextualType(node) { - var type = getContextualTypeWorker(node); + function getApparentTypeOfContextualType(node) { + var type = getContextualType(node); return type && getApparentType(type); } - function getContextualTypeWorker(node) { + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node) { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; @@ -20220,39 +22028,41 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 211 /* VariableDeclaration */: - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 163 /* BindingElement */: + case 215 /* VariableDeclaration */: + case 140 /* Parameter */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 167 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 174 /* ArrowFunction */: - case 204 /* ReturnStatement */: + case 178 /* ArrowFunction */: + case 208 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 184 /* YieldExpression */: + case 188 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 175 /* TypeAssertionExpression */: + case 193 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 245 /* PropertyAssignment */: + case 249 /* PropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 190 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 183 /* TemplateExpression */); + case 194 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 187 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return getContextualType(parent); - case 240 /* JsxExpression */: - case 239 /* JsxSpreadAttribute */: - return getContextualTypeForJsxExpression(parent); + case 244 /* JsxExpression */: + return getContextualType(parent); + case 242 /* JsxAttribute */: + case 243 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); } return undefined; } @@ -20268,7 +22078,7 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 173 /* FunctionExpression */ || node.kind === 174 /* ArrowFunction */; + return node.kind === 177 /* FunctionExpression */ || node.kind === 178 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -20282,10 +22092,10 @@ 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 !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var type = ts.isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) - : getContextualType(node); + : getApparentTypeOfContextualType(node); if (!type) { return undefined; } @@ -20294,15 +22104,15 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var current = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature signatureList = [signature]; } - else if (!compareSignatures(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypes)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { // Signatures aren't identical, do not use return undefined; } @@ -20345,13 +22155,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 === 181 /* BinaryExpression */ && parent.operatorToken.kind === 56 /* EqualsToken */ && parent.left === node) { + if (parent.kind === 185 /* BinaryExpression */ && parent.operatorToken.kind === 56 /* EqualsToken */ && parent.left === node) { return true; } - if (parent.kind === 245 /* PropertyAssignment */) { + if (parent.kind === 249 /* PropertyAssignment */) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 164 /* ArrayLiteralExpression */) { + if (parent.kind === 168 /* ArrayLiteralExpression */) { return isAssignmentTarget(parent); } return false; @@ -20367,8 +22177,8 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } function hasDefaultValue(node) { - return (node.kind === 163 /* BindingElement */ && !!node.initializer) || - (node.kind === 181 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); + return (node.kind === 167 /* BindingElement */ && !!node.initializer) || + (node.kind === 185 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; @@ -20377,7 +22187,7 @@ var ts; var inDestructuringPattern = isAssignmentTarget(node); for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 185 /* SpreadElementExpression */) { + if (inDestructuringPattern && e.kind === 189 /* SpreadElementExpression */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -20401,7 +22211,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 185 /* SpreadElementExpression */; + hasSpreadElement = hasSpreadElement || e.kind === 189 /* SpreadElementExpression */; } if (!hasSpreadElement) { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such @@ -20411,12 +22221,12 @@ var ts; type.pattern = node; return type; } - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { var pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 162 /* ArrayBindingPattern */ || pattern.kind === 164 /* ArrayLiteralExpression */)) { + if (pattern && (pattern.kind === 166 /* ArrayBindingPattern */ || pattern.kind === 168 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -20424,7 +22234,7 @@ var ts; elementTypes.push(contextualType.elementTypes[i]); } else { - if (patternElement.kind !== 187 /* OmittedExpression */) { + if (patternElement.kind !== 191 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -20439,7 +22249,7 @@ var ts; return createArrayType(elementTypes.length ? getUnionType(elementTypes) : undefinedType); } function isNumericName(name) { - return name.kind === 136 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 138 /* 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, @@ -20447,7 +22257,7 @@ var ts; return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132 /* NumberLike */); } function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); + return isTypeAny(type) || isTypeOfKind(type, kind); } function isNumericLiteralName(name) { // The intent of numeric names is that @@ -20488,31 +22298,44 @@ var ts; } return links.resolvedType; } + function getObjectLiteralIndexInfo(node, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 /* String */ || isNumericName(node.properties[i].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); + } function checkObjectLiteral(node, contextualMapper) { var inDestructuringPattern = isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = {}; var propertiesArray = []; - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 161 /* ObjectBindingPattern */ || contextualType.pattern.kind === 165 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 165 /* ObjectBindingPattern */ || contextualType.pattern.kind === 169 /* ObjectLiteralExpression */); var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var memberDecl = _a[_i]; var member = memberDecl.symbol; - if (memberDecl.kind === 245 /* PropertyAssignment */ || - memberDecl.kind === 246 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 249 /* PropertyAssignment */ || + memberDecl.kind === 250 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 245 /* PropertyAssignment */) { + if (memberDecl.kind === 249 /* PropertyAssignment */) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 143 /* MethodDeclaration */) { + else if (memberDecl.kind === 145 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 246 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 250 /* ShorthandPropertyAssignment */); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -20520,13 +22343,16 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 245 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 246 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 249 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 250 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912 /* Optional */; } + if (ts.hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } } - else if (contextualTypeHasPattern) { + else if (contextualTypeHasPattern && !(contextualType.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); @@ -20552,10 +22378,18 @@ 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 === 145 /* GetAccessor */ || memberDecl.kind === 146 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 147 /* GetAccessor */ || memberDecl.kind === 148 /* SetAccessor */); checkAccessorDeclaration(memberDecl); } - if (!ts.hasDynamicName(memberDecl)) { + if (ts.hasDynamicName(memberDecl)) { + if (isNumericName(memberDecl.name)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + } + else { propertiesTable[member.name] = member; } propertiesArray.push(member); @@ -20574,74 +22408,36 @@ var ts; } } } - var stringIndexType = getIndexType(0 /* String */); - var numberIndexType = getIndexType(1 /* Number */); - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshObjectLiteral */; - result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); + result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */) | (patternWithComputedProperties ? 67108864 /* ObjectLiteralPatternWithComputedProperties */ : 0); if (inDestructuringPattern) { result.pattern = node; } return result; - function getIndexType(kind) { - if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { - var propTypes = []; - for (var i = 0; i < propertiesArray.length; i++) { - var propertyDecl = node.properties[i]; - if (kind === 0 /* String */ || isNumericName(propertyDecl.name)) { - // Do not call getSymbolOfNode(propertyDecl), as that will get the - // original symbol for the node. We actually want to get the symbol - // created by checkObjectLiteral, since that will be appropriately - // contextually typed and resolved. - var type = getTypeOfSymbol(propertiesArray[i]); - if (!ts.contains(propTypes, type)) { - propTypes.push(type); - } - } - } - var result_1 = propTypes.length ? getUnionType(propTypes) : undefinedType; - typeFlags |= result_1.flags; - return result_1; - } - return undefined; - } } function checkJsxSelfClosingElement(node) { checkJsxOpeningLikeElement(node); return jsxElementType || anyType; } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 69 /* Identifier */) { - return lhs.text === rhs.text; - } - return lhs.right.text === rhs.right.text && - tagNamesAreEquivalent(lhs.left, rhs.left); - } function checkJsxElement(node) { // Check attributes checkJsxOpeningLikeElement(node.openingElement); - // Check that the closing tag matches - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - error(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNode(node.openingElement.tagName)); - } - else { - // Perform resolution on the closing tag so that rename/go to definition/etc work - getJsxElementTagSymbol(node.closingElement); - } + // Perform resolution on the closing tag so that rename/go to definition/etc work + getJsxTagSymbol(node.closingElement); // Check children for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; switch (child.kind) { - case 240 /* JsxExpression */: + case 244 /* JsxExpression */: checkJsxExpression(child); break; - case 233 /* JsxElement */: + case 237 /* JsxElement */: checkJsxElement(child); break; - case 234 /* JsxSelfClosingElement */: + case 238 /* JsxSelfClosingElement */: checkJsxSelfClosingElement(child); break; } @@ -20659,7 +22455,7 @@ var ts; * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name */ function isJsxIntrinsicIdentifier(tagName) { - if (tagName.kind === 135 /* QualifiedName */) { + if (tagName.kind === 137 /* QualifiedName */) { return false; } else { @@ -20723,77 +22519,55 @@ var ts; } return type; } - /// Returns the type JSX.IntrinsicElements. May return `unknownType` if that type is not present. - function getJsxIntrinsicElementsType() { - if (!jsxIntrinsicElementsType) { - jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType; + function getJsxType(name) { + if (jsxTypes[name] === undefined) { + return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType; } - return jsxIntrinsicElementsType; + return jsxTypes[name]; } - /// Given a JSX opening element or self-closing element, return the symbol of the property that the tag name points to if - /// this is an intrinsic tag. This might be a named - /// property of the IntrinsicElements interface, or its string indexer. - /// If this is a class-based tag (otherwise returns undefined), returns the symbol of the class - /// type or factory function. - /// Otherwise, returns unknownSymbol. - function getJsxElementTagSymbol(node) { - var flags = 8 /* UnknownElement */; + function getJsxTagSymbol(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicTagSymbol(node); + } + else { + return checkExpression(node.tagName).symbol; + } + } + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - links.resolvedSymbol = lookupIntrinsicTag(node); - } - else { - links.resolvedSymbol = lookupClassTag(node); - } - } - return links.resolvedSymbol; - function lookupIntrinsicTag(node) { - var intrinsicElementsType = getJsxIntrinsicElementsType(); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { // Property case var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); if (intrinsicProp) { links.jsxFlags |= 1 /* IntrinsicNamedElement */; - return intrinsicProp; + return links.resolvedSymbol = intrinsicProp; } // Intrinsic string indexer case var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); if (indexSignatureType) { links.jsxFlags |= 2 /* IntrinsicIndexedElement */; - return intrinsicElementsType.symbol; + return links.resolvedSymbol = intrinsicElementsType.symbol; } // Wasn't found error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.tagName.text, "JSX." + JsxNames.IntrinsicElements); - return unknownSymbol; + return links.resolvedSymbol = unknownSymbol; } else { if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); } + return links.resolvedSymbol = unknownSymbol; } } - function lookupClassTag(node) { - var valueSymbol = resolveJsxTagName(node); - // Look up the value in the current scope - if (valueSymbol && valueSymbol !== unknownSymbol) { - links.jsxFlags |= 4 /* ClassElement */; - if (valueSymbol.flags & 8388608 /* Alias */) { - markAliasSymbolAsReferenced(valueSymbol); - } - } - return valueSymbol || unknownSymbol; - } - function resolveJsxTagName(node) { - if (node.tagName.kind === 69 /* Identifier */) { - var tag = node.tagName; - var sym = getResolvedSymbol(tag); - return sym.exportSymbol || sym; - } - else { - return checkQualifiedName(node.tagName).symbol; - } - } + return links.resolvedSymbol; } /** * Given a JSX element that is a class element, finds the Element Instance Type. If the @@ -20801,15 +22575,7 @@ var ts; * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node) { - // There is no such thing as an instance type for a non-class element. This - // line shouldn't be hit. - ts.Debug.assert(!!(getNodeLinks(node).jsxFlags & 4 /* ClassElement */), "Should not call getJsxElementInstanceType on non-class Element"); - var classSymbol = getJsxElementTagSymbol(node); - if (classSymbol === unknownSymbol) { - // Couldn't find the class instance type. Error has already been issued - return anyType; - } - var valueType = getTypeOfSymbol(classSymbol); + var valueType = checkExpression(node.tagName); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -20825,19 +22591,13 @@ var ts; return unknownType; } } - var returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); - // Issue an error if this return type isn't assignable to JSX.ElementClass - var elemClassType = getJsxGlobalElementClassType(); - if (elemClassType) { - checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - return returnType; + return getUnionType(signatures.map(getReturnTypeOfSignature)); } /// e.g. "props" for React.d.ts, - /// or 'undefined' if ElementAttributesPropery doesn't exist (which means all + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all /// non-intrinsic elements' attributes type is 'any'), /// or '' if it has 0 properties (which means every - /// non-instrinsic elements' attributes type is the element instance type) + /// non-intrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { // JSX var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); @@ -20845,7 +22605,7 @@ var ts; var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056 /* Type */); // JSX.ElementAttributesProperty [type] var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); - // The properites of JSX.ElementAttributesProperty + // The properties of JSX.ElementAttributesProperty var attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { // Element Attributes has zero properties, so the element attributes type will be the class instance type @@ -20872,9 +22632,40 @@ var ts; function getJsxElementAttributesType(node) { var links = getNodeLinks(node); if (!links.resolvedJsxType) { - var sym = getJsxElementTagSymbol(node); - if (links.jsxFlags & 4 /* ClassElement */) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; + } + } + else { + // Get the element instance type (the result of newing or invoking this tag) var elemInstanceType = getJsxElementInstanceType(node); + var elemClassType = getJsxGlobalElementClassType(); + if (!elemClassType || !isTypeAssignableTo(elemInstanceType, elemClassType)) { + // Is this is a stateless function component? See if its single signature's return type is + // assignable to the JSX Element Type + var elemType = checkExpression(node.tagName); + var callSignatures = elemType && getSignaturesOfType(elemType, 0 /* Call */); + var callSignature = callSignatures && callSignatures.length > 0 && callSignatures[0]; + var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); + var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) { + // Intersect in JSX.IntrinsicAttributes if it exists + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return links.resolvedJsxType = paramType; + } + } + // Issue an error if this return type isn't assignable to JSX.ElementClass + if (elemClassType) { + checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } @@ -20894,27 +22685,38 @@ var ts; return links.resolvedJsxType = emptyObjectType; } else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + // Props is of type 'any' or unknown return links.resolvedJsxType = attributesType; } - else if (!(attributesType.flags & 80896 /* ObjectType */)) { - error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType)); + else if (attributesType.flags & 16384 /* Union */) { + // Props cannot be a union type + error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return links.resolvedJsxType = anyType; } else { - return links.resolvedJsxType = attributesType; + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return links.resolvedJsxType = apparentAttributesType; } } } - else if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { - return links.resolvedJsxType = getTypeOfSymbol(sym); - } - else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { - return links.resolvedJsxType = getIndexTypeOfSymbol(sym, 0 /* String */); - } - else { - // Resolution failed, so we don't know - return links.resolvedJsxType = anyType; - } + return links.resolvedJsxType = unknownType; } return links.resolvedJsxType; } @@ -20936,7 +22738,7 @@ var ts; } /// Returns all the properties of the Jsx.IntrinsicElements interface function getJsxIntrinsicTagNames() { - var intrinsics = getJsxIntrinsicElementsType(); + var intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } function checkJsxPreconditions(errorNode) { @@ -20953,14 +22755,13 @@ var ts; function checkJsxOpeningLikeElement(node) { checkGrammarJsxElement(node); checkJsxPreconditions(node); - // If we're compiling under --jsx react, the symbol 'React' should - // be marked as 'used' so we don't incorrectly elide its import. And if there - // is no 'React' symbol in scope, we should issue an error. - if (compilerOptions.jsx === 2 /* React */) { - var reactSym = resolveName(node.tagName, "React", 107455 /* Value */, ts.Diagnostics.Cannot_find_name_0, "React"); - if (reactSym) { - getSymbolLinks(reactSym).referenced = true; - } + // The reactNamespace symbol should be marked as 'used' so we don't incorrectly elide its import. And if there + // is no reactNamespace symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = {}; @@ -20969,11 +22770,11 @@ var ts; // thus should have their types ignored var sawSpreadedAny = false; for (var i = node.attributes.length - 1; i >= 0; i--) { - if (node.attributes[i].kind === 238 /* JsxAttribute */) { + if (node.attributes[i].kind === 242 /* JsxAttribute */) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 239 /* JsxSpreadAttribute */); + ts.Debug.assert(node.attributes[i].kind === 243 /* JsxSpreadAttribute */); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -21003,10 +22804,10 @@ 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 : 141 /* PropertyDeclaration */; + return s.valueDeclaration ? s.valueDeclaration.kind : 143 /* PropertyDeclaration */; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 8 /* Public */ | 64 /* Static */ : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0; } /** * Check whether the requested property access is valid. @@ -21018,9 +22819,9 @@ var ts; */ function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationFlagsFromSymbol(prop); - var declaringClass = getDeclaredTypeOfSymbol(prop.parent); + var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); if (left.kind === 95 /* SuperKeyword */) { - var errorNode = node.kind === 166 /* PropertyAccessExpression */ ? + var errorNode = node.kind === 170 /* PropertyAccessExpression */ ? node.name : node.right; // TS 1.0 spec (April 2014): 4.8.2 @@ -21030,7 +22831,7 @@ var ts; // - 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 (getDeclarationKindFromSymbol(prop) !== 143 /* MethodDeclaration */) { + if (languageVersion < 2 /* ES6 */ && getDeclarationKindFromSymbol(prop) !== 145 /* MethodDeclaration */) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); @@ -21046,7 +22847,7 @@ var ts; } } // Public properties are otherwise accessible. - if (!(flags & (16 /* Private */ | 32 /* Protected */))) { + if (!(flags & (8 /* Private */ | 16 /* Protected */))) { return true; } // Property is known to be private or protected at this point @@ -21054,7 +22855,7 @@ var ts; var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; // Private property is accessible if declaring and enclosing class are the same - if (flags & 16 /* Private */) { + if (flags & 8 /* Private */) { if (declaringClass !== enclosingClass) { error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; @@ -21072,7 +22873,7 @@ var ts; return false; } // No further restrictions for static properties - if (flags & 64 /* Static */) { + if (flags & 32 /* Static */) { return true; } // An instance property must be accessed through an instance of the enclosing class @@ -21117,7 +22918,7 @@ var ts; return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 166 /* PropertyAccessExpression */ + var left = node.kind === 170 /* PropertyAccessExpression */ ? node.expression : node.left; var type = checkExpression(left); @@ -21129,11 +22930,58 @@ var ts; } return true; } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 216 /* VariableDeclarationList */) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 69 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return undefined; + } + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); + } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr) { + var e = skipParenthesizedNodes(expr); + if (e.kind === 69 /* Identifier */) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 204 /* ForInStatement */ && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(checkExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } function checkIndexedAccess(node) { // Grammar checking if (!node.argumentExpression) { - var sourceFile = getSourceFile(node); - if (node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 173 /* 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); @@ -21182,20 +23030,24 @@ var ts; // Check for compatible indexer types. if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { // Try to use a number indexer. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */)) { - var numberIndexType = getIndexTypeOfType(objectType, 1 /* Number */); - if (numberIndexType) { - return numberIndexType; + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + var numberIndexInfo = getIndexInfoOfType(objectType, 1 /* Number */); + if (numberIndexInfo) { + getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; + return numberIndexInfo.type; } } // Try to use string indexing. - var stringIndexType = getIndexTypeOfType(objectType, 0 /* String */); - if (stringIndexType) { - return stringIndexType; + var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */); + if (stringIndexInfo) { + getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; + return stringIndexInfo.type; } // Fall back to any. if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); + error(node, getIndexTypeOfType(objectType, 1 /* Number */) ? + ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : + ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } return anyType; } @@ -21214,7 +23066,7 @@ var ts; if (indexArgumentExpression.kind === 9 /* StringLiteral */ || indexArgumentExpression.kind === 8 /* NumericLiteral */) { return indexArgumentExpression.text; } - if (indexArgumentExpression.kind === 167 /* ElementAccessExpression */ || indexArgumentExpression.kind === 166 /* PropertyAccessExpression */) { + if (indexArgumentExpression.kind === 171 /* ElementAccessExpression */ || indexArgumentExpression.kind === 170 /* PropertyAccessExpression */) { var value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); @@ -21269,10 +23121,10 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 174 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 139 /* Decorator */) { + else if (node.kind !== 141 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -21289,7 +23141,7 @@ var ts; // so order how inherited signatures are processed is still preserved. // interface A { (x: string): void } // interface B extends A { (x: 'foo'): string } - // let b: B; + // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] function reorderCandidates(signatures, result) { var lastParent; @@ -21302,13 +23154,13 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_5 = signature.declaration && signature.declaration.parent; + var parent_6 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_5 === lastParent) { + if (lastParent && parent_6 === lastParent) { index++; } else { - lastParent = parent_5; + lastParent = parent_6; index = cutoffIndex; } } @@ -21316,7 +23168,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_5; + lastParent = parent_6; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -21338,7 +23190,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 185 /* SpreadElementExpression */) { + if (arg && arg.kind === 189 /* SpreadElementExpression */) { return i; } } @@ -21350,13 +23202,13 @@ var ts; var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments var isDecorator; var spreadArgIndex = -1; - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 174 /* 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 === 183 /* TemplateExpression */) { + if (tagExpression.template.kind === 187 /* 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; @@ -21373,7 +23225,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 139 /* Decorator */) { + else if (node.kind === 141 /* Decorator */) { isDecorator = true; typeArguments = undefined; adjustedArgCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); @@ -21382,7 +23234,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 === 169 /* NewExpression */); + ts.Debug.assert(callExpression.kind === 173 /* NewExpression */); return signature.minArgumentCount === 0; } // For IDE scenarios we may have an incomplete call, so a trailing comma is tantamount to adding another argument. @@ -21417,7 +23269,7 @@ var ts; if (type.flags & 80896 /* ObjectType */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && - resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) { + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { return resolved.callSignatures[0]; } } @@ -21434,7 +23286,7 @@ var ts; } function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; - var inferenceMapper = createInferenceMapper(context); + var inferenceMapper = getInferenceMapper(context); // Clear out all the inference results from the last time inferTypeArguments was called on this context for (var i = 0; i < typeParameters.length; i++) { // As an optimization, we don't have to clear (and later recompute) inferred types @@ -21461,7 +23313,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 187 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 191 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); // If the effective argument type is 'undefined', there is no synthetic type @@ -21482,7 +23334,7 @@ var ts; // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. if (excludeArgument) { for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exlusion value is always undefined + // No need to check for omitted args and template expressions, their exclusion value is always undefined if (excludeArgument[i] === false) { var arg = args[i]; var paramType = getTypeAtPosition(signature, i); @@ -21492,14 +23344,11 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; + var mapper; for (var i = 0; i < typeParameters.length; i++) { - var typeArgNode = typeArguments[i]; - var typeArgument = getTypeFromTypeNode(typeArgNode); - // Do not push on this array! It has a preallocated length - typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable /* so far */) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { @@ -21509,7 +23358,11 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); typeArgumentHeadMessage = headMessage; } - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); } } } @@ -21520,7 +23373,7 @@ var ts; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 187 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 191 /* OmittedExpression */) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); @@ -21528,7 +23381,7 @@ var ts; // for the argument. In that case, we should check the argument. if (argType === undefined) { argType = arg.kind === 9 /* StringLiteral */ && !reportErrors - ? getStringLiteralType(arg) + ? getStringLiteralTypeForText(arg.text) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } // Use argument expression as error location when reporting errors @@ -21552,16 +23405,16 @@ var ts; */ function getEffectiveCallArguments(node) { var args; - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 174 /* TaggedTemplateExpression */) { var template = node.template; args = [undefined]; - if (template.kind === 183 /* TemplateExpression */) { + if (template.kind === 187 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } - else if (node.kind === 139 /* Decorator */) { + else if (node.kind === 141 /* Decorator */) { // For a decorator, we return undefined as we will determine // the number and types of arguments for a decorator using // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. @@ -21586,19 +23439,19 @@ var ts; * Otherwise, the argument count is the length of the 'args' array. */ function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 139 /* Decorator */) { + if (node.kind === 141 /* Decorator */) { switch (node.parent.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; - case 141 /* PropertyDeclaration */: + case 143 /* PropertyDeclaration */: // A property declaration decorator will have two arguments (see // `PropertyDecorator` in core.d.ts) return 2; - case 143 /* MethodDeclaration */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts) // If we are emitting decorators for ES3, we will only pass two arguments. @@ -21608,7 +23461,7 @@ var ts; // If the method decorator signature only accepts a target and a key, we will only // type check those arguments. return signature.parameters.length >= 3 ? 3 : 2; - case 138 /* Parameter */: + case 140 /* Parameter */: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; @@ -21632,25 +23485,25 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 138 /* Parameter */) { + if (node.kind === 140 /* Parameter */) { // For a parameter decorator, the `target` is the parent type of the // parameter's containing method. node = node.parent; - if (node.kind === 144 /* Constructor */) { + if (node.kind === 146 /* Constructor */) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 141 /* PropertyDeclaration */ || - node.kind === 143 /* MethodDeclaration */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */) { + if (node.kind === 143 /* PropertyDeclaration */ || + node.kind === 145 /* MethodDeclaration */ || + node.kind === 147 /* GetAccessor */ || + node.kind === 148 /* SetAccessor */) { // For a property or method decorator, the `target` is the // "static"-side type of the parent of the member if the member is // declared "static"; otherwise, it is the "instance"-side type of the @@ -21677,21 +23530,21 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 138 /* Parameter */) { + if (node.kind === 140 /* Parameter */) { node = node.parent; - if (node.kind === 144 /* Constructor */) { + if (node.kind === 146 /* Constructor */) { // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } } - if (node.kind === 141 /* PropertyDeclaration */ || - node.kind === 143 /* MethodDeclaration */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */) { + if (node.kind === 143 /* PropertyDeclaration */ || + node.kind === 145 /* MethodDeclaration */ || + node.kind === 147 /* GetAccessor */ || + node.kind === 148 /* SetAccessor */) { // The `propertyKey` for a property or method decorator will be a // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will @@ -21701,10 +23554,10 @@ var ts; case 69 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getStringLiteralType(element.name); - case 136 /* ComputedPropertyName */: + return getStringLiteralTypeForText(element.name.text); + case 138 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); - if (allConstituentTypesHaveKind(nameType, 16777216 /* ESSymbol */)) { + if (isTypeOfKind(nameType, 16777216 /* ESSymbol */)) { return nameType; } else { @@ -21727,22 +23580,22 @@ var ts; */ function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a paramter decorator - if (node.kind === 214 /* ClassDeclaration */) { + // or its `parameterIndex` for a parameter decorator + if (node.kind === 218 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 138 /* Parameter */) { + if (node.kind === 140 /* Parameter */) { // The `parameterIndex` for a parameter decorator is always a number return numberType; } - if (node.kind === 141 /* PropertyDeclaration */) { + if (node.kind === 143 /* PropertyDeclaration */) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 143 /* MethodDeclaration */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */) { + if (node.kind === 145 /* MethodDeclaration */ || + node.kind === 147 /* GetAccessor */ || + node.kind === 148 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. var propertyType = getTypeOfNode(node); @@ -21774,10 +23627,10 @@ var ts; // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors - if (node.kind === 139 /* Decorator */) { + if (node.kind === 141 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 174 /* TaggedTemplateExpression */) { return globalTemplateStringsArrayType; } // This is not a synthetic argument, so we return 'undefined' @@ -21789,8 +23642,8 @@ var ts; */ function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 139 /* Decorator */ || - (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */)) { + if (node.kind === 141 /* Decorator */ || + (argIndex === 0 && node.kind === 174 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -21799,11 +23652,11 @@ var ts; * Gets the error node to use when reporting errors for an effective argument. */ function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 139 /* Decorator */) { + if (node.kind === 141 /* Decorator */) { // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 174 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -21812,8 +23665,8 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 170 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 139 /* Decorator */; + var isTaggedTemplate = node.kind === 174 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 141 /* Decorator */; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; @@ -21919,7 +23772,8 @@ var ts; } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], /*reportErrors*/ true, headMessage); + var typeArguments_2 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -21977,7 +23831,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -22031,8 +23885,10 @@ var ts; // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated // with the type arguments specified in the extends clause. var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); - var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); - return resolveCall(node, baseConstructors, candidatesOutArray); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); + } } return resolveUntypedCall(node); } @@ -22056,7 +23912,7 @@ var ts; // We exclude union types because we may have a union of function types that happen to have // no common signatures. 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 + // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== unknownType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); @@ -22119,6 +23975,9 @@ var ts; // that the user will not add any. var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } return resolveCall(node, constructSignatures, candidatesOutArray); } // If expressionType's apparent type is an object type with no construct signatures but @@ -22136,6 +23995,30 @@ var ts; error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); return resolveErrorCall(node); } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var flags = declaration.flags; + // Public constructor is accessible. + if (!(flags & (8 /* Private */ | 16 /* Protected */))) { + return true; + } + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + // A private or protected constructor can only be instantiated within it's own class + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + if (flags & 8 /* Private */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (flags & 16 /* Protected */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -22158,16 +24041,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 138 /* Parameter */: + case 140 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 141 /* PropertyDeclaration */: + case 143 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 143 /* MethodDeclaration */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -22186,7 +24069,7 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo; + var errorInfo = void 0; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); @@ -22204,16 +24087,16 @@ var ts; // to correctly fill the candidatesOutArray. if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 168 /* CallExpression */) { + if (node.kind === 172 /* CallExpression */) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 169 /* NewExpression */) { + else if (node.kind === 173 /* NewExpression */) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 174 /* TaggedTemplateExpression */) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } - else if (node.kind === 139 /* Decorator */) { + else if (node.kind === 141 /* Decorator */) { links.resolvedSignature = resolveDecorator(node, candidatesOutArray); } else { @@ -22222,6 +24105,13 @@ var ts; } return links.resolvedSignature; } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } /** * Syntactically and semantically checks a call or new expression. * @param node The call/new expression to be checked. @@ -22234,19 +24124,30 @@ var ts; if (node.expression.kind === 95 /* SuperKeyword */) { return voidType; } - if (node.kind === 169 /* NewExpression */) { + if (node.kind === 173 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 144 /* Constructor */ && - declaration.kind !== 148 /* ConstructSignature */ && - declaration.kind !== 153 /* ConstructorType */) { - // When resolved signature is a call signature (and not a construct signature) the result type is any - if (compilerOptions.noImplicitAny) { + declaration.kind !== 146 /* Constructor */ && + declaration.kind !== 150 /* ConstructSignature */ && + declaration.kind !== 155 /* ConstructorType */ && + !ts.isJSDocConstructSignature(declaration)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + var funcSymbol = checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */)) { + return getInferredClassType(funcSymbol); + } + else if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; } } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } return getReturnTypeOfSignature(signature); } function checkTaggedTemplateExpression(node) { @@ -22257,7 +24158,10 @@ var ts; var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); - if (!(isTypeAssignableTo(targetType, widenedType))) { + // Permit 'number[] | "foo"' to be asserted to 'string'. + var bothAreStringLike = maybeTypeOfKind(targetType, 258 /* StringLike */) && + maybeTypeOfKind(widenedType, 258 /* StringLike */); + if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } } @@ -22287,7 +24191,7 @@ var ts; if (ts.isBindingPattern(node.name)) { for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 191 /* OmittedExpression */) { if (element.name.kind === 69 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -22335,6 +24239,13 @@ var ts; inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); } } + function getReturnTypeFromJSDocComment(func) { + var returnTag = ts.getJSDocReturnTag(func); + if (returnTag && returnTag.typeExpression) { + return getTypeFromTypeNode(returnTag.typeExpression.type); + } + return undefined; + } function createPromiseType(promisedType) { // creates a `Promise` type where `T` is the promisedType argument var globalPromiseType = getGlobalPromiseType(); @@ -22352,7 +24263,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 192 /* Block */) { + if (func.body.kind !== 196 /* Block */) { type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -22363,7 +24274,7 @@ var ts; } } else { - var types; + var types = void 0; var funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); @@ -22402,7 +24313,8 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience + return getUnionType(types); } } if (funcIsGenerator) { @@ -22465,48 +24377,61 @@ var ts; }); return aggregatedTypes; } - // TypeScript Specification 1.0 (6.3) - July 2014 - // An explicitly typed function whose return type isn't the Void or the Any type - // must have at least one return statement somewhere in its body. - // An exception to this rule is if the function implementation consists of a single 'throw' statement. + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; } - // Functions that return 'void' or 'any' don't need any return expressions. - if (returnType === voidType || isTypeAny(returnType)) { + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 16 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - // also if HasImplicitReturnValue flags is not set this means that all codepaths in function body end with return of throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 /* Block */ || !(func.flags & 524288 /* HasImplicitReturn */)) { + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (ts.nodeIsMissing(func.body) || func.body.kind !== 196 /* Block */ || !(func.flags & 32768 /* HasImplicitReturn */)) { return; } - if (func.flags & 1048576 /* HasExplicitReturn */) { - if (compilerOptions.noImplicitReturns) { - error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { - // This function does not conform to the specification. + var hasExplicitReturn = func.flags & 65536 /* HasExplicitReturn */; + if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + var inferredReturnType = hasExplicitReturn + ? getReturnTypeOfSignature(getSignatureFromDeclaration(func)) + : voidType; + if (inferredReturnType === voidType || isTypeAny(inferredReturnType)) { + return; + } + } + error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { - ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 145 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 173 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 177 /* FunctionExpression */) { checkGrammarForGenerator(node); } // The identityMapper object is used to indicate that function expressions are wildcards if (contextualMapper === identityMapper && isContextSensitive(node)) { return anyFunctionType; } - var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } var links = getNodeLinks(node); var type = getTypeOfSymbol(node.symbol); var contextSensitive = isContextSensitive(node); @@ -22536,28 +24461,23 @@ var ts; } if (!contextChecked) { checkSignatureDeclaration(node); + checkNodeDeferred(node); } } } - if (produceDiagnostics && node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 145 /* MethodDeclaration */ && node.kind !== 144 /* MethodSignature */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } - function checkFunctionExpressionOrObjectLiteralMethodBody(node) { - ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 145 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } - var returnType = node.type && getTypeFromTypeNode(node.type); - var promisedType; - if (returnType && isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - if (returnType && !node.asteriskToken) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + if (!node.asteriskToken) { + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { if (!node.type) { @@ -22568,7 +24488,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 192 /* Block */) { + if (node.body.kind === 196 /* Block */) { checkSourceElement(node.body); } else { @@ -22578,16 +24498,15 @@ var ts; // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. var exprType = checkExpression(node.body); - if (returnType) { + if (returnOrPromisedType) { if (isAsync) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); - checkTypeAssignableTo(awaitedType, promisedType, node.body); + checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } else { - checkTypeAssignableTo(exprType, returnType, node.body); + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } - checkFunctionAndClassExpressionBodies(node.body); } } } @@ -22598,75 +24517,74 @@ var ts; } return true; } - function checkReferenceExpression(n, invalidReferenceMessage, constantVariableMessage) { - function findSymbol(n) { - var symbol = getNodeLinks(n).resolvedSymbol; - // Because we got the symbol from the resolvedSymbol property, it might be of kind - // SymbolFlags.ExportValue. In this case it is necessary to get the actual export - // symbol, which will have the correct flags set on it. - return symbol && getExportSymbolOfValueSymbolIfExported(symbol); + function isReadonlySymbol(symbol) { + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + return symbol.flags & 4 /* Property */ && (getDeclarationFlagsFromSymbol(symbol) & 64 /* Readonly */) !== 0 || + symbol.flags & 3 /* Variable */ && (getDeclarationFlagsFromSymbol(symbol) & 2048 /* Const */) !== 0 || + symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || + (symbol.flags & 8 /* EnumMember */) !== 0; + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & 4 /* Property */ && + (expr.kind === 170 /* PropertyAccessExpression */ || expr.kind === 171 /* ElementAccessExpression */) && + expr.expression.kind === 97 /* ThisKeyword */) { + var func = ts.getContainingFunction(expr); + return !(func && func.kind === 146 /* Constructor */ && func.parent === symbol.valueDeclaration.parent); + } + return true; } - function isReferenceOrErrorExpression(n) { - // TypeScript 1.0 spec (April 2014): - // Expressions are classified as values or references. - // References are the subset of expressions that are permitted as the target of an assignment. - // Specifically, references are combinations of identifiers(section 4.3), parentheses(section 4.7), - // and property accesses(section 4.10). - // All other expression constructs described in this chapter are classified as values. - switch (n.kind) { - case 69 /* Identifier */: { - var symbol = findSymbol(n); - // TypeScript 1.0 spec (April 2014): 4.3 - // An identifier expression that references a variable or parameter is classified as a reference. - // 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; + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 170 /* PropertyAccessExpression */ || expr.kind === 171 /* ElementAccessExpression */) { + var node = skipParenthesizedNodes(expr.expression); + if (node.kind === 69 /* Identifier */) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 8388608 /* Alias */) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return declaration && declaration.kind === 228 /* NamespaceImport */; } - case 166 /* 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 167 /* ElementAccessExpression */: - // old compiler doesn't check indexed access - return true; - case 172 /* ParenthesizedExpression */: - return isReferenceOrErrorExpression(n.expression); - default: - return false; } } - function isConstVariableReference(n) { - switch (n.kind) { - case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: { - var symbol = findSymbol(n); - return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384 /* Const */) !== 0; - } - case 167 /* ElementAccessExpression */: { - var index = n.argumentExpression; - var symbol = findSymbol(n.expression); - if (symbol && index && index.kind === 9 /* StringLiteral */) { - var name_12 = index.text; - var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_12); - return prop && (prop.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 16384 /* Const */) !== 0; - } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage, constantVariableMessage) { + // References are combinations of identifiers, parentheses, and property accesses. + var node = skipParenthesizedNodes(expr); + if (node.kind !== 69 /* Identifier */ && node.kind !== 170 /* PropertyAccessExpression */ && node.kind !== 171 /* ElementAccessExpression */) { + error(expr, invalidReferenceMessage); + return false; + } + // Because we get the symbol from the resolvedSymbol property, it might be of kind + // SymbolFlags.ExportValue. In this case it is necessary to get the actual export + // symbol, which will have the correct flags set on it. + var links = getNodeLinks(node); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol) { + if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { + // Only variables (and not functions, classes, namespaces, enum objects, or enum members) + // are considered references when referenced using a simple identifier. + if (node.kind === 69 /* Identifier */ && !(symbol.flags & 3 /* Variable */)) { + error(expr, invalidReferenceMessage); return false; } - case 172 /* ParenthesizedExpression */: - return isConstVariableReference(n.expression); - default: + if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { + error(expr, constantVariableMessage); return false; + } } } - if (!isReferenceOrErrorExpression(n)) { - error(n, invalidReferenceMessage); - return false; - } - if (isConstVariableReference(n)) { - error(n, constantVariableMessage); - return false; + else if (node.kind === 171 /* ElementAccessExpression */) { + if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { + error(expr, constantVariableMessage); + return false; + } } return true; } @@ -22685,7 +24603,7 @@ var ts; function checkAwaitExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.parserContextFlags & 8 /* Await */)) { + if (!(node.flags & 33554432 /* AwaitContext */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -22701,7 +24619,7 @@ var ts; case 35 /* PlusToken */: case 36 /* MinusToken */: case 50 /* TildeToken */: - if (someConstituentTypeHasKind(operandType, 16777216 /* ESSymbol */)) { + if (maybeTypeOfKind(operandType, 16777216 /* ESSymbol */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -22712,7 +24630,7 @@ var ts; var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); } return numberType; } @@ -22723,43 +24641,53 @@ var ts; var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); } return numberType; } - // Just like isTypeOfKind below, except that it returns true if *any* constituent - // has this kind. - function someConstituentTypeHasKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 49152 /* UnionOrIntersection */) { - var types = type.types; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var current = types_9[_i]; - if (current.flags & kind) { - return true; - } - } - return false; - } - return false; - } - // Return true if type has the given flags, or is a union or intersection type composed of types that all have those flags. - function allConstituentTypesHaveKind(type, kind) { + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type, kind) { if (type.flags & kind) { return true; } if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var current = types_10[_i]; - if (!(current.flags & kind)) { + var t = types_10[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + // Return true if type is of the given kind. A union type is of a given kind if all constituent types + // are of the given kind. An intersection type is of a given kind if at least one constituent type is + // of the given kind. + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 16384 /* Union */) { + var types = type.types; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + if (!isTypeOfKind(t, kind)) { return false; } } return true; } + if (type.flags & 32768 /* Intersection */) { + var types = type.types; + for (var _a = 0, types_12 = types; _a < types_12.length; _a++) { + var t = types_12[_a]; + if (isTypeOfKind(t, kind)) { + return true; + } + } + } return false; } function isConstEnumObjectType(type) { @@ -22774,7 +24702,7 @@ 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, 16777726 /* Primitive */)) { + if (isTypeOfKind(leftType, 16777726 /* Primitive */)) { error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported @@ -22800,24 +24728,31 @@ var ts; var properties = node.properties; for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var p = properties_3[_i]; - if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { - // TODO(andersh): Computed property support - var name_13 = p.name; + if (p.kind === 249 /* PropertyAssignment */ || p.kind === 250 /* ShorthandPropertyAssignment */) { + var name_12 = p.name; + if (name_12.kind === 138 /* ComputedPropertyName */) { + checkComputedPropertyName(name_12); + } + if (isComputedNonLiteralName(name_12)) { + continue; + } + var text = getTextOfPropertyName(name_12); var type = isTypeAny(sourceType) ? sourceType - : getTypeOfPropertyOfType(sourceType, name_13.text) || - isNumericLiteralName(name_13.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || + : getTypeOfPropertyOfType(sourceType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); if (type) { - if (p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 250 /* ShorthandPropertyAssignment */) { checkDestructuringAssignment(p, type); } else { - checkDestructuringAssignment(p.initializer || name_13, type); + // non-shorthand property assignments should always have initializers + checkDestructuringAssignment(p.initializer, type); } } else { - error(name_13, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_13)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_12)); } } else { @@ -22834,8 +24769,8 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187 /* OmittedExpression */) { - if (e.kind !== 185 /* SpreadElementExpression */) { + if (e.kind !== 191 /* OmittedExpression */) { + if (e.kind !== 189 /* SpreadElementExpression */) { var propName = "" + i; var type = isTypeAny(sourceType) ? sourceType @@ -22860,7 +24795,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 181 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { + if (restExpression.kind === 185 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -22874,7 +24809,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 246 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 250 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -22884,21 +24819,21 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + if (target.kind === 185 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 165 /* ObjectLiteralExpression */) { + if (target.kind === 169 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 164 /* ArrayLiteralExpression */) { + if (target.kind === 168 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); } function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant)) { + if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); } return sourceType; @@ -22908,7 +24843,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 /* EqualsToken */ && (left.kind === 165 /* ObjectLiteralExpression */ || left.kind === 164 /* ArrayLiteralExpression */)) { + if (operator === 56 /* EqualsToken */ && (left.kind === 169 /* ObjectLiteralExpression */ || left.kind === 168 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); @@ -22946,7 +24881,7 @@ var ts; leftType = rightType; if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) rightType = leftType; - var suggestedOperator; + var suggestedOperator = void 0; // if a user tries to apply a bitwise operator to 2 boolean operands // try and return them a helpful suggestion if ((leftType.flags & 8 /* Boolean */) && @@ -22973,14 +24908,14 @@ var ts; leftType = rightType; if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) rightType = leftType; - var resultType; - if (allConstituentTypesHaveKind(leftType, 132 /* NumberLike */) && allConstituentTypesHaveKind(rightType, 132 /* NumberLike */)) { + var resultType = void 0; + if (isTypeOfKind(leftType, 132 /* NumberLike */) && isTypeOfKind(rightType, 132 /* NumberLike */)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } else { - if (allConstituentTypesHaveKind(leftType, 258 /* StringLike */) || allConstituentTypesHaveKind(rightType, 258 /* StringLike */)) { + if (isTypeOfKind(leftType, 258 /* StringLike */) || isTypeOfKind(rightType, 258 /* StringLike */)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -23014,6 +24949,10 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: + // Permit 'number[] | "foo"' to be asserted to 'string'. + if (maybeTypeOfKind(leftType, 258 /* StringLike */) && maybeTypeOfKind(rightType, 258 /* StringLike */)) { + return booleanType; + } if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) { reportOperatorError(); } @@ -23034,8 +24973,8 @@ var ts; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 16777216 /* ESSymbol */) ? left : - someConstituentTypeHasKind(rightType, 16777216 /* ESSymbol */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 16777216 /* ESSymbol */) ? left : + maybeTypeOfKind(rightType, 16777216 /* ESSymbol */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -23066,7 +25005,7 @@ var ts; // requires VarExpr to be classified as a reference // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) // and the type of the non - compound operation to be assignable to the type of VarExpr. - var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); // Use default messages if (ok) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported @@ -23096,7 +25035,7 @@ var ts; function checkYieldExpression(node) { // Grammar checking if (produceDiagnostics) { - if (!(node.parserContextFlags & 2 /* Yield */) || isYieldExpressionInClass(node)) { + if (!(node.flags & 8388608 /* YieldContext */) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } if (isInParameterInitializerBeforeContainingFunction(node)) { @@ -23109,7 +25048,7 @@ var ts; // we are in a yield context. if (func && func.asteriskToken) { var expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); - var expressionElementType; + var expressionElementType = void 0; var nodeIsYieldStar = !!node.asteriskToken; if (nodeIsYieldStar) { expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); @@ -23137,6 +25076,13 @@ var ts; var type2 = checkExpression(node.whenFalse, contextualMapper); return getUnionType([type1, type2]); } + function checkStringLiteralExpression(node) { + var contextualType = getContextualType(node); + if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + return getStringLiteralTypeForText(node.text); + } + return stringType; + } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with // the type of each expression, as any value may be coerced into a string. @@ -23166,7 +25112,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 === 136 /* ComputedPropertyName */) { + if (node.name.kind === 138 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpression(node.initializer, contextualMapper); @@ -23177,7 +25123,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 === 136 /* ComputedPropertyName */) { + if (node.name.kind === 138 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -23187,7 +25133,7 @@ var ts; if (isInferentialContext(contextualMapper)) { var signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); if (contextualType) { var contextualSignature = getSingleCallSignature(contextualType); if (contextualSignature && !contextualSignature.typeParameters) { @@ -23207,7 +25153,7 @@ var ts; // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, contextualMapper) { var type; - if (node.kind === 135 /* QualifiedName */) { + if (node.kind === 137 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -23219,9 +25165,9 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 167 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + var ok = (node.parent.kind === 170 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 171 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 69 /* Identifier */ || node.kind === 137 /* 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); } @@ -23248,65 +25194,66 @@ var ts; return booleanType; case 8 /* NumericLiteral */: return checkNumericLiteral(node); - case 183 /* TemplateExpression */: + case 187 /* TemplateExpression */: return checkTemplateExpression(node); case 9 /* StringLiteral */: + return checkStringLiteralExpression(node); case 11 /* NoSubstitutionTemplateLiteral */: return stringType; case 10 /* RegularExpressionLiteral */: return globalRegExpType; - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return checkArrayLiteral(node, contextualMapper); - case 165 /* ObjectLiteralExpression */: + case 169 /* ObjectLiteralExpression */: return checkObjectLiteral(node, contextualMapper); - case 166 /* PropertyAccessExpression */: + case 170 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 167 /* ElementAccessExpression */: + case 171 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: return checkCallExpression(node); - case 170 /* TaggedTemplateExpression */: + case 174 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return checkExpression(node.expression, contextualMapper); - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: return checkClassExpression(node); - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 176 /* TypeOfExpression */: + case 180 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 175 /* TypeAssertionExpression */: + case 193 /* AsExpression */: return checkAssertion(node); - case 175 /* DeleteExpression */: + case 179 /* DeleteExpression */: return checkDeleteExpression(node); - case 177 /* VoidExpression */: + case 181 /* VoidExpression */: return checkVoidExpression(node); - case 178 /* AwaitExpression */: + case 182 /* AwaitExpression */: return checkAwaitExpression(node); - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 180 /* PostfixUnaryExpression */: + case 184 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return checkBinaryExpression(node, contextualMapper); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 185 /* SpreadElementExpression */: + case 189 /* SpreadElementExpression */: return checkSpreadElementExpression(node, contextualMapper); - case 187 /* OmittedExpression */: + case 191 /* OmittedExpression */: return undefinedType; - case 184 /* YieldExpression */: + case 188 /* YieldExpression */: return checkYieldExpression(node); - case 240 /* JsxExpression */: + case 244 /* JsxExpression */: return checkJsxExpression(node); - case 233 /* JsxElement */: + case 237 /* JsxElement */: return checkJsxElement(node); - case 234 /* JsxSelfClosingElement */: + case 238 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node); - case 235 /* JsxOpeningElement */: + case 239 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -23318,11 +25265,10 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); + getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node))); if (produceDiagnostics) { - checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } - // TODO: Check multiple declarations are identical } function checkParameter(node) { // Grammar checking @@ -23333,9 +25279,9 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 56 /* AccessibilityModifier */) { + if (node.flags & 28 /* AccessibilityModifier */) { func = ts.getContainingFunction(node); - if (!(func.kind === 144 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 146 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -23352,9 +25298,9 @@ var ts; if (!node.asteriskToken || !node.body) { return false; } - return node.kind === 143 /* MethodDeclaration */ || - node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */; + return node.kind === 145 /* MethodDeclaration */ || + node.kind === 217 /* FunctionDeclaration */ || + node.kind === 177 /* FunctionExpression */; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { @@ -23368,91 +25314,100 @@ var ts; } return -1; } - function isInLegalTypePredicatePosition(node) { + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name_13 = _a[_i].name; + if (ts.isBindingPattern(name_13) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_13, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { switch (node.parent.kind) { - case 174 /* ArrowFunction */: - case 147 /* CallSignature */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 152 /* FunctionType */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - return node === node.parent.type; + case 178 /* ArrowFunction */: + case 149 /* CallSignature */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 154 /* FunctionType */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + var parent_7 = node.parent; + if (node === parent_7.type) { + return parent_7; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var name_14 = _a[_i].name; + if (name_14.kind === 69 /* Identifier */ && + name_14.text === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name_14.kind === 166 /* ArrayBindingPattern */ || + name_14.kind === 165 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_14, predicateVariableNode, predicateVariableName)) { + return true; + } + } } - return false; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 149 /* IndexSignature */) { + if (node.kind === 151 /* IndexSignature */) { checkGrammarIndexSignature(node); } - else if (node.kind === 152 /* FunctionType */ || node.kind === 213 /* FunctionDeclaration */ || node.kind === 153 /* ConstructorType */ || - node.kind === 147 /* CallSignature */ || node.kind === 144 /* Constructor */ || - node.kind === 148 /* ConstructSignature */) { + else if (node.kind === 154 /* FunctionType */ || node.kind === 217 /* FunctionDeclaration */ || node.kind === 155 /* ConstructorType */ || + node.kind === 149 /* CallSignature */ || node.kind === 146 /* Constructor */ || + node.kind === 150 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } checkTypeParameters(node.typeParameters); ts.forEach(node.parameters, checkParameter); if (node.type) { - if (node.type.kind === 150 /* 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, getTypeOfNode(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 === 161 /* ObjectBindingPattern */ || - param.name.kind === 162 /* ArrayBindingPattern */) { - (function checkBindingPattern(pattern) { - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (element.name.kind === 69 /* 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 === 162 /* ArrayBindingPattern */ || - element.name.kind === 161 /* 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); - } + checkSourceElement(node.type); } if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 148 /* ConstructSignature */: + case 150 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 147 /* CallSignature */: + case 149 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -23475,12 +25430,14 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } + else if (ts.isAsyncFunctionLike(node)) { + checkAsyncFunctionReturnType(node); + } } } - checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 215 /* InterfaceDeclaration */) { + if (node.kind === 219 /* 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 @@ -23500,7 +25457,7 @@ var ts; var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { - case 130 /* StringKeyword */: + case 131 /* StringKeyword */: if (!seenStringIndexer) { seenStringIndexer = true; } @@ -23508,7 +25465,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 128 /* NumberKeyword */: + case 129 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -23530,7 +25487,7 @@ var ts; // Grammar checking checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration - checkFunctionLikeDeclaration(node); + checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. if (node.flags & 128 /* Abstract */ && node.body) { @@ -23540,7 +25497,7 @@ var ts; function checkConstructorDeclaration(node) { // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. checkSignatureDeclaration(node); - // Grammar check for checking only related to constructoDeclaration + // Grammar check for checking only related to constructorDeclaration checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); var symbol = getSymbolOfNode(node); @@ -23556,14 +25513,11 @@ var ts; if (!produceDiagnostics) { return; } - function isSuperCallExpression(n) { - return n.kind === 168 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; - } function containsSuperCallAsComputedPropertyName(n) { return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (isSuperCallExpression(n)) { + if (ts.isSuperCallExpression(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -23578,13 +25532,13 @@ var ts; if (n.kind === 97 /* ThisKeyword */) { error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); } - else if (n.kind !== 173 /* FunctionExpression */ && n.kind !== 213 /* FunctionDeclaration */) { + else if (n.kind !== 177 /* FunctionExpression */ && n.kind !== 217 /* FunctionDeclaration */) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 141 /* PropertyDeclaration */ && - !(n.flags & 64 /* Static */) && + return n.kind === 143 /* PropertyDeclaration */ && + !(n.flags & 32 /* Static */) && !!n.initializer; } // TS 1.0 spec (April 2014): 8.3.2 @@ -23592,12 +25546,11 @@ var ts; // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { - var containingClassSymbol = getSymbolOfNode(containingClassDecl); - var containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); - var baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); - if (containsSuperCall(node.body)) { - if (baseConstructorType === nullType) { - error(node, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } // The first statement in the body of a constructor (excluding prologue directives) must be a super call // if both of the following are true: @@ -23605,15 +25558,15 @@ var ts; // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & (8 /* Public */ | 16 /* Private */ | 32 /* Protected */); }); + ts.forEach(node.parameters, function (p) { return p.flags & (4 /* Public */ | 8 /* Private */ | 16 /* Protected */); }); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { var statements = node.body.statements; - var superCallStatement; + var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 195 /* ExpressionStatement */ && isSuperCallExpression(statement.expression)) { + if (statement.kind === 199 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; } @@ -23624,13 +25577,9 @@ var ts; if (!superCallStatement) { error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); } - else { - // In such a required super call, it is a compile-time error for argument expressions to reference this. - markThisReferencesAsErrors(superCallStatement.expression); - } } } - else if (baseConstructorType !== nullType) { + else if (!classExtendsNull) { error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); } } @@ -23639,9 +25588,11 @@ var ts; if (produceDiagnostics) { // Grammar checking accessors checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (node.kind === 145 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288 /* HasImplicitReturn */)) { - if (node.flags & 1048576 /* HasExplicitReturn */) { + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 147 /* GetAccessor */) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 32768 /* HasImplicitReturn */)) { + if (node.flags & 65536 /* HasExplicitReturn */) { if (compilerOptions.noImplicitReturns) { error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -23651,15 +25602,24 @@ 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 === 138 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } if (!ts.hasDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 145 /* GetAccessor */ ? 146 /* SetAccessor */ : 145 /* GetAccessor */; + var otherKind = node.kind === 147 /* GetAccessor */ ? 148 /* SetAccessor */ : 147 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 56 /* AccessibilityModifier */) !== (otherAccessor.flags & 56 /* AccessibilityModifier */))) { + if (((node.flags & 28 /* AccessibilityModifier */) !== (otherAccessor.flags & 28 /* AccessibilityModifier */))) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } + if (((node.flags & 128 /* Abstract */) !== (otherAccessor.flags & 128 /* Abstract */))) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } var currentAccessorType = getAnnotatedAccessorType(node); var otherAccessorType = getAnnotatedAccessorType(otherAccessor); // TypeScript 1.0 spec (April 2014): 4.5 @@ -23673,18 +25633,32 @@ var ts; } getTypeOfAccessors(getSymbolOfNode(node)); } - checkFunctionLikeDeclaration(node); + if (node.parent.kind !== 169 /* ObjectLiteralExpression */) { + checkSourceElement(node.body); + } + else { + checkNodeDeferred(node); + } + } + function checkAccessorDeferred(node) { + checkSourceElement(node.body); } function checkMissingDeclaration(node) { checkDecorators(node); } - function checkTypeArgumentConstraints(typeParameters, typeArguments) { + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var typeArguments; + var mapper; var result = true; for (var i = 0; i < typeParameters.length; i++) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { + if (!typeArguments) { + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + mapper = createTypeMapper(typeParameters, typeArguments); + } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -23728,59 +25702,21 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 16 /* Private */) && ts.isInAmbientContext(node); - } - function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { - if (!produceDiagnostics) { - return; - } - var signature = getSignatureFromDeclaration(signatureDeclarationNode); - if (!signature.hasStringLiterals) { - return; - } - // TypeScript 1.0 spec (April 2014): 3.7.2.2 - // Specialized signatures are not permitted in conjunction with a function body - if (ts.nodeIsPresent(signatureDeclarationNode.body)) { - error(signatureDeclarationNode, ts.Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type); - return; - } - // TypeScript 1.0 spec (April 2014): 3.7.2.4 - // Every specialized call or construct signature in an object type must be assignable - // to at least one non-specialized call or construct signature in the same object type - 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 === 215 /* InterfaceDeclaration */) { - ts.Debug.assert(signatureDeclarationNode.kind === 147 /* CallSignature */ || signatureDeclarationNode.kind === 148 /* ConstructSignature */); - var signatureKind = signatureDeclarationNode.kind === 147 /* CallSignature */ ? 0 /* Call */ : 1 /* Construct */; - var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); - var containingType = getDeclaredTypeOfSymbol(containingSymbol); - signaturesToCheck = getSignaturesOfType(containingType, signatureKind); - } - else { - signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); - } - for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { - var otherSignature = signaturesToCheck_1[_i]; - if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { - return; - } - } - error(signatureDeclarationNode, ts.Diagnostics.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature); + return (node.flags & 8 /* Private */) && ts.isInAmbientContext(node); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedNodeFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 215 /* InterfaceDeclaration */ && - n.parent.kind !== 214 /* ClassDeclaration */ && - n.parent.kind !== 186 /* ClassExpression */ && + if (n.parent.kind !== 219 /* InterfaceDeclaration */ && + n.parent.kind !== 218 /* ClassDeclaration */ && + n.parent.kind !== 190 /* ClassExpression */ && ts.isInAmbientContext(n)) { - if (!(flags & 4 /* Ambient */)) { + if (!(flags & 2 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported - flags |= 2 /* Export */; + flags |= 1 /* Export */; } - flags |= 4 /* Ambient */; + flags |= 2 /* Ambient */; } return flags & flagsToCheck; } @@ -23802,36 +25738,36 @@ var ts; // deviations, we XOR someOverloadFlags with allOverloadFlags var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; if (someButNotAllOverloadFlags !== 0) { - var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); ts.forEach(overloads, function (o) { - var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - if (deviation & 2 /* Export */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1 /* Export */) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } - else if (deviation & 4 /* Ambient */) { + else if (deviation & 2 /* Ambient */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (16 /* Private */ | 32 /* Protected */)) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + else if (deviation & (8 /* Private */ | 16 /* Protected */)) { + error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128 /* Abstract */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } } function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { if (someHaveQuestionToken !== allHaveQuestionToken) { - var canonicalHasQuestionToken = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); ts.forEach(overloads, function (o) { - var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken; + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } } - var flagsToCheck = 2 /* Export */ | 4 /* Ambient */ | 16 /* Private */ | 32 /* Protected */ | 128 /* Abstract */; + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; var someNodeFlags = 0; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; @@ -23855,16 +25791,23 @@ var ts; seen = c === node; } }); - if (subsequentNode) { + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { var errorNode_1 = subsequentNode.name || subsequentNode; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - // 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 === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */); - ts.Debug.assert((node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* Static */)); - var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); + var reportError = (node.kind === 145 /* MethodDeclaration */ || node.kind === 144 /* MethodSignature */) && + (node.flags & 32 /* Static */) !== (subsequentNode.flags & 32 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = node.flags & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } return; } else if (ts.nodeIsPresent(subsequentNode.body)) { @@ -23897,7 +25840,7 @@ var ts; var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 215 /* InterfaceDeclaration */ || node.parent.kind === 155 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 219 /* InterfaceDeclaration */ || node.parent.kind === 157 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -23908,7 +25851,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 === 213 /* FunctionDeclaration */ || node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */ || node.kind === 144 /* Constructor */) { + if (node.kind === 217 /* FunctionDeclaration */ || node.kind === 145 /* MethodDeclaration */ || node.kind === 144 /* MethodSignature */ || node.kind === 146 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -23960,29 +25903,11 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - // If the implementation signature has string literals, we will have reported an error in - // checkSpecializedSignatureDeclaration - if (!bodySignature.hasStringLiterals) { - // TypeScript 1.0 spec (April 2014): 6.1 - // If a function declaration includes overloads, the overloads determine the call - // signatures of the type given to the function object - // and the function implementation signature must be assignable to that type - // - // TypeScript 1.0 spec (April 2014): 3.8.4 - // Note that specialized call and construct signatures (section 3.7.2.4) are not significant when determining assignment compatibility - // Consider checking against specialized signatures too. Not doing so creates a type hole: - // - // function g(x: "hi", y: boolean); - // function g(x: string, y: {}); - // function g(x: string, y: string) { } - // - // The implementation is completely unrelated to the specialized signature, yet we do not check this. - for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { - var signature = signatures_3[_a]; - if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { - error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); - break; - } + for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { + var signature = signatures_3[_a]; + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; } } } @@ -24015,8 +25940,8 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var d = _a[_i]; var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 2 /* Export */ | 512 /* Default */); - if (effectiveDeclarationFlags & 2 /* Export */) { + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { if (effectiveDeclarationFlags & 512 /* Default */) { defaultExportedDeclarationSpaces |= declarationSpaces; } @@ -24028,7 +25953,7 @@ var ts; nonExportedDeclarationSpaces |= declarationSpaces; } } - // Spaces for anyting not declared a 'default export'. + // Spaces for anything not declared a 'default export'. var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; @@ -24037,7 +25962,7 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); - // Only error on the declarations that conributed to the intersecting spaces. + // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); } @@ -24048,20 +25973,20 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return 2097152 /* ExportType */; - case 218 /* ModuleDeclaration */: - return d.name.kind === 9 /* StringLiteral */ || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + case 222 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ : 4194304 /* ExportNamespace */; - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 221 /* ImportEqualsDeclaration */: - var result = 0; + case 225 /* ImportEqualsDeclaration */: + var result_1 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); - return result; + ts.forEach(target.declarations, function (d) { result_1 |= getDeclarationSpaces(d); }); + return result_1; default: return 1048576 /* ExportValue */; } @@ -24218,6 +26143,33 @@ var ts; } } } + /** + * Checks that the return type provided is an instantiation of the global Promise type + * and returns the awaited type of the return type. + * + * @param returnType The return type of a FunctionLikeDeclaration + * @param location The node on which to report the error. + */ + function checkCorrectPromiseType(returnType, location) { + if (returnType === unknownType) { + // The return type already had some other error, so we ignore and return + // the unknown type. + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType === emptyGenericType + || globalPromiseType === getTargetType(returnType)) { + // Either we couldn't resolve the global promise type, which would have already + // reported an error, or we could resolve it and the return type is a valid type + // reference to the global type. In either case, we return the awaited type for + // the return type. + return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + } + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(location, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } /** * Checks the return type of an async function to ensure it is a compatible * Promise implementation. @@ -24232,6 +26184,10 @@ var ts; * callable `then` signature. */ function checkAsyncFunctionReturnType(node) { + if (languageVersion >= 2 /* ES6 */) { + var returnType = getTypeFromTypeNode(node.type); + return checkCorrectPromiseType(returnType, node.type); + } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify @@ -24278,6 +26234,8 @@ var ts; error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } + // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. + checkReturnTypeAnnotationAsExpression(node); // Validate the promise constructor type. var promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { @@ -24285,10 +26243,10 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var promiseName = ts.getEntityNameFromTypeNode(node.type); - var root = getFirstIdentifier(promiseName); - var rootSymbol = getSymbol(node.locals, root.text, 107455 /* Value */); + var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); + var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, 107455 /* Value */); if (rootSymbol) { - error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, getFullyQualifiedName(promiseConstructor)); + error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } // Get and return the awaited type of the return type. @@ -24305,22 +26263,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 138 /* Parameter */: + case 140 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 141 /* PropertyDeclaration */: + case 143 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 143 /* MethodDeclaration */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -24333,9 +26291,9 @@ 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 === 151 /* TypeReference */) { + if (node && node.kind === 153 /* TypeReference */) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = root.parent.kind === 153 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; // Resolve type so we know which symbol is referenced var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); // Resolved symbol is alias @@ -24353,23 +26311,10 @@ var ts; * an expression if it is a type reference to a type with a value declaration. */ function checkTypeAnnotationAsExpression(node) { - switch (node.kind) { - case 141 /* PropertyDeclaration */: - checkTypeNodeAsExpression(node.type); - break; - case 138 /* Parameter */: - checkTypeNodeAsExpression(node.type); - break; - case 143 /* MethodDeclaration */: - checkTypeNodeAsExpression(node.type); - break; - case 145 /* GetAccessor */: - checkTypeNodeAsExpression(node.type); - break; - case 146 /* SetAccessor */: - checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node)); - break; - } + checkTypeNodeAsExpression(node.type); + } + function checkReturnTypeAnnotationAsExpression(node) { + checkTypeNodeAsExpression(node.type); } /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ function checkParameterTypeAnnotationsAsExpressions(node) { @@ -24390,53 +26335,48 @@ var ts; 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); + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } 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 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; - case 143 /* MethodDeclaration */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: checkParameterTypeAnnotationsAsExpressions(node); - // fall-through - case 146 /* SetAccessor */: - case 145 /* GetAccessor */: - case 141 /* PropertyDeclaration */: - case 138 /* Parameter */: + checkReturnTypeAnnotationAsExpression(node); + break; + case 143 /* PropertyDeclaration */: + case 140 /* Parameter */: checkTypeAnnotationAsExpression(node); break; } } - emitDecorate = true; - if (node.kind === 138 /* Parameter */) { - emitParam = true; - } ts.forEach(node.decorators, checkDecorator); } function checkFunctionDeclaration(node) { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); + checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkFunctionLikeDeclaration(node) { + function checkFunctionOrMethodDeclaration(node) { checkDecorators(node); checkSignatureDeclaration(node); var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } // 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 === 136 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 138 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -24447,7 +26387,13 @@ var ts; // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.forEach(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)) ? + declaration : undefined; }); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); @@ -24461,13 +26407,9 @@ var ts; } } checkSourceElement(node.body); - if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - var returnType = getTypeFromTypeNode(node.type); - var promisedType; - if (isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + if (!node.asteriskToken) { + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !node.type) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method @@ -24485,13 +26427,10 @@ var ts; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 192 /* Block */) { + if (node.kind === 196 /* Block */) { checkGrammarStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); - if (ts.isFunctionBlock(node) || node.kind === 219 /* ModuleBlock */) { - checkFunctionAndClassExpressionBodies(node); - } } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact @@ -24508,12 +26447,12 @@ var ts; if (!(identifier && identifier.text === name)) { return false; } - if (node.kind === 141 /* PropertyDeclaration */ || - node.kind === 140 /* PropertySignature */ || - node.kind === 143 /* MethodDeclaration */ || - node.kind === 142 /* MethodSignature */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */) { + if (node.kind === 143 /* PropertyDeclaration */ || + node.kind === 142 /* PropertySignature */ || + node.kind === 145 /* MethodDeclaration */ || + node.kind === 144 /* MethodSignature */ || + node.kind === 147 /* GetAccessor */ || + node.kind === 148 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -24522,7 +26461,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 138 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 140 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -24575,16 +26514,31 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 218 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 222 /* 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 === 248 /* SourceFile */ && ts.isExternalModule(parent)) { + if (parent.kind === 252 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (node.kind === 222 /* 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 === 252 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2097152 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } function checkVarDeclaredNamesNotShadowed(node) { // - ScriptBody : StatementList // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList @@ -24598,24 +26552,24 @@ var ts; // A non-initialized declaration is a no-op as the block declaration will resolve before the var // declaration. the problem is if the declaration has an initializer. this will act as a write to the // block declared value. this is fine for let, but not const. - // Only consider declarations with initializers, uninitialized let declarations will not + // Only consider declarations with initializers, uninitialized const declarations will not // step on a let/const variable. - // Do not consider let and const declarations, as duplicate block-scoped declarations + // Do not consider const and const declarations, as duplicate block-scoped declarations // are handled by the binder. - // We are only looking for let declarations that step on let\const declarations from a + // We are only looking for const declarations that step on let\const declarations from a // different scope. e.g.: // { // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration - // let x = 0; // symbol for this declaration will be 'symbol' + // const x = 0; // symbol for this declaration will be 'symbol' // } // skip block-scoped variables and parameters - if ((ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 3072 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { return; } // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 211 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 215 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -24624,25 +26578,25 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 193 /* VariableStatement */ && varDeclList.parent.parent + if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 3072 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 216 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 197 /* 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 === 192 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 219 /* ModuleBlock */ || - container.kind === 218 /* ModuleDeclaration */ || - container.kind === 248 /* SourceFile */); + (container.kind === 196 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 223 /* ModuleBlock */ || + container.kind === 222 /* ModuleDeclaration */ || + container.kind === 252 /* 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_14 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_14, name_14); + var name_15 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_15, name_15); } } } @@ -24650,7 +26604,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 !== 138 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 140 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -24661,7 +26615,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 === 138 /* Parameter */) { + if (referencedSymbol.valueDeclaration.kind === 140 /* Parameter */) { if (referencedSymbol.valueDeclaration === node) { error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); return; @@ -24687,24 +26641,31 @@ 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 === 136 /* ComputedPropertyName */) { + if (node.name.kind === 138 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } + if (node.kind === 167 /* BindingElement */) { + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 138 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { 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 === 138 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 140 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - if (node.initializer) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 204 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -24714,7 +26675,8 @@ var ts; var type = getTypeOfVariableOrParameterOrProperty(symbol); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer - if (node.initializer) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 204 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -24730,15 +26692,16 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } } - if (node.kind !== 141 /* PropertyDeclaration */ && node.kind !== 140 /* PropertySignature */) { + if (node.kind !== 143 /* PropertyDeclaration */ && node.kind !== 142 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + if (node.kind === 215 /* VariableDeclaration */ || node.kind === 167 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } function checkVariableDeclaration(node) { @@ -24756,7 +26719,7 @@ var ts; } function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (node.modifiers && node.parent.kind === 169 /* ObjectLiteralExpression */) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -24777,7 +26740,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 194 /* EmptyStatement */) { + if (node.thenStatement.kind === 198 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -24797,12 +26760,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 216 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 216 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -24822,14 +26785,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 === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 216 /* 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 === 164 /* ArrayLiteralExpression */ || varExpr.kind === 165 /* ObjectLiteralExpression */) { + if (varExpr.kind === 168 /* ArrayLiteralExpression */ || varExpr.kind === 169 /* 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. @@ -24838,7 +26801,7 @@ var ts; else { var leftType = checkExpression(varExpr); checkReferenceExpression(varExpr, /*invalidReferenceMessage*/ ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, - /*constantVariableMessage*/ ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant); + /*constantVariableMessage*/ ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); // 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 @@ -24858,7 +26821,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 === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 216 /* 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); @@ -24872,7 +26835,7 @@ 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 === 164 /* ArrayLiteralExpression */ || varExpr.kind === 165 /* ObjectLiteralExpression */) { + if (varExpr.kind === 168 /* ArrayLiteralExpression */ || varExpr.kind === 169 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */)) { @@ -24880,7 +26843,7 @@ var ts; } else { // run check only former check succeeded to avoid cascading errors - checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant); + checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); } } var rightType = checkExpression(node.expression); @@ -25051,7 +27014,7 @@ var ts; * This function does the following steps: * 1. Break up arrayOrStringType (possibly a union) into its string constituents and array constituents. * 2. Take the element types of the array constituents. - * 3. Return the union of the element types, and string if there was a string constitutent. + * 3. Return the union of the element types, and string if there was a string constituent. * * For example: * string -> string @@ -25068,7 +27031,13 @@ var ts; ts.Debug.assert(languageVersion < 2 /* ES6 */); // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. - var arrayType = removeTypesFromUnionType(arrayOrStringType, 258 /* StringLike */, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); + var arrayType = arrayOrStringType; + if (arrayOrStringType.flags & 16384 /* Union */) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258 /* StringLike */); })); + } + else if (arrayOrStringType.flags & 258 /* StringLike */) { + arrayType = emptyUnionType; + } var hasStringConstituent = arrayOrStringType !== arrayType; var reportedError = false; if (hasStringConstituent) { @@ -25110,8 +27079,8 @@ var ts; checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); // TODO: Check that target label is valid } - function isGetAccessorWithAnnotatatedSetAccessor(node) { - return !!(node.kind === 145 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 146 /* SetAccessor */))); + function isGetAccessorWithAnnotatedSetAccessor(node) { + return !!(node.kind === 147 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 148 /* SetAccessor */))); } function checkReturnStatement(node) { // Grammar checking @@ -25134,15 +27103,15 @@ var ts; // for generators. return; } - if (func.kind === 146 /* SetAccessor */) { + if (func.kind === 148 /* SetAccessor */) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === 144 /* Constructor */) { + else if (func.kind === 146 /* Constructor */) { if (!checkTypeAssignableTo(exprType, returnType, node.expression)) { 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) { + else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { if (ts.isAsyncFunctionLike(func)) { var promisedType = getPromisedType(returnType); var awaitedType = checkAwaitedType(exprType, node.expression, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -25163,7 +27132,7 @@ var ts; function checkWithStatement(node) { // Grammar checking for withStatement if (!checkGrammarStatementInAmbientContext(node)) { - if (node.parserContextFlags & 8 /* Await */) { + if (node.flags & 33554432 /* AwaitContext */) { grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -25176,9 +27145,10 @@ var ts; var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); + var expressionTypeIsStringLike = maybeTypeOfKind(expressionType, 258 /* StringLike */); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 242 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 246 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -25190,13 +27160,17 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 241 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 245 /* 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. var caseType = checkExpression(caseClause.expression); - if (!isTypeAssignableTo(expressionType, caseType)) { - // check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails + var expressionTypeIsAssignableToCaseType = + // Permit 'number[] | "foo"' to be asserted to 'string'. + (expressionTypeIsStringLike && maybeTypeOfKind(caseType, 258 /* StringLike */)) || + isTypeAssignableTo(expressionType, caseType); + if (!expressionTypeIsAssignableToCaseType) { + // 'expressionType is not assignable to caseType', try the reversed check and report errors if it fails checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); } } @@ -25211,7 +27185,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 207 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 211 /* 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; @@ -25285,7 +27259,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!(member.flags & 64 /* Static */) && ts.hasDynamicName(member)) { + if (!(member.flags & 32 /* Static */) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); @@ -25316,7 +27290,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 === 136 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { + if (prop.valueDeclaration.name.kind === 138 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { @@ -25350,7 +27324,7 @@ var ts; error(name, message, name.text); } } - // Check each type parameter and check that list has no duplicate type parameter declarations + /** Check each type parameter and check that type parameters have no duplicate type parameter declarations */ function checkTypeParameters(typeParameterDeclarations) { if (typeParameterDeclarations) { for (var i = 0, n = typeParameterDeclarations.length; i < n; i++) { @@ -25366,10 +27340,32 @@ var ts; } } } + /** Check that type parameter lists are identical across multiple declarations */ + function checkTypeParameterListsIdentical(node, symbol) { + if (symbol.declarations.length === 1) { + return; + } + var firstDecl; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 218 /* ClassDeclaration */ || declaration.kind === 219 /* InterfaceDeclaration */) { + if (!firstDecl) { + firstDecl = declaration; + } + else if (!areTypeParametersIdentical(firstDecl.typeParameters, node.typeParameters)) { + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, node.name.text); + } + } + } + } function checkClassExpression(node) { checkClassLikeDeclaration(node); + checkNodeDeferred(node); return getTypeOfSymbol(getSymbolOfNode(node)); } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + } function checkClassDeclaration(node) { if (!node.name && !(node.flags & 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); @@ -25384,6 +27380,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } checkTypeParameters(node.typeParameters); checkExportsOnMergedDeclarations(node); @@ -25391,13 +27388,14 @@ var ts; var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(node, symbol); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - emitExtends = emitExtends || !ts.isInAmbientContext(node); var baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { - var baseType = baseTypes[0]; + var baseType_1 = baseTypes[0]; var staticBaseType = getBaseConstructorTypeOfClass(type); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); if (baseTypeNode.typeArguments) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); @@ -25408,7 +27406,7 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (!(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 @@ -25416,11 +27414,11 @@ var ts; // 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; })) { + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } - checkKindsOfPropertyMemberOverrides(type, baseType); + checkKindsOfPropertyMemberOverrides(type, baseType_1); } } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); @@ -25450,6 +27448,18 @@ var ts; checkTypeForDuplicateIndexSignatures(node); } } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && declaration.flags & 8 /* Private */) { + var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, node.expression.text); + } + } + } + } function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags @@ -25484,7 +27494,7 @@ var ts; var baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { - // In order to resolve whether the inherited method was overriden in the base class or not, + // In order to resolve whether the inherited method was overridden in the base class or not, // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* // type declaration, derived and base resolve to the same symbol even in the case of generic classes. if (derived === base) { @@ -25494,7 +27504,7 @@ var ts; // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 128 /* Abstract */))) { - if (derivedClassDecl.kind === 186 /* ClassExpression */) { + if (derivedClassDecl.kind === 190 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -25505,11 +27515,11 @@ var ts; else { // derived overrides base. var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); - if ((baseDeclarationFlags & 16 /* Private */) || (derivedDeclarationFlags & 16 /* Private */)) { + if ((baseDeclarationFlags & 8 /* Private */) || (derivedDeclarationFlags & 8 /* Private */)) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 64 /* Static */) !== (derivedDeclarationFlags & 64 /* Static */)) { + if ((baseDeclarationFlags & 32 /* Static */) !== (derivedDeclarationFlags & 32 /* Static */)) { // value of 'static' is not the same for properties - not override, skip it continue; } @@ -25542,7 +27552,7 @@ var ts; } } function isAccessor(kind) { - return kind === 145 /* GetAccessor */ || kind === 146 /* SetAccessor */; + return kind === 147 /* GetAccessor */ || kind === 148 /* SetAccessor */; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -25612,13 +27622,9 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 215 /* 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); - } - } + checkTypeParameterListsIdentical(node, symbol); // Only check this symbol once + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 219 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -25651,7 +27657,7 @@ var ts; } function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 8192 /* EnumValuesComputed */)) { + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { var enumSymbol = getSymbolOfNode(node); var enumType = getDeclaredTypeOfSymbol(enumSymbol); var autoValue = 0; // set to undefined when enum member is non-constant @@ -25659,11 +27665,14 @@ var ts; var enumIsConst = ts.isConst(node); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.name.kind === 136 /* ComputedPropertyName */) { + if (isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } - else if (isNumericLiteralName(member.name.text)) { - error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + else { + var text = getTextOfPropertyName(member.name); + if (isNumericLiteralName(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } } var previousEnumMemberIsNonConstant = autoValue === undefined; var initializer = member.initializer; @@ -25683,10 +27692,11 @@ var ts; error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); } if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue++; + getNodeLinks(member).enumMemberValue = autoValue; + autoValue++; } } - nodeLinks.flags |= 8192 /* EnumValuesComputed */; + nodeLinks.flags |= 16384 /* EnumValuesComputed */; } function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { // Controls if error should be reported after evaluation of constant value is completed @@ -25718,7 +27728,7 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; @@ -25729,7 +27739,7 @@ var ts; case 50 /* TildeToken */: return ~value_1; } return undefined; - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -25754,15 +27764,15 @@ var ts; return undefined; case 8 /* NumericLiteral */: return +e.text; - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return evalConstant(e.expression); case 69 /* Identifier */: - case 167 /* ElementAccessExpression */: - case 166 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: + case 170 /* PropertyAccessExpression */: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; - var propertyName; + var propertyName = void 0; if (e.kind === 69 /* Identifier */) { // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. // instead pick current enum type and later try to fetch member from the type @@ -25770,8 +27780,8 @@ var ts; propertyName = e.text; } else { - var expression; - if (e.kind === 167 /* ElementAccessExpression */) { + var expression = void 0; + if (e.kind === 171 /* ElementAccessExpression */) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9 /* StringLiteral */) { return undefined; @@ -25789,7 +27799,7 @@ var ts; if (current.kind === 69 /* Identifier */) { break; } - else if (current.kind === 166 /* PropertyAccessExpression */) { + else if (current.kind === 170 /* PropertyAccessExpression */) { current = current.expression; } else { @@ -25834,6 +27844,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); @@ -25857,10 +27868,10 @@ var ts; } }); } - var seenEnumMissingInitialInitializer = false; + var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 217 /* EnumDeclaration */) { + if (declaration.kind !== 221 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -25869,11 +27880,11 @@ var ts; } var firstEnumMember = enumDeclaration.members[0]; if (!firstEnumMember.initializer) { - if (seenEnumMissingInitialInitializer) { + if (seenEnumMissingInitialInitializer_1) { error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); } else { - seenEnumMissingInitialInitializer = true; + seenEnumMissingInitialInitializer_1 = true; } } }); @@ -25883,8 +27894,8 @@ var ts; var declarations = symbol.declarations; for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; - if ((declaration.kind === 214 /* ClassDeclaration */ || - (declaration.kind === 213 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + if ((declaration.kind === 218 /* ClassDeclaration */ || + (declaration.kind === 217 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -25907,7 +27918,12 @@ var ts; function checkModuleDeclaration(node) { if (produceDiagnostics) { // Grammar checking - var isAmbientExternalModule = node.name.kind === 9 /* StringLiteral */; + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = ts.isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); var contextErrorMessage = isAmbientExternalModule ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; @@ -25916,18 +27932,19 @@ var ts; return; } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!ts.isInAmbientContext(node) && node.name.kind === 9 /* StringLiteral */) { + if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ && symbol.declarations.length > 1 - && !ts.isInAmbientContext(node) + && !inAmbientContext && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -25940,30 +27957,120 @@ 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, 214 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 218 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; } } - // Checks for ambient external modules. if (isAmbientExternalModule) { - if (!isGlobalSourceFile(node.parent)) { - error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + if (ts.isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Merged */); + if (checkBody) { + // body of ambient external module is always a module block + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } } - if (ts.isExternalModuleNameRelative(node.name.text)) { - error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(node.name.text)) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } } } } checkSourceElement(node.body); } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 197 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 231 /* ExportAssignment */: + case 232 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 225 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind !== 9 /* StringLiteral */) { + error(node.name, ts.Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + break; + } + // fallthrough + case 226 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 167 /* BindingElement */: + case 215 /* VariableDeclaration */: + var name_16 = node.name; + if (ts.isBindingPattern(name_16)) { + for (var _b = 0, _c = name_16.elements; _b < _c.length; _b++) { + var el = _c[_b]; + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // fallthrough + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 217 /* FunctionDeclaration */: + case 219 /* InterfaceDeclaration */: + case 222 /* ModuleDeclaration */: + case 220 /* TypeAliasDeclaration */: + var symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Merged */); + if (!reportError) { + if (isGlobalAugmentation) { + // global symbol should not have parent since it is not explicitly exported + reportError = symbol.parent !== undefined; + } + else { + // symbol should not originate in augmentation + reportError = ts.isExternalModuleAugmentation(symbol.parent.valueDeclaration); + } + } + if (reportError) { + error(node, ts.Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + } + } + break; + } + } function getFirstIdentifier(node) { while (true) { - if (node.kind === 135 /* QualifiedName */) { + if (node.kind === 137 /* QualifiedName */) { node = node.left; } - else if (node.kind === 166 /* PropertyAccessExpression */) { + else if (node.kind === 170 /* PropertyAccessExpression */) { node = node.expression; } else { @@ -25979,20 +28086,24 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 219 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; - if (node.parent.kind !== 248 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 228 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 223 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 252 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 232 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - // TypeScript 1.0 spec (April 2013): 12.1.6 - // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference - // other external modules only through top - level external module names. - // Relative external module names are not permitted. - error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); - return false; + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } } return true; } @@ -26004,7 +28115,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 === 230 /* ExportSpecifier */ ? + var message = node.kind === 234 /* 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)); @@ -26014,6 +28125,7 @@ var ts; function checkImportBinding(node) { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); } function checkImportDeclaration(node) { @@ -26021,7 +28133,7 @@ var ts; // 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 & 1022 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -26031,7 +28143,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 228 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -26049,7 +28161,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -26068,7 +28180,7 @@ var ts; } } else { - if (modulekind === 5 /* ES6 */ && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES6 && !ts.isInAmbientContext(node)) { // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } @@ -26080,7 +28192,7 @@ var ts; // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -26088,29 +28200,38 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 219 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; - if (node.parent.kind !== 248 /* SourceFile */ && !inAmbientExternalModule) { + var inAmbientExternalModule = node.parent.kind === 223 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 252 /* SourceFile */ && !inAmbientExternalModule) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } else { // export * from "foo" var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && moduleSymbol.exports["export="]) { + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } } } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 248 /* SourceFile */ && node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 218 /* ModuleDeclaration */) { + if (node.parent.kind !== 252 /* SourceFile */ && node.parent.kind !== 223 /* ModuleBlock */ && node.parent.kind !== 222 /* ModuleDeclaration */) { return grammarErrorOnFirstToken(node, errorMessage); } } function checkExportSpecifier(node) { checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { - markExportAsReferenced(node); + var exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_re_export_name_that_is_not_defined_in_the_module); + } + else { + markExportAsReferenced(node); + } } } function checkExportAssignment(node) { @@ -26118,13 +28239,13 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 248 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 218 /* ModuleDeclaration */ && container.name.kind === 69 /* Identifier */) { + var container = node.parent.kind === 252 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 222 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 959 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69 /* Identifier */) { @@ -26135,25 +28256,16 @@ var ts; } checkExternalModuleExports(container); if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === 5 /* ES6 */) { + if (modulekind === ts.ModuleKind.ES6) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_export_default_or_another_module_format_instead); } - else if (modulekind === 4 /* System */) { + else if (modulekind === ts.ModuleKind.System) { // system modules does not support export assignment grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); } } } - function getModuleStatements(node) { - if (node.kind === 248 /* SourceFile */) { - return node.statements; - } - if (node.kind === 218 /* ModuleDeclaration */ && node.body.kind === 219 /* ModuleBlock */) { - return node.body.statements; - } - return emptyArray; - } function hasExportedMembers(moduleSymbol) { for (var id in moduleSymbol.exports) { if (id !== "export=") { @@ -26169,14 +28281,41 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports["export="]; if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + var exports = getExportsOfModule(moduleSymbol); + for (var id in exports) { + if (id === "__export") { + continue; + } + var _a = exports[id], declarations = _a.declarations, flags = _a.flags; + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1536 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + continue; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + continue; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); + } + } + } } 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 isNotOverload(declaration) { + return declaration.kind !== 217 /* FunctionDeclaration */ || !!declaration.body; } } function checkSourceElement(node) { @@ -26185,229 +28324,156 @@ var ts; } var kind = node.kind; if (cancellationToken) { - // Only bother checking on a few construct kinds. We don't want to be excessivly + // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 222 /* ModuleDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 217 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 137 /* TypeParameter */: + case 139 /* TypeParameter */: return checkTypeParameter(node); - case 138 /* Parameter */: + case 140 /* Parameter */: return checkParameter(node); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return checkPropertyDeclaration(node); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: return checkSignatureDeclaration(node); - case 149 /* IndexSignature */: + case 151 /* IndexSignature */: return checkSignatureDeclaration(node); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return checkMethodDeclaration(node); - case 144 /* Constructor */: + case 146 /* Constructor */: return checkConstructorDeclaration(node); - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: return checkAccessorDeclaration(node); - case 151 /* TypeReference */: + case 153 /* TypeReference */: return checkTypeReferenceNode(node); - case 150 /* TypePredicate */: + case 152 /* TypePredicate */: return checkTypePredicate(node); - case 154 /* TypeQuery */: + case 156 /* TypeQuery */: return checkTypeQuery(node); - case 155 /* TypeLiteral */: + case 157 /* TypeLiteral */: return checkTypeLiteral(node); - case 156 /* ArrayType */: + case 158 /* ArrayType */: return checkArrayType(node); - case 157 /* TupleType */: + case 159 /* TupleType */: return checkTupleType(node); - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 160 /* UnionType */: + case 161 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 160 /* ParenthesizedType */: + case 162 /* ParenthesizedType */: return checkSourceElement(node.type); - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 196 /* Block */: + case 223 /* ModuleBlock */: return checkBlock(node); - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return checkVariableStatement(node); - case 195 /* ExpressionStatement */: + case 199 /* ExpressionStatement */: return checkExpressionStatement(node); - case 196 /* IfStatement */: + case 200 /* IfStatement */: return checkIfStatement(node); - case 197 /* DoStatement */: + case 201 /* DoStatement */: return checkDoStatement(node); - case 198 /* WhileStatement */: + case 202 /* WhileStatement */: return checkWhileStatement(node); - case 199 /* ForStatement */: + case 203 /* ForStatement */: return checkForStatement(node); - case 200 /* ForInStatement */: + case 204 /* ForInStatement */: return checkForInStatement(node); - case 201 /* ForOfStatement */: + case 205 /* ForOfStatement */: return checkForOfStatement(node); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 206 /* ContinueStatement */: + case 207 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 204 /* ReturnStatement */: + case 208 /* ReturnStatement */: return checkReturnStatement(node); - case 205 /* WithStatement */: + case 209 /* WithStatement */: return checkWithStatement(node); - case 206 /* SwitchStatement */: + case 210 /* SwitchStatement */: return checkSwitchStatement(node); - case 207 /* LabeledStatement */: + case 211 /* LabeledStatement */: return checkLabeledStatement(node); - case 208 /* ThrowStatement */: + case 212 /* ThrowStatement */: return checkThrowStatement(node); - case 209 /* TryStatement */: + case 213 /* TryStatement */: return checkTryStatement(node); - case 211 /* VariableDeclaration */: + case 215 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 163 /* BindingElement */: + case 167 /* BindingElement */: return checkBindingElement(node); - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: return checkClassDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 216 /* TypeAliasDeclaration */: + case 220 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: return checkImportDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: return checkExportDeclaration(node); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return checkExportAssignment(node); - case 194 /* EmptyStatement */: + case 198 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 210 /* DebuggerStatement */: + case 214 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 231 /* MissingDeclaration */: + case 235 /* MissingDeclaration */: return checkMissingDeclaration(node); } } // Function and class expression bodies are checked after all statements in the enclosing body. This is // to ensure constructs like the following are permitted: - // let foo = function () { - // let s = foo(); + // const foo = function () { + // const s = foo(); // return "hello"; // } // Here, performing a full type check of the body of the function expression whilst in the process of // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. - function checkFunctionAndClassExpressionBodies(node) { - switch (node.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - checkFunctionExpressionOrObjectLiteralMethodBody(node); - break; - case 186 /* ClassExpression */: - ts.forEach(node.members, checkSourceElement); - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - if (ts.isObjectLiteralMethod(node)) { - checkFunctionExpressionOrObjectLiteralMethodBody(node); - } - break; - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); - break; - case 205 /* WithStatement */: - checkFunctionAndClassExpressionBodies(node.expression); - break; - case 139 /* Decorator */: - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 163 /* BindingElement */: - case 164 /* ArrayLiteralExpression */: - case 165 /* ObjectLiteralExpression */: - case 245 /* PropertyAssignment */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 170 /* TaggedTemplateExpression */: - case 183 /* TemplateExpression */: - case 190 /* TemplateSpan */: - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: - case 172 /* ParenthesizedExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 178 /* AwaitExpression */: - case 175 /* DeleteExpression */: - case 179 /* PrefixUnaryExpression */: - case 180 /* PostfixUnaryExpression */: - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 185 /* SpreadElementExpression */: - case 184 /* YieldExpression */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 193 /* VariableStatement */: - case 195 /* ExpressionStatement */: - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: - case 204 /* ReturnStatement */: - case 206 /* SwitchStatement */: - case 220 /* CaseBlock */: - case 241 /* CaseClause */: - case 242 /* DefaultClause */: - case 207 /* LabeledStatement */: - case 208 /* ThrowStatement */: - case 209 /* TryStatement */: - case 244 /* CatchClause */: - case 211 /* VariableDeclaration */: - case 212 /* VariableDeclarationList */: - case 214 /* ClassDeclaration */: - case 243 /* HeritageClause */: - case 188 /* ExpressionWithTypeArguments */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 227 /* ExportAssignment */: - case 248 /* SourceFile */: - case 240 /* JsxExpression */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - case 235 /* JsxOpeningElement */: - ts.forEachChild(node, checkFunctionAndClassExpressionBodies); - break; + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + checkAccessorDeferred(node); + break; + case 190 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + } } } function checkSourceFile(node) { @@ -26421,39 +28487,27 @@ var ts; 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; + if (compilerOptions.skipDefaultLibCheck) { + // If the user specified '--noLib' and a file has a '/// ', + // then we should treat that file as a default lib. + if (node.hasNoDefaultLib) { + return; + } } // Grammar checking checkGrammarSourceFile(node); - emitExtends = false; - emitDecorate = false; - emitParam = false; potentialThisCollisions.length = 0; + deferredNodes = []; ts.forEach(node.statements, checkSourceElement); - checkFunctionAndClassExpressionBodies(node); - if (ts.isExternalModule(node)) { + checkDeferredNodes(); + deferredNodes = undefined; + if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } if (potentialThisCollisions.length) { ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); potentialThisCollisions.length = 0; } - if (emitExtends) { - links.flags |= 8 /* EmitExtends */; - } - if (emitDecorate) { - links.flags |= 16 /* EmitDecorate */; - } - if (emitParam) { - links.flags |= 32 /* EmitParam */; - } - if (emitAwaiter) { - links.flags |= 64 /* EmitAwaiter */; - } - if (emitGenerator || (emitAwaiter && languageVersion < 2 /* ES6 */)) { - links.flags |= 128 /* EmitGenerator */; - } links.flags |= 1 /* TypeChecked */; } } @@ -26491,7 +28545,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 205 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 209 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -26514,34 +28568,34 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 248 /* SourceFile */: - if (!ts.isExternalModule(location)) { + case 252 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } // fall through; this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. - if (!(memberFlags & 64 /* Static */)) { + if (!(memberFlags & 32 /* Static */)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; - case 173 /* FunctionExpression */: + case 177 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -26590,37 +28644,48 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 137 /* TypeParameter */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: + case 139 /* TypeParameter */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 221 /* 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 === 135 /* QualifiedName */) { + while (node.parent && node.parent.kind === 137 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 151 /* TypeReference */; + return node.parent && node.parent.kind === 153 /* TypeReference */; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 166 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 170 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 188 /* ExpressionWithTypeArguments */; + return node.parent && node.parent.kind === 192 /* ExpressionWithTypeArguments */; + } + function isNodeWithinClass(node, classDeclaration) { + while (true) { + node = ts.getContainingClass(node); + if (!node) { + return false; + } + if (node === classDeclaration) { + return true; + } + } } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 135 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 137 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 221 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 225 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 227 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 231 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -26632,11 +28697,23 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 227 /* ExportAssignment */) { + if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 170 /* PropertyAccessExpression */) { + var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + return getSymbolOfNode(entityName.parent.parent); + default: + } + } + if (entityName.parent.kind === 231 /* ExportAssignment */) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 166 /* PropertyAccessExpression */) { + if (entityName.kind !== 170 /* PropertyAccessExpression */) { if (isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); @@ -26648,7 +28725,7 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 188 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 192 /* ExpressionWithTypeArguments */) { meaning = 793056 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -26661,10 +28738,10 @@ var ts; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if ((entityName.parent.kind === 235 /* JsxOpeningElement */) || - (entityName.parent.kind === 234 /* JsxSelfClosingElement */) || - (entityName.parent.kind === 237 /* JsxClosingElement */)) { - return getJsxElementTagSymbol(entityName.parent); + else if ((entityName.parent.kind === 239 /* JsxOpeningElement */) || + (entityName.parent.kind === 238 /* JsxSelfClosingElement */) || + (entityName.parent.kind === 241 /* JsxClosingElement */)) { + return getJsxTagSymbol(entityName.parent); } else if (ts.isExpression(entityName)) { if (ts.nodeIsMissing(entityName)) { @@ -26677,14 +28754,14 @@ var ts; var meaning = 107455 /* Value */ | 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 166 /* PropertyAccessExpression */) { + else if (entityName.kind === 170 /* PropertyAccessExpression */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 135 /* QualifiedName */) { + else if (entityName.kind === 137 /* QualifiedName */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -26693,16 +28770,16 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = entityName.parent.kind === 153 /* 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 */; return resolveEntityName(entityName, meaning); } - else if (entityName.parent.kind === 238 /* JsxAttribute */) { + else if (entityName.parent.kind === 242 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 150 /* TypePredicate */) { + if (entityName.parent.kind === 152 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? @@ -26719,12 +28796,12 @@ var ts; } if (node.kind === 69 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 227 /* ExportAssignment */ + return node.parent.kind === 231 /* ExportAssignment */ ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } - else if (node.parent.kind === 163 /* BindingElement */ && - node.parent.parent.kind === 161 /* ObjectBindingPattern */ && + else if (node.parent.kind === 167 /* BindingElement */ && + node.parent.parent.kind === 165 /* ObjectBindingPattern */ && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -26735,17 +28812,19 @@ var ts; } switch (node.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: - case 135 /* QualifiedName */: + case 170 /* PropertyAccessExpression */: + case 137 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; + case 163 /* ThisType */: + return getTypeFromTypeNode(node).symbol; case 121 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 144 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 146 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -26753,14 +28832,14 @@ var ts; // External module name in an import declaration if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 222 /* ImportDeclaration */ || node.parent.kind === 228 /* ExportDeclaration */) && + ((node.parent.kind === 226 /* ImportDeclaration */ || node.parent.kind === 232 /* ExportDeclaration */) && node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } // Fall through case 8 /* NumericLiteral */: // index access - if (node.parent.kind === 167 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + if (node.parent.kind === 171 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -26777,11 +28856,17 @@ 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 === 246 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 107455 /* Value */); + if (location && location.kind === 250 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 107455 /* Value */ | 8388608 /* Alias */); } return undefined; } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further @@ -26838,7 +28923,7 @@ var ts; */ function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 64 /* Static */ + return node.flags & 32 /* Static */ ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -26858,15 +28943,15 @@ var ts; } function getRootSymbols(symbol) { if (symbol.flags & 268435456 /* SyntheticProperty */) { - var symbols = []; - var name_15 = symbol.name; + var symbols_3 = []; + var name_17 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_15); + var symbol = getPropertyOfType(t, name_17); if (symbol) { - symbols.push(symbol); + symbols_3.push(symbol); } }); - return symbols; + return symbols_3; } else if (symbol.flags & 67108864 /* Transient */) { var target = getSymbolLinks(symbol).target; @@ -26880,6 +28965,30 @@ var ts; function isArgumentsLocalBinding(node) { return getReferencedValueSymbol(node) === argumentsSymbol; } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol) { + // module not found - be conservative + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455 /* Value */) + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455 /* Value */); + } + } // 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) { @@ -26897,11 +29006,11 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 248 /* SourceFile */) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 252 /* SourceFile */) { return parentSymbol.valueDeclaration; } for (var n = node.parent; n; n = n.parent) { - if ((n.kind === 218 /* ModuleDeclaration */ || n.kind === 217 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { + if ((n.kind === 222 /* ModuleDeclaration */ || n.kind === 221 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { return n; } } @@ -26914,58 +29023,77 @@ var ts; var symbol = getReferencedValueSymbol(node); return symbol && symbol.flags & 8388608 /* Alias */ ? getDeclarationOfAliasSymbol(symbol) : undefined; } - function isStatementWithLocals(node) { - switch (node.kind) { - case 192 /* Block */: - case 220 /* CaseBlock */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - return true; - } - return false; - } - function isNestedRedeclarationSymbol(symbol) { + function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418 /* BlockScoped */) { var links = getSymbolLinks(symbol); - if (links.isNestedRedeclaration === undefined) { + if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - links.isNestedRedeclaration = isStatementWithLocals(container) && - !!resolveName(container.parent, symbol.name, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.name, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { + // redeclaration - always should be renamed + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 196 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } } - return links.isNestedRedeclaration; + return links.isDeclarationWithCollidingName; } return false; } // When resolved as an expression identifier, if the given node references a nested block scoped entity with - // a name that hides an existing name, return the declaration of that entity. Otherwise, return undefined. - function getReferencedNestedRedeclaration(node) { + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(node) { var symbol = getReferencedValueSymbol(node); - return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + return symbol && isSymbolOfDeclarationWithCollidingName(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)); + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(node) { + return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); } function isValueAliasDeclaration(node) { switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 225 /* ImportEqualsDeclaration */: + case 227 /* ImportClause */: + case 228 /* NamespaceImport */: + case 230 /* ImportSpecifier */: + case 234 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node)); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return node.expression && node.expression.kind === 69 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; } return false; } function isTopLevelValueImportEqualsWithEntityName(node) { - if (node.parent.kind !== 248 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node.parent.kind !== 252 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -26977,7 +29105,7 @@ var ts; if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } - // const enums and modules that contain only const enums are not considered values from the emit perespective + // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true return target !== unknownSymbol && target && @@ -27027,7 +29155,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 247 /* EnumMember */) { + if (node.kind === 251 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -27062,22 +29190,22 @@ var ts; else if (type.flags & 1 /* Any */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (allConstituentTypesHaveKind(type, 16 /* Void */)) { + else if (isTypeOfKind(type, 16 /* Void */)) { return ts.TypeReferenceSerializationKind.VoidType; } - else if (allConstituentTypesHaveKind(type, 8 /* Boolean */)) { + else if (isTypeOfKind(type, 8 /* Boolean */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (allConstituentTypesHaveKind(type, 132 /* NumberLike */)) { + else if (isTypeOfKind(type, 132 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (allConstituentTypesHaveKind(type, 258 /* StringLike */)) { + else if (isTypeOfKind(type, 258 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } - else if (allConstituentTypesHaveKind(type, 8192 /* Tuple */)) { + else if (isTypeOfKind(type, 8192 /* Tuple */)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (allConstituentTypesHaveKind(type, 16777216 /* ESSymbol */)) { + else if (isTypeOfKind(type, 16777216 /* ESSymbol */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -27119,23 +29247,12 @@ var ts; var symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } - function instantiateSingleCallFunctionType(functionType, typeArguments) { - if (functionType === unknownType) { - return unknownType; - } - var signature = getSingleCallSignature(functionType); - if (!signature) { - return unknownType; - } - var instantiatedSignature = getSignatureInstantiation(signature, typeArguments); - return getOrCreateTypeFromSignature(instantiatedSignature); - } function createResolver() { return { getReferencedExportContainer: getReferencedExportContainer, getReferencedImportDeclaration: getReferencedImportDeclaration, - getReferencedNestedRedeclaration: getReferencedNestedRedeclaration, - isNestedRedeclaration: isNestedRedeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, isValueAliasDeclaration: isValueAliasDeclaration, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: isReferencedAliasDeclaration, @@ -27153,25 +29270,50 @@ var ts; getReferencedValueDeclaration: getReferencedValueDeclaration, getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, isOptionalParameter: isOptionalParameter, - isArgumentsLocalBinding: isArgumentsLocalBinding + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration }; } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 252 /* SourceFile */); + } function initializeTypeChecker() { // Bind all source files and propagate errors ts.forEach(host.getSourceFiles(), function (file) { ts.bindSourceFile(file, compilerOptions); }); + var augmentations; // Initialize global symbol table ts.forEach(host.getSourceFiles(), function (file) { - if (!ts.isExternalModule(file)) { + if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } }); - // Initialize special symbols + if (augmentations) { + // merge module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _i = 0, augmentations_1 = augmentations; _i < augmentations_1.length; _i++) { + var list = augmentations_1[_i]; + for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { + var augmentation = list_2[_a]; + mergeModuleAugmentation(augmentation); + } + } + } + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; - globals[undefinedSymbol.name] = undefinedSymbol; // Initialize special types globalArrayType = getGlobalType("Array", /*arity*/ 1); globalObjectType = getGlobalType("Object"); @@ -27215,6 +29357,9 @@ var ts; globalIterableIteratorType = emptyGenericType; } anyArrayType = createArrayType(anyType); + var symbol = getGlobalSymbol("ReadonlyArray", 793056 /* Type */, /*diagnostic*/ undefined); + globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; } function createInstantiatedPromiseLikeType() { var promiseLikeType = getGlobalPromiseLikeType(); @@ -27240,9 +29385,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + if (node.kind === 145 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } } - else if (node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */) { + else if (node.kind === 147 /* GetAccessor */ || node.kind === 148 /* 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); @@ -27252,38 +29402,38 @@ var ts; } function checkGrammarModifiers(node) { switch (node.kind) { - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 144 /* Constructor */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 149 /* IndexSignature */: - case 218 /* ModuleDeclaration */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: - case 227 /* ExportAssignment */: - case 138 /* Parameter */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 146 /* Constructor */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 151 /* IndexSignature */: + case 222 /* ModuleDeclaration */: + case 226 /* ImportDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 232 /* ExportDeclaration */: + case 231 /* ExportAssignment */: + case 140 /* Parameter */: break; - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118 /* AsyncKeyword */) && - node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + node.parent.kind !== 223 /* ModuleBlock */ && node.parent.kind !== 252 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 193 /* VariableStatement */: - case 216 /* TypeAliasDeclaration */: - if (node.modifiers && node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 197 /* VariableStatement */: + case 220 /* TypeAliasDeclaration */: + if (node.modifiers && node.parent.kind !== 223 /* ModuleBlock */ && node.parent.kind !== 252 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74 /* ConstKeyword */) && - node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + node.parent.kind !== 223 /* ModuleBlock */ && node.parent.kind !== 252 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; @@ -27293,37 +29443,48 @@ var ts; if (!node.modifiers) { return; } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync; + var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; + if (modifier.kind !== 127 /* ReadonlyKeyword */) { + if (node.kind === 142 /* PropertySignature */ || node.kind === 144 /* MethodSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 151 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } switch (modifier.kind) { + case 74 /* ConstKeyword */: + if (node.kind !== 221 /* EnumDeclaration */ && node.parent.kind === 218 /* ClassDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74 /* ConstKeyword */)); + } + break; case 112 /* PublicKeyword */: case 111 /* ProtectedKeyword */: case 110 /* PrivateKeyword */: - var text = void 0; - if (modifier.kind === 112 /* PublicKeyword */) { - text = "public"; - } - else if (modifier.kind === 111 /* ProtectedKeyword */) { - text = "protected"; + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (modifier.kind === 111 /* ProtectedKeyword */) { lastProtected = modifier; } - else { - text = "private"; + else if (modifier.kind === 110 /* PrivateKeyword */) { lastPrivate = modifier; } - if (flags & 56 /* AccessibilityModifier */) { + if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & 64 /* Static */) { + else if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); + else if (node.parent.kind === 223 /* ModuleBlock */ || node.parent.kind === 252 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { if (modifier.kind === 110 /* PrivateKeyword */) { @@ -27336,29 +29497,42 @@ var ts; flags |= ts.modifierToFlag(modifier.kind); break; case 113 /* StaticKeyword */: - if (flags & 64 /* Static */) { + if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); + else if (node.parent.kind === 223 /* ModuleBlock */ || node.parent.kind === 252 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 140 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= 64 /* Static */; + flags |= 32 /* Static */; lastStatic = modifier; break; + case 127 /* ReadonlyKeyword */: + if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 143 /* PropertyDeclaration */ && node.kind !== 142 /* PropertySignature */ && node.kind !== 151 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64 /* Readonly */; + lastReadonly = modifier; + break; case 82 /* ExportKeyword */: - if (flags & 2 /* Export */) { + if (flags & 1 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & 4 /* Ambient */) { + else if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } else if (flags & 128 /* Abstract */) { @@ -27367,48 +29541,51 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 218 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 140 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= 2 /* Export */; + flags |= 1 /* Export */; break; case 122 /* DeclareKeyword */: - if (flags & 4 /* Ambient */) { + if (flags & 2 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 218 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 140 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219 /* ModuleBlock */) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 223 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= 4 /* Ambient */; + flags |= 2 /* Ambient */; lastDeclare = modifier; break; case 115 /* AbstractKeyword */: if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 214 /* ClassDeclaration */) { - if (node.kind !== 143 /* MethodDeclaration */) { - return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); + if (node.kind !== 218 /* ClassDeclaration */) { + if (node.kind !== 145 /* MethodDeclaration */ && + node.kind !== 143 /* PropertyDeclaration */ && + node.kind !== 147 /* GetAccessor */ && + node.kind !== 148 /* SetAccessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 214 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { + if (!(node.parent.kind === 218 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & 64 /* Static */) { + if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 16 /* Private */) { + if (flags & 8 /* Private */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } @@ -27418,10 +29595,10 @@ var ts; if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 4 /* Ambient */ || ts.isInAmbientContext(node.parent)) { + else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 140 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -27429,28 +29606,25 @@ var ts; break; } } - if (node.kind === 144 /* Constructor */) { - if (flags & 64 /* Static */) { + if (node.kind === 146 /* Constructor */) { + if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & 32 /* Protected */) { - return grammarErrorOnNode(lastProtected, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); - } - else if (flags & 16 /* Private */) { - return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); - } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } return; } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && flags & 4 /* Ambient */) { + else if ((node.kind === 226 /* ImportDeclaration */ || node.kind === 225 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 138 /* Parameter */ && (flags & 56 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 140 /* Parameter */ && (flags & 28 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } if (flags & 256 /* Async */) { @@ -27462,10 +29636,10 @@ var ts; return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher); } switch (node.kind) { - case 143 /* MethodDeclaration */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: if (!node.asteriskToken) { return false; } @@ -27531,7 +29705,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 174 /* ArrowFunction */) { + if (node.kind === 178 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -27554,7 +29728,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 1022 /* Modifier */) { + if (parameter.flags & 959 /* Modifier */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -27566,21 +29740,16 @@ var ts; if (!parameter.type) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } - if (parameter.type.kind !== 130 /* StringKeyword */ && parameter.type.kind !== 128 /* NumberKeyword */) { + if (parameter.type.kind !== 131 /* StringKeyword */ && parameter.type.kind !== 129 /* NumberKeyword */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } } - function checkGrammarForIndexSignatureModifier(node) { - if (node.flags & 1022 /* Modifier */) { - grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); - } - } function checkGrammarIndexSignature(node) { // Prevent cascading error by short-circuit - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node) || checkGrammarForIndexSignatureModifier(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); } function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { if (typeArguments && typeArguments.length === 0) { @@ -27599,7 +29768,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { var arg = args_1[_i]; - if (arg.kind === 187 /* OmittedExpression */) { + if (arg.kind === 191 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -27673,19 +29842,19 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 136 /* ComputedPropertyName */) { + if (node.kind !== 138 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 181 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { + if (computedPropertyName.expression.kind === 185 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */ || - node.kind === 143 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 217 /* FunctionDeclaration */ || + node.kind === 177 /* FunctionExpression */ || + node.kind === 145 /* MethodDeclaration */); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -27706,23 +29875,28 @@ var ts; var seen = {}; var Property = 1; var GetAccessor = 2; - var SetAccesor = 4; - var GetOrSetAccessor = GetAccessor | SetAccesor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - var name_16 = prop.name; - if (prop.kind === 187 /* OmittedExpression */ || - name_16.kind === 136 /* ComputedPropertyName */) { + var SetAccessor = 4; + var GetOrSetAccessor = GetAccessor | SetAccessor; + var _loop_1 = function(prop) { + var name_18 = prop.name; + if (prop.kind === 191 /* OmittedExpression */ || + name_18.kind === 138 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name_16); - continue; + checkGrammarComputedPropertyName(name_18); + return "continue"; } - if (prop.kind === 246 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 250 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; } - // ECMA-262 11.1.5 Object Initialiser + // Modifiers are never allowed on properties except for 'async' on a method declaration + ts.forEach(prop.modifiers, function (mod) { + if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 145 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + }); + // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and // IsDataDescriptor(propId.descriptor) is true. @@ -27731,65 +29905,71 @@ 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 === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */) { - // Grammar checking for computedPropertName and shorthandPropertyAssignment + if (prop.kind === 249 /* PropertyAssignment */ || prop.kind === 250 /* ShorthandPropertyAssignment */) { + // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_16.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name_16); + if (name_18.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name_18); } currentKind = Property; } - else if (prop.kind === 143 /* MethodDeclaration */) { + else if (prop.kind === 145 /* MethodDeclaration */) { currentKind = Property; } - else if (prop.kind === 145 /* GetAccessor */) { + else if (prop.kind === 147 /* GetAccessor */) { currentKind = GetAccessor; } - else if (prop.kind === 146 /* SetAccessor */) { - currentKind = SetAccesor; + else if (prop.kind === 148 /* SetAccessor */) { + currentKind = SetAccessor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_16.text)) { - seen[name_16.text] = currentKind; + if (!ts.hasProperty(seen, name_18.text)) { + seen[name_18.text] = currentKind; } else { - var existingKind = seen[name_16.text]; + var existingKind = seen[name_18.text]; if (currentKind === Property && existingKind === Property) { - continue; + return "continue"; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_16.text] = currentKind | existingKind; + seen[name_18.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return { value: grammarErrorOnNode(name_18, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return { value: grammarErrorOnNode(name_18, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } + }; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_1(prop); + if (typeof state_2 === "object") return state_2.value; + if (state_2 === "continue") continue; } } function checkGrammarJsxElement(node) { var seen = {}; for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 239 /* JsxSpreadAttribute */) { + if (attr.kind === 243 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; - var name_17 = jsxAttr.name; - if (!ts.hasProperty(seen, name_17.text)) { - seen[name_17.text] = true; + var name_19 = jsxAttr.name; + if (!ts.hasProperty(seen, name_19.text)) { + seen[name_19.text] = true; } else { - return grammarErrorOnNode(name_17, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_19, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 240 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 244 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -27798,24 +29978,35 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 212 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 216 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { - if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 204 /* 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]; + var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 204 /* 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 === 200 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 204 /* 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); @@ -27832,16 +30023,16 @@ var ts; else if (ts.isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined) { + else if (accessor.body === undefined && !(accessor.flags & 128 /* Abstract */)) { return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } - else if (kind === 145 /* GetAccessor */ && accessor.parameters.length) { + else if (kind === 147 /* GetAccessor */ && accessor.parameters.length) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); } - else if (kind === 146 /* SetAccessor */) { + else if (kind === 148 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -27853,7 +30044,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); } - else if (parameter.flags & 1022 /* Modifier */) { + else if (parameter.flags & 959 /* Modifier */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } else if (parameter.questionToken) { @@ -27866,7 +30057,7 @@ var ts; } } function checkGrammarForNonSymbolComputedProperty(node, message) { - if (node.kind === 136 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(node.expression)) { + if (ts.isDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -27876,12 +30067,12 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (node.parent.kind === 169 /* ObjectLiteralExpression */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; } else if (node.body === undefined) { - return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (ts.isClassLike(node.parent)) { @@ -27900,10 +30091,10 @@ 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 === 215 /* InterfaceDeclaration */) { + else if (node.parent.kind === 219 /* 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 === 155 /* TypeLiteral */) { + else if (node.parent.kind === 157 /* TypeLiteral */) { return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); } } @@ -27914,11 +30105,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 207 /* LabeledStatement */: + case 211 /* 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 === 202 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 206 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -27926,8 +30117,8 @@ var ts; return false; } break; - case 206 /* SwitchStatement */: - if (node.kind === 203 /* BreakStatement */ && !node.label) { + case 210 /* SwitchStatement */: + if (node.kind === 207 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -27942,13 +30133,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 203 /* BreakStatement */ + var message = node.kind === 207 /* 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 === 203 /* BreakStatement */ + var message = node.kind === 207 /* 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); @@ -27960,7 +30151,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 === 162 /* ArrayBindingPattern */ || node.name.kind === 161 /* ObjectBindingPattern */) { + if (node.name.kind === 166 /* ArrayBindingPattern */ || node.name.kind === 165 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -27970,7 +30161,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 200 /* ForInStatement */ && node.parent.parent.kind !== 201 /* ForOfStatement */) { + if (node.parent.parent.kind !== 204 /* ForInStatement */ && node.parent.parent.kind !== 205 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { // Error on equals token which immediate precedes the initializer @@ -27987,7 +30178,7 @@ var ts; } } } - var checkLetConstNames = languageVersion >= 2 /* ES6 */ && (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding @@ -27998,7 +30189,7 @@ var ts; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 69 /* Identifier */) { - if (name.text === "let") { + if (name.originalKeywordKind === 108 /* LetKeyword */) { return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -28006,7 +30197,7 @@ var ts; var elements = name.elements; for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { var element = elements_2[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 191 /* OmittedExpression */) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -28023,15 +30214,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 196 /* IfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 200 /* IfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: + case 209 /* WithStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: return false; - case 207 /* LabeledStatement */: + case 211 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -28046,23 +30237,6 @@ var ts; } } } - function isIntegerLiteral(expression) { - if (expression.kind === 179 /* PrefixUnaryExpression */) { - var unaryExpression = expression; - if (unaryExpression.operator === 35 /* PlusToken */ || unaryExpression.operator === 36 /* MinusToken */) { - expression = unaryExpression.operand; - } - } - if (expression.kind === 8 /* NumericLiteral */) { - // Allows for scientific notation since literalExpression.text was formed by - // coercing a number to a string. Sometimes this coercion can yield a string - // in scientific notation. - // We also don't need special logic for hex because a hex integer is converted - // to decimal when it is coerced. - return /^[0-9]+([eE]\+?[0-9]+)?$/.test(expression.text); - } - return false; - } function hasParseDiagnostics(sourceFile) { return sourceFile.parseDiagnostics.length > 0; } @@ -28087,10 +30261,6 @@ var ts; return true; } } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 69 /* 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); @@ -28108,15 +30278,21 @@ var ts; return true; } } - else if (node.parent.kind === 215 /* InterfaceDeclaration */) { + else if (node.parent.kind === 219 /* InterfaceDeclaration */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } } - else if (node.parent.kind === 155 /* TypeLiteral */) { + else if (node.parent.kind === 157 /* TypeLiteral */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } } if (ts.isInAmbientContext(node) && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); @@ -28135,14 +30311,14 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 215 /* InterfaceDeclaration */ || - node.kind === 216 /* TypeAliasDeclaration */ || - node.kind === 222 /* ImportDeclaration */ || - node.kind === 221 /* ImportEqualsDeclaration */ || - node.kind === 228 /* ExportDeclaration */ || - node.kind === 227 /* ExportAssignment */ || - (node.flags & 4 /* Ambient */) || - (node.flags & (2 /* Export */ | 512 /* Default */))) { + if (node.kind === 219 /* InterfaceDeclaration */ || + node.kind === 220 /* TypeAliasDeclaration */ || + node.kind === 226 /* ImportDeclaration */ || + node.kind === 225 /* ImportEqualsDeclaration */ || + node.kind === 232 /* ExportDeclaration */ || + node.kind === 231 /* ExportAssignment */ || + (node.flags & 2 /* Ambient */) || + (node.flags & (1 /* Export */ | 512 /* Default */))) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -28150,7 +30326,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 === 193 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 197 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -28173,10 +30349,10 @@ var ts; } // We are either parented by another statement, or some sort of block. // If we're in a block, we only want to really report an error once - // to prevent noisyness. So use a bit on the block to indicate if + // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 192 /* Block */ || node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + if (node.parent.kind === 196 /* Block */ || node.parent.kind === 223 /* ModuleBlock */ || node.parent.kind === 252 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -28189,7 +30365,7 @@ var ts; } function checkGrammarNumericLiteral(node) { // Grammar checking - if (node.flags & 32768 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { + if (node.isOctalLiteral && languageVersion >= 1 /* ES5 */) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -28201,21 +30377,345 @@ var ts; return true; } } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); /// /* @internal */ var ts; +(function (ts) { + var nullSourceMapWriter; + // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans + var defaultLastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitStart: function (range) { }, + emitEnd: function (range, stopOverridingSpan) { }, + emitPos: function (pos) { }, + changeEmitSourcePos: function () { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; }, + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var currentSourceFile; + var sourceMapDir; // The directory in which sourcemap will be + var stopOverridingSpan = false; + var modifyLastSourcePos = false; + // Current source map file and its index in the sources list + var sourceMapSourceIndex; + // Last recorded and encoded spans + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + // Source map data + var sourceMapData; + return { + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + changeEmitSourcePos: changeEmitSourcePos, + getText: getText, + getSourceMappingURL: getSourceMappingURL, + initialize: initialize, + reset: reset + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + // Current source map file and its index in the sources list + sourceMapSourceIndex = -1; + // Last recorded and encoded spans + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; + lastEncodedNameIndex = 0; + // Initialize source map data + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, + sourceMapDecodedMappings: [] + }; + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + } + function updateLastEncodedAndRecordedSpans() { + if (modifyLastSourcePos) { + // Reset the source pos + modifyLastSourcePos = false; + // Change Last recorded Map with last encoded emit line and character + lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; + lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; + // Pop sourceMapDecodedMappings to remove last entry + sourceMapData.sourceMapDecodedMappings.pop(); + // Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan + // If the list is empty which indicates that we are at the beginning of the file, + // we have to reset it to default value (same value when we first initialize sourceMapWriter) + lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? + sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : + defaultLastEncodedSourceMapSpan; + // TODO: Update lastEncodedNameIndex + // Since we dont support this any more, lets not worry about it right now. + // When we start supporting nameIndex, we will get back to this + // Change the encoded source map + var sourceMapMappings = sourceMapData.sourceMapMappings; + var lenthToSet = sourceMapMappings.length - 1; + for (; lenthToSet >= 0; lenthToSet--) { + var currentChar = sourceMapMappings.charAt(lenthToSet); + if (currentChar === ",") { + // Separator for the entry found + break; + } + if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { + // Last line separator found + break; + } + } + sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); + } + } + // Encoding for sourcemap span + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + // Line/Comma delimiters + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + // Emit comma to separate the entry + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + // Emit line delimiters + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + // 1. Relative Column 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + // 2. Relative sourceIndex + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + // 3. Relative sourceLine 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + // 4. Relative sourceColumn 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + // 5. Relative namePosition 0 based + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this"); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (pos === -1) { + return; + } + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + // Convert the location to be one-based. + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + 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.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + // Encode the last recordedSpan before assigning new + encodeLastRecordedSourceMapSpan(); + // New span + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + sourceIndex: sourceMapSourceIndex + }; + stopOverridingSpan = false; + } + else if (!stopOverridingSpan) { + // Take the new pos instead since there is no change in emittedLine and column since last location + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + updateLastEncodedAndRecordedSpans(); + } + function getStartPos(range) { + var rangeHasDecorators = !!range.decorators; + return range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1; + } + function emitStart(range) { + emitPos(getStartPos(range)); + } + function emitEnd(range, stopOverridingEnd) { + emitPos(range.end); + stopOverridingSpan = stopOverridingEnd; + } + function changeEmitSourcePos() { + ts.Debug.assert(!modifyLastSourcePos); + modifyLastSourcePos = true; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + // Add the file to tsFilePaths + // If sourceroot option: Use the relative path corresponding to the common directory path + // otherwise source locations relative to map file location + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + // The one that can be used from program to get the actual source file + sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + ts.createSourceMapWriter = createSourceMapWriter; + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + // Encode 5 bits at a time starting from least significant bits + var encodedStr = ""; + do { + var currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } +})(ts || (ts = {})); +/// +/* @internal */ +var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var diagnostics = []; - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); - emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; + var declarationDiagnostics = ts.createDiagnosticCollection(); + ts.forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); + return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName); + function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { + var declarationFilePath = _a.declarationFilePath; + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -28223,87 +30723,109 @@ var ts; var increaseIndent; var decreaseIndent; var writeTextOfNode; - var writer = createAndSetNewTextWriterWithSymbolWriter(); + var writer; + createAndSetNewTextWriterWithSymbolWriter(); var enclosingDeclaration; - var currentSourceFile; + var resultHasExternalModuleIndicator; + var currentText; + var currentLineMap; + var currentIdentifiers; + var isCurrentFileExternalModule; var reportedDeclarationError = false; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; + var noDeclare; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. // Collecting this separately because reference paths need to be first thing in the declaration file // and we could be collecting these paths from multiple files into single one with --out option var referencePathsOutput = ""; - if (root) { - // Emitting just a single file, so emit references in this file only + // Emit references corresponding to each file + var emittedReferencedFiles = []; + var addedGlobalFileReference = false; + var allSourcesModuleElementDeclarationEmitInfo = []; + ts.forEach(sourceFiles, function (sourceFile) { + // Dont emit for javascript file + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + // Check what references need to be added if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; - ts.forEach(root.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); - // All the references that are not going to be part of same file - if (referencedFile && ((referencedFile.flags & 4096 /* DeclarationFile */) || - ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || - !addedGlobalFileReference)) { - writeReferencePath(referencedFile); - if (!ts.isExternalModuleOrDeclarationFile(referencedFile)) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + // Emit reference in dts, if the file reference was not already emitted + if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { + // Add a reference to generated dts file, + // global file reference is added only + // - if it is not bundled emit (because otherwise it would be self reference) + // - and it is not already added + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } + emittedReferencedFiles.push(referencedFile); } }); } - emitSourceFile(root); + resultHasExternalModuleIndicator = false; + if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { + noDeclare = false; + emitSourceFile(sourceFile); + } + else if (ts.isExternalModule(sourceFile)) { + noDeclare = true; + write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); + writeLine(); + increaseIndent(); + emitSourceFile(sourceFile); + decreaseIndent(); + write("}"); + writeLine(); + } // create asynchronous output for the importDeclarations if (moduleElementDeclarationEmitInfo.length) { var oldWriter = writer; ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible) { - ts.Debug.assert(aliasEmitInfo.node.kind === 222 /* ImportDeclaration */); + if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { + ts.Debug.assert(aliasEmitInfo.node.kind === 226 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0); + ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + increaseIndent(); + } writeImportDeclaration(aliasEmitInfo.node); aliasEmitInfo.asynchronousOutput = writer.getText(); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + decreaseIndent(); + } } }); setWriter(oldWriter); + allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); + moduleElementDeclarationEmitInfo = []; } - } - else { - // Emit references corresponding to this file - var emittedReferencedFiles = []; - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) { - // Check what references need to be added - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - // If the reference file is a declaration file or an external module, emit that reference - if (referencedFile && (ts.isExternalModuleOrDeclarationFile(referencedFile) && - !ts.contains(emittedReferencedFiles, referencedFile))) { - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - emitSourceFile(sourceFile); - } - }); - } + if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + // in case if we didn't write any external module specifiers in .d.ts we need to emit something + // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. + write("export {};"); + writeLine(); + } + }); return { reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: moduleElementDeclarationEmitInfo, + moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput: referencePathsOutput }; function hasInternalAnnotation(range) { - var text = currentSourceFile.text; - var comment = text.substring(range.pos, range.end); + var comment = currentText.substring(range.pos, range.end); return comment.indexOf("@internal") >= 0; } function stripInternal(node) { if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { return; } @@ -28322,7 +30844,6 @@ var ts; writer.writeParameter = writer.write; writer.writeSymbol = writer.write; setWriter(writer); - return writer; } function setWriter(newWriter) { writer = newWriter; @@ -28336,10 +30857,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 211 /* VariableDeclaration */) { + if (declaration.kind === 215 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 225 /* NamedImports */ || declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 223 /* ImportClause */) { + else if (declaration.kind === 229 /* NamedImports */ || declaration.kind === 230 /* ImportSpecifier */ || declaration.kind === 227 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -28357,7 +30878,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 === 222 /* ImportDeclaration */) { + if (moduleElementEmitInfo.node.kind === 226 /* 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; @@ -28367,12 +30888,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 222 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 222 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -28382,23 +30903,23 @@ var ts; }); setWriter(oldWriter); } - function handleSymbolAccessibilityError(symbolAccesibilityResult) { - if (symbolAccesibilityResult.accessibility === 0 /* Accessible */) { + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { // write the aliases - if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccesibilityResult.aliasesToMakeVisible); + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); } } else { // Report error reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); if (errorInfo) { if (errorInfo.typeName) { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); } else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); } } } @@ -28408,7 +30929,8 @@ var ts; } function reportInaccessibleThisError() { if (errorNameNode) { - diagnostics.push(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + reportedDeclarationError = true; + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); } } function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { @@ -28461,10 +30983,10 @@ var ts; } function writeJsDocComments(declaration) { if (declaration) { - var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile); - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); + var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -28474,64 +30996,64 @@ var ts; function emitType(type) { switch (type.kind) { case 117 /* AnyKeyword */: - case 130 /* StringKeyword */: - case 128 /* NumberKeyword */: + case 131 /* StringKeyword */: + case 129 /* NumberKeyword */: case 120 /* BooleanKeyword */: - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 97 /* ThisKeyword */: - case 9 /* StringLiteral */: - return writeTextOfNode(currentSourceFile, type); - case 188 /* ExpressionWithTypeArguments */: + case 163 /* ThisType */: + case 164 /* StringLiteralType */: + return writeTextOfNode(currentText, type); + case 192 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); - case 151 /* TypeReference */: + case 153 /* TypeReference */: return emitTypeReference(type); - case 154 /* TypeQuery */: + case 156 /* TypeQuery */: return emitTypeQuery(type); - case 156 /* ArrayType */: + case 158 /* ArrayType */: return emitArrayType(type); - case 157 /* TupleType */: + case 159 /* TupleType */: return emitTupleType(type); - case 158 /* UnionType */: + case 160 /* UnionType */: return emitUnionType(type); - case 159 /* IntersectionType */: + case 161 /* IntersectionType */: return emitIntersectionType(type); - case 160 /* ParenthesizedType */: + case 162 /* ParenthesizedType */: return emitParenType(type); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: return emitSignatureDeclarationWithJsDocComments(type); - case 155 /* TypeLiteral */: + case 157 /* TypeLiteral */: return emitTypeLiteral(type); case 69 /* Identifier */: return emitEntityName(type); - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: return emitEntityName(type); - case 150 /* TypePredicate */: + case 152 /* TypePredicate */: return emitTypePredicate(type); } function writeEntityName(entityName) { if (entityName.kind === 69 /* Identifier */) { - writeTextOfNode(currentSourceFile, entityName); + writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 135 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 135 /* QualifiedName */ ? entityName.right : entityName.name; + var left = entityName.kind === 137 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 137 /* QualifiedName */ ? entityName.right : entityName.name; writeEntityName(left); write("."); - writeTextOfNode(currentSourceFile, right); + writeTextOfNode(currentText, right); } } function emitEntityName(entityName) { var visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 221 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + entityName.parent.kind === 225 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); handleSymbolAccessibilityError(visibilityResult); writeEntityName(entityName); } function emitExpressionWithTypeArguments(node) { if (ts.isSupportedExpressionWithTypeArguments(node)) { - ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 166 /* PropertyAccessExpression */); + ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 170 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -28549,7 +31071,7 @@ var ts; } } function emitTypePredicate(type) { - writeTextOfNode(currentSourceFile, type.parameterName); + writeTextOfNode(currentText, type.parameterName); write(" is "); emitType(type.type); } @@ -28590,9 +31112,12 @@ var ts; } } function emitSourceFile(node) { - currentSourceFile = node; + currentText = node.text; + currentLineMap = ts.getLineStarts(node); + currentIdentifiers = node.identifiers; + isCurrentFileExternalModule = ts.isExternalModule(node); enclosingDeclaration = node; - ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true /* remove comments */); + ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true /* remove comments */); emitLines(node.statements); } // Return a temp variable name to be used in `export default` statements. @@ -28601,21 +31126,22 @@ var ts; // do not need to keep track of created temp names. function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) { + if (!ts.hasProperty(currentIdentifiers, baseName)) { return baseName; } var count = 0; while (true) { - var name_18 = baseName + "_" + (++count); - if (!ts.hasProperty(currentSourceFile.identifiers, name_18)) { - return name_18; + count++; + var name_20 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_20)) { + return name_20; } } } function emitExportAssignment(node) { if (node.expression.kind === 69 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentSourceFile, node.expression); + writeTextOfNode(currentText, node.expression); } else { // Expression @@ -28652,10 +31178,10 @@ var ts; if (isModuleElementVisible) { writeModuleElement(node); } - else if (node.kind === 221 /* ImportEqualsDeclaration */ || - (node.parent.kind === 248 /* SourceFile */ && ts.isExternalModule(currentSourceFile))) { - var isVisible; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248 /* SourceFile */) { + else if (node.kind === 225 /* ImportEqualsDeclaration */ || + (node.parent.kind === 252 /* SourceFile */ && isCurrentFileExternalModule)) { + var isVisible = void 0; + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 252 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -28665,7 +31191,7 @@ var ts; }); } else { - if (node.kind === 222 /* ImportDeclaration */) { + if (node.kind === 226 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -28683,23 +31209,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return writeVariableStatement(node); - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: return writeClassDeclaration(node); - case 216 /* TypeAliasDeclaration */: + case 220 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -28707,30 +31233,33 @@ var ts; } function emitModuleElementDeclarationFlags(node) { // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent === currentSourceFile) { + if (node.parent.kind === 252 /* SourceFile */) { // If the node is exported - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { write("export "); } if (node.flags & 512 /* Default */) { write("default "); } - else if (node.kind !== 215 /* InterfaceDeclaration */) { + else if (node.kind !== 219 /* InterfaceDeclaration */ && !noDeclare) { write("declare "); } } } - function emitClassMemberDeclarationFlags(node) { - if (node.flags & 16 /* Private */) { + function emitClassMemberDeclarationFlags(flags) { + if (flags & 8 /* Private */) { write("private "); } - else if (node.flags & 32 /* Protected */) { + else if (flags & 16 /* Protected */) { write("protected "); } - if (node.flags & 64 /* Static */) { + if (flags & 32 /* Static */) { write("static "); } - if (node.flags & 128 /* Abstract */) { + if (flags & 64 /* Readonly */) { + write("readonly "); + } + if (flags & 128 /* Abstract */) { write("abstract "); } } @@ -28738,11 +31267,11 @@ var ts; // note usage of writer. methods instead of aliases created, just to make sure we are using // correct writer especially to handle asynchronous alias writing emitJsDocComments(node); - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { write("export "); } write("import "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" = "); if (ts.isInternalModuleImportEqualsDeclaration(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); @@ -28750,11 +31279,11 @@ var ts; } else { write("require("); - writeTextOfNode(currentSourceFile, ts.getExternalModuleImportEqualsDeclarationExpression(node)); + emitExternalModuleSpecifier(node); write(");"); } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccesibilityResult) { + function getImportEntityNameVisibilityError(symbolAccessibilityResult) { return { diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -28764,7 +31293,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 224 /* NamespaceImport */) { + if (namedBindings.kind === 228 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -28773,28 +31302,24 @@ var ts; } } function writeImportDeclaration(node) { - if (!node.importClause && !(node.flags & 2 /* Export */)) { - // do not write non-exported import declarations that don't have import clauses - return; - } emitJsDocComments(node); - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { write("export "); } write("import "); if (node.importClause) { var currentWriterPos = writer.getTextPos(); if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentSourceFile, node.importClause.name); + writeTextOfNode(currentText, node.importClause.name); } if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { if (currentWriterPos !== writer.getTextPos()) { // If the default binding was emitted, write the separated write(", "); } - if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 228 /* NamespaceImport */) { write("* as "); - writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name); + writeTextOfNode(currentText, node.importClause.namedBindings.name); } else { write("{ "); @@ -28804,16 +31329,45 @@ var ts; } write(" from "); } - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); write(";"); writer.writeLine(); } + function emitExternalModuleSpecifier(parent) { + // emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations). + // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered + // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' + // so compiler will treat them as external modules. + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 222 /* ModuleDeclaration */; + var moduleSpecifier; + if (parent.kind === 225 /* ImportEqualsDeclaration */) { + var node = parent; + moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); + } + else if (parent.kind === 222 /* ModuleDeclaration */) { + moduleSpecifier = parent.name; + } + else { + var node = parent; + moduleSpecifier = node.moduleSpecifier; + } + if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); + if (moduleName) { + write("\""); + write(moduleName); + write("\""); + return; + } + } + writeTextOfNode(currentText, moduleSpecifier); + } function emitImportOrExportSpecifier(node) { if (node.propertyName) { - writeTextOfNode(currentSourceFile, node.propertyName); + writeTextOfNode(currentText, node.propertyName); write(" as "); } - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } function emitExportSpecifier(node) { emitImportOrExportSpecifier(node); @@ -28835,7 +31389,7 @@ var ts; } if (node.moduleSpecifier) { write(" from "); - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); } write(";"); writer.writeLine(); @@ -28843,17 +31397,27 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 65536 /* Namespace */) { - write("namespace "); + if (ts.isGlobalScopeAugmentation(node)) { + write("global "); } else { - write("module "); + if (node.flags & 4096 /* Namespace */) { + write("namespace "); + } + else { + write("module "); + } + if (ts.isExternalModuleAugmentation(node)) { + emitExternalModuleSpecifier(node); + } + else { + writeTextOfNode(currentText, node.name); + } } - writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 219 /* ModuleBlock */) { + while (node.body.kind !== 223 /* ModuleBlock */) { node = node.body; write("."); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; @@ -28872,14 +31436,14 @@ var ts; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("type "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); emitTypeParameters(node.typeParameters); write(" = "); emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); write(";"); writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult) { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -28894,7 +31458,7 @@ var ts; write("const "); } write("enum "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" {"); writeLine(); increaseIndent(); @@ -28905,7 +31469,7 @@ var ts; } function emitEnumMemberDeclaration(node) { emitJsDocComments(node); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); @@ -28915,61 +31479,61 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 143 /* MethodDeclaration */ && (node.parent.flags & 16 /* Private */); + return node.parent.kind === 145 /* MethodDeclaration */ && (node.parent.flags & 8 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { increaseIndent(); emitJsDocComments(node); decreaseIndent(); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); // 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 === 152 /* FunctionType */ || - node.parent.kind === 153 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 155 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 143 /* MethodDeclaration */ || - node.parent.kind === 142 /* MethodSignature */ || - node.parent.kind === 152 /* FunctionType */ || - node.parent.kind === 153 /* ConstructorType */ || - node.parent.kind === 147 /* CallSignature */ || - node.parent.kind === 148 /* ConstructSignature */); + if (node.parent.kind === 154 /* FunctionType */ || + node.parent.kind === 155 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 157 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 145 /* MethodDeclaration */ || + node.parent.kind === 144 /* MethodSignature */ || + node.parent.kind === 154 /* FunctionType */ || + node.parent.kind === 155 /* ConstructorType */ || + node.parent.kind === 149 /* CallSignature */ || + node.parent.kind === 150 /* ConstructSignature */); emitType(node.constraint); } else { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); } } - function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { + function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult) { // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 148 /* ConstructSignature */: + case 150 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 147 /* CallSignature */: + case 149 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - if (node.parent.flags & 64 /* Static */) { + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + if (node.parent.flags & 32 /* 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 === 214 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 218 /* 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 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -29000,10 +31564,10 @@ var ts; else if (!isImplementsList && node.expression.kind === 93 /* NullKeyword */) { write("null"); } - function getHeritageClauseVisibilityError(symbolAccesibilityResult) { + function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + if (node.parent.parent.kind === 218 /* 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 : @@ -29025,7 +31589,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 56 /* AccessibilityModifier */) { + if (param.flags & 28 /* AccessibilityModifier */) { emitPropertyDeclaration(param); } }); @@ -29037,7 +31601,7 @@ var ts; write("abstract "); } write("class "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -29060,7 +31624,7 @@ var ts; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("interface "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -29079,7 +31643,7 @@ var ts; return; } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node); + emitClassMemberDeclarationFlags(node.flags); emitVariableDeclaration(node); write(";"); writeLine(); @@ -29087,7 +31651,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 !== 211 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (node.kind !== 215 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -29095,53 +31659,53 @@ var ts; // If this node is a computed name, it can only be a symbol, because we've already skipped // it if it's not a well known symbol. In that case, the text of the name will be exactly // what we want, namely the name expression enclosed in brackets. - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); // If optional property emit ? - if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && ts.hasQuestionToken(node)) { + if ((node.kind === 143 /* PropertyDeclaration */ || node.kind === 142 /* PropertySignature */) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && node.parent.kind === 155 /* TypeLiteral */) { + if ((node.kind === 143 /* PropertyDeclaration */ || node.kind === 142 /* PropertySignature */) && node.parent.kind === 157 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 16 /* Private */)) { + else if (!(node.flags & 8 /* Private */)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 211 /* VariableDeclaration */) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 215 /* VariableDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) { + else if (node.kind === 143 /* PropertyDeclaration */ || node.kind === 142 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. - if (node.flags & 64 /* Static */) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + if (node.flags & 32 /* Static */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : 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 === 214 /* ClassDeclaration */) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + else if (node.parent.kind === 218 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; } else { // Interfaces cannot have types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; } } } - function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: node, @@ -29157,15 +31721,15 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 191 /* OmittedExpression */) { elements.push(element); } } emitCommaList(elements, emitBindingElement); } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: bindingElement, @@ -29177,7 +31741,7 @@ var ts; emitBindingPattern(bindingElement.name); } else { - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError); } } @@ -29220,14 +31784,14 @@ var ts; if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node); - writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 16 /* Private */)) { + emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : 64 /* Readonly */)); + writeTextOfNode(currentText, node.name); + if (!(node.flags & 8 /* Private */)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 145 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + var anotherAccessor = node.kind === 147 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -29240,24 +31804,24 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 145 /* GetAccessor */ + return accessor.kind === 147 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type : undefined; } } - function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 146 /* SetAccessor */) { + if (accessorWithTypeAnnotation.kind === 148 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named - if (accessorWithTypeAnnotation.parent.flags & 64 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + if (accessorWithTypeAnnotation.parent.flags & 32 /* Static */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; } @@ -29269,16 +31833,16 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 64 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + if (accessorWithTypeAnnotation.flags & 32 /* Static */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; @@ -29299,21 +31863,21 @@ var ts; // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 217 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 143 /* MethodDeclaration */) { - emitClassMemberDeclarationFlags(node); + else if (node.kind === 145 /* MethodDeclaration */ || node.kind === 146 /* Constructor */) { + emitClassMemberDeclarationFlags(node.flags); } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 217 /* FunctionDeclaration */) { write("function "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } - else if (node.kind === 144 /* Constructor */) { + else if (node.kind === 146 /* Constructor */) { write("constructor"); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); if (ts.hasQuestionToken(node)) { write("?"); } @@ -29326,37 +31890,39 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { - // Construct signature or constructor type write new Signature - if (node.kind === 148 /* ConstructSignature */ || node.kind === 153 /* ConstructorType */) { - write("new "); - } - emitTypeParameters(node.typeParameters); - if (node.kind === 149 /* IndexSignature */) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + if (node.kind === 151 /* IndexSignature */) { + // Index signature can have readonly modifier + emitClassMemberDeclarationFlags(node.flags); write("["); } else { + // Construct signature or constructor type write new Signature + if (node.kind === 150 /* ConstructSignature */ || node.kind === 155 /* ConstructorType */) { + write("new "); + } + emitTypeParameters(node.typeParameters); write("("); } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; // Parameters emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 149 /* IndexSignature */) { + if (node.kind === 151 /* IndexSignature */) { write("]"); } else { write(")"); } // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 152 /* FunctionType */ || node.kind === 153 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 155 /* TypeLiteral */) { + var isFunctionTypeOrConstructorType = node.kind === 154 /* FunctionType */ || node.kind === 155 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 157 /* TypeLiteral */) { // Emit type literal signature return type only if specified if (node.type) { write(isFunctionTypeOrConstructorType ? " => " : ": "); emitType(node.type); } } - else if (node.kind !== 144 /* Constructor */ && !(node.flags & 16 /* Private */)) { + else if (node.kind !== 146 /* Constructor */ && !(node.flags & 8 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -29364,53 +31930,53 @@ var ts; write(";"); writeLine(); } - function getReturnTypeVisibilityError(symbolAccesibilityResult) { + function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 148 /* ConstructSignature */: + case 150 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.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 147 /* CallSignature */: + case 149 /* CallSignature */: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.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 149 /* IndexSignature */: + case 151 /* IndexSignature */: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.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 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - if (node.flags & 64 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + if (node.flags & 32 /* Static */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : 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 === 214 /* ClassDeclaration */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + else if (node.parent.kind === 218 /* ClassDeclaration */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; } else { // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 213 /* FunctionDeclaration */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + case 217 /* FunctionDeclaration */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; @@ -29437,71 +32003,71 @@ var ts; emitBindingPattern(node.name); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } if (resolver.isOptionalParameter(node)) { write("?"); } decreaseIndent(); - if (node.parent.kind === 152 /* FunctionType */ || - node.parent.kind === 153 /* ConstructorType */ || - node.parent.parent.kind === 155 /* TypeLiteral */) { + if (node.parent.kind === 154 /* FunctionType */ || + node.parent.kind === 155 /* ConstructorType */ || + node.parent.parent.kind === 157 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 16 /* Private */)) { + else if (!(node.parent.flags & 8 /* Private */)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } - function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage: diagnosticMessage, errorNode: node, typeName: node.name } : undefined; } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 144 /* Constructor */: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + case 146 /* Constructor */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 148 /* ConstructSignature */: + case 150 /* ConstructSignature */: // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.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 147 /* CallSignature */: + case 149 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.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 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - if (node.parent.flags & 64 /* Static */) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + if (node.parent.flags & 32 /* Static */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : 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 === 214 /* ClassDeclaration */) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + else if (node.parent.parent.kind === 218 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.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 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? 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 213 /* FunctionDeclaration */: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + case 217 /* FunctionDeclaration */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; @@ -29511,12 +32077,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 === 161 /* ObjectBindingPattern */) { + if (bindingPattern.kind === 165 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 162 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 166 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -29527,15 +32093,7 @@ var ts; } } function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.kind === 187 /* OmittedExpression */) { + if (bindingElement.kind === 191 /* 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) @@ -29544,7 +32102,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 163 /* BindingElement */) { + else if (bindingElement.kind === 167 /* 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" @@ -29552,7 +32110,7 @@ var ts; // Example: // original: function foo({y: [a,b,c]}) {} // emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void; - writeTextOfNode(currentSourceFile, bindingElement.propertyName); + writeTextOfNode(currentText, bindingElement.propertyName); write(": "); } if (bindingElement.name) { @@ -29575,7 +32133,7 @@ var ts; if (bindingElement.dotDotDotToken) { write("..."); } - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); } } } @@ -29583,64 +32141,86 @@ var ts; } function emitNode(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 218 /* ModuleDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 215 /* InterfaceDeclaration */: - case 214 /* ClassDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: + case 217 /* FunctionDeclaration */: + case 222 /* ModuleDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 219 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 221 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: return emitExportDeclaration(node); - case 144 /* Constructor */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 146 /* Constructor */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return writeFunctionDeclaration(node); - case 148 /* ConstructSignature */: - case 147 /* CallSignature */: - case 149 /* IndexSignature */: + case 150 /* ConstructSignature */: + case 149 /* CallSignature */: + case 151 /* IndexSignature */: return emitSignatureDeclarationWithJsDocComments(node); - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: return emitAccessorDeclaration(node); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return emitPropertyDeclaration(node); - case 247 /* EnumMember */: + case 251 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return emitExportAssignment(node); - case 248 /* SourceFile */: + case 252 /* SourceFile */: return emitSourceFile(node); } } - function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 4096 /* DeclarationFile */ - ? referencedFile.fileName // Declaration file, use declaration file name - : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) - ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file - : ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; // Global out file - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ false); - referencePathsOutput += "/// " + newLine; + /** + * Adds the reference to referenced file, returns true if global file reference was emitted + * @param referencedFile + * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not + */ + function writeReferencePath(referencedFile, addBundledFileReference) { + var declFileName; + var addedBundledEmitReference = false; + if (ts.isDeclarationFile(referencedFile)) { + // Declaration file, use declaration file name + declFileName = referencedFile.fileName; + } + else { + // Get the declaration file path + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + } + if (declFileName) { + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + referencePathsOutput += "/// " + newLine; + } + return addedBundledEmitReference; + function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path + if (isBundledEmit && !addBundledFileReference) { + return; + } + ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); + declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; + addedBundledEmitReference = isBundledEmit; + } } } /* @internal */ - function writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); - // TODO(shkamat): Should we not write any declaration file if any of them can produce error, - // or should we just not write this file like we are doing now - if (!emitDeclarationResult.reportedDeclarationError) { + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; + if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } + return emitSkipped; function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { var appliedSyncOutputPos = 0; var declarationOutput = ""; @@ -29659,14 +32239,23 @@ var ts; ts.writeDeclarationFile = writeDeclarationFile; })(ts || (ts = {})); /// +/// /// /* @internal */ var ts; (function (ts) { - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); + function getResolvedExternalModuleName(host, file) { + return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || ts.isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; var Jump; (function (Jump) { Jump[Jump["Break"] = 2] = "Break"; @@ -29935,6 +32524,11 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); // 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 @@ -29945,41 +32539,19 @@ var ts; 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};"; // emit output for the __param helper function var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\n return new Promise(function (resolve, reject) {\n generator = generator.call(thisArg, _arguments);\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\n function onfulfill(value) { try { step(\"next\", value); } catch (e) { reject(e); } }\n function onreject(value) { try { step(\"throw\", value); } catch (e) { reject(e); } }\n function step(verb, value) {\n var result = generator[verb](value);\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\n }\n step(\"next\", void 0);\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || 0 /* ES3 */; - var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - var diagnostics = []; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emitSkipped = false; var newLine = host.getNewLine(); - var jsxDesugaring = host.getCompilerOptions().jsx !== 1 /* Preserve */; - var shouldEmitJsx = function (s) { return (s.languageVariant === 1 /* JSX */ && !jsxDesugaring); }; - if (targetSourceFile === undefined) { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - if (compilerOptions.outFile || compilerOptions.out) { - emitFile(compilerOptions.outFile || compilerOptions.out); - } - } - else { - // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) - if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) { - emitFile(compilerOptions.outFile || compilerOptions.out); - } - } - // Sort and make the unique list of diagnostics - diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics); + var emitJavaScript = createFileEmitter(); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { - emitSkipped: false, - diagnostics: diagnostics, + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), sourceMaps: sourceMapDataList }; function isUniqueLocalName(name, container) { @@ -30024,10 +32596,18 @@ var ts; } } } - function emitJavaScript(jsFilePath, root) { + function createFileEmitter() { var writer = ts.createTextWriter(newLine); var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); + var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; var currentSourceFile; + var currentText; + var currentLineMap; + var currentFileIdentifiers; + var renamedDependencies; + var isEs6Module; + var isCurrentFileExternalModule; // name of an exporter function if file is a System external module // System.register([...], function () {...}) // exporting in System modules looks like: @@ -30035,81 +32615,112 @@ var ts; // => // var x;... exporter("x", x = 1) var exportFunctionForFile; - var generatedNameSet = {}; - var nodeToGeneratedName = []; + var contextObjectForFile; + var generatedNameSet; + var nodeToGeneratedName; var computedPropertyNamesToGeneratedNames; + var decoratedClassAliases; var convertedLoopState; - var extendsEmitted = false; - var decorateEmitted = false; - var paramEmitted = false; - var awaiterEmitted = false; + var extendsEmitted; + var decorateEmitted; + var paramEmitted; + var awaiterEmitted; var tempFlags = 0; var tempVariables; var tempParameters; var externalImports; var exportSpecifiers; var exportEquals; - var hasExportStars; - /** Write emitted output to disk */ - var writeEmittedFiles = writeJavaScriptFile; + var hasExportStarsToExportValues; var detachedCommentsInfo; - var writeComment = ts.writeCommentRange; - /** Emit a node */ - var emit = emitNodeWithCommentsAndWithoutSourcemap; - /** Called just before starting emit of a node */ - var emitStart = function (node) { }; - /** Called once the emit of the node is done */ - var emitEnd = function (node) { }; - /** Emit the text for the given token that comes after startPos - * This by default writes the text provided with the given tokenKind - * but if optional emitFn callback is provided the text is emitted using the callback instead of default text - * @param tokenKind the kind of the token to search and emit - * @param startPos the position in the source to start searching for the token - * @param emitFn if given will be invoked to emit the text instead of actual token emit */ - var emitToken = emitTokenText; - /** Called to before starting the lexical scopes as in function/class in the emitted code because of node - * @param scopeDeclaration node that starts the lexical scope - * @param scopeName Optional name of this scope instead of deducing one from the declaration node */ - var scopeEmitStart = function (scopeDeclaration, scopeName) { }; - /** Called after coming out of the scope */ - var scopeEmitEnd = function () { }; /** Sourcemap data that will get encoded */ var sourceMapData; + /** Is the file being emitted into its own file */ + var isOwnFileEmit; /** If removeComments is true, no leading-comments needed to be emitted **/ var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; + var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; var moduleEmitDelegates = (_a = {}, - _a[5 /* ES6 */] = emitES6Module, - _a[2 /* AMD */] = emitAMDModule, - _a[4 /* System */] = emitSystemModule, - _a[3 /* UMD */] = emitUMDModule, - _a[1 /* CommonJS */] = emitCommonJSModule, + _a[ts.ModuleKind.ES6] = emitES6Module, + _a[ts.ModuleKind.AMD] = emitAMDModule, + _a[ts.ModuleKind.System] = emitSystemModule, + _a[ts.ModuleKind.UMD] = emitUMDModule, + _a[ts.ModuleKind.CommonJS] = emitCommonJSModule, _a ); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - initializeEmitterWithSourceMaps(); - } - if (root) { + var bundleEmitDelegates = (_b = {}, + _b[ts.ModuleKind.ES6] = function () { }, + _b[ts.ModuleKind.AMD] = emitAMDModule, + _b[ts.ModuleKind.System] = emitSystemModule, + _b[ts.ModuleKind.UMD] = function () { }, + _b[ts.ModuleKind.CommonJS] = function () { }, + _b + ); + return doEmit; + function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + generatedNameSet = {}; + nodeToGeneratedName = []; + decoratedClassAliases = []; + isOwnFileEmit = !isBundledEmit; + // Emit helpers from all the files + if (isBundledEmit && modulekind) { + ts.forEach(sourceFiles, emitEmitHelpers); + } // Do not call emit directly. It does not set the currentSourceFile. - emitSourceFile(root); + ts.forEach(sourceFiles, emitSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# sourceMappingURL=" + sourceMappingURL); + } + writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM); + // reset the state + sourceMap.reset(); + writer.reset(); + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + exportFunctionForFile = undefined; + contextObjectForFile = undefined; + generatedNameSet = undefined; + nodeToGeneratedName = undefined; + decoratedClassAliases = undefined; + computedPropertyNamesToGeneratedNames = undefined; + convertedLoopState = undefined; + extendsEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + tempFlags = 0; + tempVariables = undefined; + tempParameters = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = undefined; + detachedCommentsInfo = undefined; + sourceMapData = undefined; + isEs6Module = false; + renamedDependencies = undefined; + isCurrentFileExternalModule = false; } - else { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!isExternalModuleOrDeclarationFile(sourceFile)) { - emitSourceFile(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM); - return; function emitSourceFile(sourceFile) { currentSourceFile = sourceFile; + currentText = sourceFile.text; + currentLineMap = ts.getLineStarts(sourceFile); exportFunctionForFile = undefined; - emit(sourceFile); + contextObjectForFile = undefined; + isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"]; + renamedDependencies = sourceFile.renamedDependencies; + currentFileIdentifiers = sourceFile.identifiers; + isCurrentFileExternalModule = ts.isExternalModule(sourceFile); + setSourceFile(sourceFile); + emitNodeWithCommentsAndWithoutSourcemap(sourceFile); } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentSourceFile.identifiers, name) && + !ts.hasProperty(currentFileIdentifiers, name) && !ts.hasProperty(generatedNameSet, name); } // Return the next available name in the pattern _a ... _z, _0, _1, ... @@ -30117,10 +32728,10 @@ var ts; // Note that names generated by makeTempVariableName and makeUniqueName will never conflict. function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_19 = flags === 268435456 /* _i */ ? "_i" : "_n"; - if (isUniqueName(name_19)) { + var name_21 = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name_21)) { tempFlags |= flags; - return name_19; + return name_21; } } while (true) { @@ -30128,9 +32739,9 @@ var ts; tempFlags++; // Skip over 'i' and 'n' if (count !== 8 && count !== 13) { - var name_20 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_20)) { - return name_20; + var name_22 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); + if (isUniqueName(name_22)) { + return name_22; } } } @@ -30174,17 +32785,17 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return makeUniqueName(node.text); - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: + case 222 /* ModuleDeclaration */: + case 221 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 222 /* ImportDeclaration */: - case 228 /* ExportDeclaration */: + case 226 /* ImportDeclaration */: + case 232 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 213 /* FunctionDeclaration */: - case 214 /* ClassDeclaration */: - case 227 /* ExportAssignment */: + case 217 /* FunctionDeclaration */: + case 218 /* ClassDeclaration */: + case 231 /* ExportAssignment */: return generateNameForExportDefault(); - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: return generateNameForClassExpression(); } } @@ -30192,338 +32803,15 @@ var ts; 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 - // Current source map file and its index in the sources list - var sourceMapSourceIndex = -1; - // Names and its index map - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; + /** Write emitted output to disk */ + function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark) { + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); } - // Last recorded and encoded spans - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Line/Comma delimiters - if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { - // Emit comma to separate the entry - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - // Emit line delimiters - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - // 1. Relative Column 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - // 2. Relative sourceIndex - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - // 3. Relative sourceLine 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - // 4. Relative sourceColumn 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - // 5. Relative namePosition 0 based - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - // Add a new least significant bit that has the sign of the value. - // if negative number the least significant bit that gets added to the number has value 1 - // else least significant bit value that gets added is 0 - // eg. -1 changes to binary : 01 [1] => 3 - // +1 changes to binary : 01 [0] => 2 - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - // Encode 5 bits at a time starting from least significant bits - var encodedStr = ""; - do { - var currentDigit = inValue & 31; // 11111 - inValue = inValue >> 5; - if (inValue > 0) { - // There are still more digits to decode, set the msb (6th bit) - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); } - function recordSourceMapSpan(pos) { - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); - // Convert the location to be one-based. - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - 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.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - // Encode the last recordedSpan before assigning new - encodeLastRecordedSourceMapSpan(); - // New span - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - // Take the new pos instead since there is no change in emittedLine and column since last location - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - // Get the token pos after skipping to the token (ignoring the leading trivia) - recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - // Add the file to tsFilePaths - // If sourceroot option: Use the relative path corresponding to the common directory path - // otherwise source locations relative to map file location - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(node.fileName); - if (compilerOptions.inlineSources) { - if (!sourceMapData.sourceMapSourcesContent) { - sourceMapData.sourceMapSourcesContent = []; - } - sourceMapData.sourceMapSourcesContent.push(node.text); - } - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - // 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_21 = node.name; - if (!name_21 || name_21.kind !== 136 /* ComputedPropertyName */) { - scopeName = "." + scopeName; - } - scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - // The scope was already given a name use it - recordScopeNameStart(scopeName); - } - else if (node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */ || - node.kind === 143 /* MethodDeclaration */ || - node.kind === 142 /* MethodSignature */ || - node.kind === 145 /* GetAccessor */ || - node.kind === 146 /* SetAccessor */ || - node.kind === 218 /* ModuleDeclaration */ || - node.kind === 214 /* ClassDeclaration */ || - node.kind === 217 /* EnumDeclaration */) { - // Declaration and has associated name use it - if (node.name) { - var name_22 = node.name; - // For computed property names, the text will include the brackets - scopeName = name_22.kind === 136 /* ComputedPropertyName */ - ? ts.getTextOfNode(name_22) - : node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - // Block just use the name from upper level scope - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - ts.writeCommentRange(currentSourceFile, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) { - if (typeof JSON !== "undefined") { - var map_1 = { - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }; - if (sourcesContent !== undefined) { - map_1.sourcesContent = sourcesContent; - } - return JSON.stringify(map_1); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\" " + (sourcesContent !== undefined ? ",\"sourcesContent\":[" + serializeStringArray(sourcesContent) + "]" : "") + "}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) { - encodeLastRecordedSourceMapSpan(); - var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent); - sourceMapDataList.push(sourceMapData); - var sourceMapUrl; - if (compilerOptions.inlineSourceMap) { - // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.convertToBase64(sourceMapText); - sourceMapUrl = "//# sourceMappingURL=data:application/json;base64," + base64SourceMapText; - } - else { - // Write source map file - ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, /*writeByteOrderMark*/ false); - sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL; - } - // Write sourcemap url to the js file and write the js file - writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark); - } - // Initialize source map data - var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapSourcesContent: undefined, - sourceMapDecodedMappings: [] - }; - // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the - // relative paths of the sources list in the sourcemap - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - // For modules or multiple emit files the mapRoot will have directory structure like the sources - // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - // The relative paths are relative to the common directory - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath - ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap - host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithSourceMap(node) { - if (node) { - if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node); - } - if (node.kind !== 248 /* SourceFile */) { - recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node); - } - } - } - function emitNodeWithCommentsAndWithSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithCommentsAndWithSourcemap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, writeByteOrderMark) { - ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark); } // Create a temporary variable with a unique unused name. function createTempVariable(flags) { @@ -30555,7 +32843,15 @@ var ts; write(";"); } } - function emitTokenText(tokenKind, startPos, emitFn) { + /** Emit the text for the given token that comes after startPos + * This by default writes the text provided with the given tokenKind + * but if optional emitFn callback is provided the text is emitted using the callback instead of default text + * @param tokenKind the kind of the token to search and emit + * @param startPos the position in the source to start searching for the token + * @param emitFn if given will be invoked to emit the text instead of actual token emit */ + function emitToken(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentText, startPos); + emitPos(tokenStartPos); var tokenString = ts.tokenToString(tokenKind); if (emitFn) { emitFn(); @@ -30563,7 +32859,9 @@ var ts; else { write(tokenString); } - return startPos + tokenString.length; + var tokenEndPos = tokenStartPos + tokenString.length; + emitPos(tokenEndPos); + return tokenEndPos; } function emitOptional(prefix, node) { if (node) { @@ -30580,11 +32878,6 @@ var ts; write(")"); } } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { ts.Debug.assert(nodes.length > 0); increaseIndent(); @@ -30657,7 +32950,7 @@ var ts; } function emitCommaList(nodes) { if (nodes) { - emitList(nodes, 0, nodes.length, /*multiline*/ false, /*trailingComma*/ false); + emitList(nodes, 0, nodes.length, /*multiLine*/ false, /*trailingComma*/ false); } } function emitLines(nodes) { @@ -30702,7 +32995,7 @@ var ts; // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (node.parent) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + return ts.getTextOfNodeFromSourceText(currentText, node); } // If we can't reach the original source text, use the canonical form if it's a number, // or an escaped quoted form of the original text if it's string-like. @@ -30729,8 +33022,8 @@ var ts; // Find original source text, since we need to emit the raw strings of the tagged template. // The raw strings contain the (escaped) strings of what the user wrote. // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + var text = ts.getTextOfNodeFromSourceText(currentText, node); + // text contains the original source, it will also contain quotes ("`"), dollar signs and braces ("${" and "}"), // thus we need to remove those characters. // First template piece starts with "`", others with "}" // Last template piece ends with "`", others with "${" @@ -30772,10 +33065,10 @@ var ts; write("("); emit(tempVariable); // Now we emit the expressions - if (node.template.kind === 183 /* TemplateExpression */) { + if (node.template.kind === 187 /* TemplateExpression */) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 181 /* BinaryExpression */ + var needsParens = templateSpan.expression.kind === 185 /* BinaryExpression */ && templateSpan.expression.operatorToken.kind === 24 /* CommaToken */; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -30810,7 +33103,7 @@ var ts; // ("abc" + 1) << (2 + "") // rather than // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== 172 /* ParenthesizedExpression */ + var needsParens = templateSpan.expression.kind !== 176 /* 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 @@ -30852,11 +33145,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: return parent.expression === template; - case 170 /* TaggedTemplateExpression */: - case 172 /* ParenthesizedExpression */: + case 174 /* TaggedTemplateExpression */: + case 176 /* ParenthesizedExpression */: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; @@ -30877,7 +33170,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 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: switch (expression.operatorToken.kind) { case 37 /* AsteriskToken */: case 39 /* SlashToken */: @@ -30889,8 +33182,8 @@ var ts; default: return -1 /* LessThan */; } - case 184 /* YieldExpression */: - case 182 /* ConditionalExpression */: + case 188 /* YieldExpression */: + case 186 /* ConditionalExpression */: return -1 /* LessThan */; default: return 1 /* GreaterThan */; @@ -30918,13 +33211,13 @@ var ts; /// these emit into an object literal property name, we don't need to be worried /// about keywords, just non-identifier characters function emitAttributeName(name) { - if (/[A-Za-z_]+[\w*]/.test(name.text)) { - write("\""); + if (/^[A-Za-z_]\w*$/.test(name.text)) { emit(name); - write("\""); } else { + write("\""); emit(name); + write("\""); } } /// Emit an name/value pair for an attribute (e.g. "x: 3") @@ -30940,7 +33233,7 @@ var ts; } function emitJsxElement(openingNode, children) { var syntheticReactRef = ts.createSynthesizedNode(69 /* Identifier */); - syntheticReactRef.text = "React"; + syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; syntheticReactRef.parent = openingNode; // Call React.createElement(tag, ... emitLeadingComments(openingNode); @@ -30957,38 +33250,38 @@ var ts; // Either emit one big object literal (no spread attribs), or // a call to React.__spread var attrs = openingNode.attributes; - if (ts.forEach(attrs, function (attr) { return attr.kind === 239 /* JsxSpreadAttribute */; })) { + if (ts.forEach(attrs, function (attr) { return attr.kind === 243 /* JsxSpreadAttribute */; })) { emitExpressionIdentifier(syntheticReactRef); write(".__spread("); var haveOpenedObjectLiteral = false; - for (var i_1 = 0; i_1 < attrs.length; i_1++) { - if (attrs[i_1].kind === 239 /* JsxSpreadAttribute */) { + for (var i = 0; i < attrs.length; i++) { + if (attrs[i].kind === 243 /* JsxSpreadAttribute */) { // If this is the first argument, we need to emit a {} as the first argument - if (i_1 === 0) { + if (i === 0) { write("{}, "); } if (haveOpenedObjectLiteral) { write("}"); haveOpenedObjectLiteral = false; } - if (i_1 > 0) { + if (i > 0) { write(", "); } - emit(attrs[i_1].expression); + emit(attrs[i].expression); } else { - ts.Debug.assert(attrs[i_1].kind === 238 /* JsxAttribute */); + ts.Debug.assert(attrs[i].kind === 242 /* JsxAttribute */); if (haveOpenedObjectLiteral) { write(", "); } else { haveOpenedObjectLiteral = true; - if (i_1 > 0) { + if (i > 0) { write(", "); } write("{"); } - emitJsxAttribute(attrs[i_1]); + emitJsxAttribute(attrs[i]); } } if (haveOpenedObjectLiteral) @@ -30998,7 +33291,7 @@ var ts; else { // One object literal with all the attributes in them write("{"); - for (var i = 0; i < attrs.length; i++) { + for (var i = 0, n = attrs.length; i < n; i++) { if (i > 0) { write(", "); } @@ -31009,23 +33302,45 @@ var ts; } // Children if (children) { - for (var i = 0; i < children.length; i++) { - // Don't emit empty expressions - if (children[i].kind === 240 /* JsxExpression */ && !(children[i].expression)) { - continue; - } - // Don't emit empty strings - if (children[i].kind === 236 /* JsxText */) { - var text = getTextToEmit(children[i]); - if (text !== undefined) { - write(", \""); - write(text); - write("\""); + var firstChild = void 0; + var multipleEmittableChildren = false; + for (var i = 0, n = children.length; i < n; i++) { + var jsxChild = children[i]; + if (isJsxChildEmittable(jsxChild)) { + // we need to decide whether to emit in single line or multiple lines as indented list + // store firstChild reference, if we see another emittable child, then emit accordingly + if (!firstChild) { + write(", "); + firstChild = jsxChild; + } + else { + // more than one emittable child, emit indented list + if (!multipleEmittableChildren) { + multipleEmittableChildren = true; + increaseIndent(); + writeLine(); + emit(firstChild); + } + write(", "); + writeLine(); + emit(jsxChild); } } + } + if (multipleEmittableChildren) { + decreaseIndent(); + } + else if (firstChild) { + if (firstChild.kind !== 237 /* JsxElement */ && firstChild.kind !== 238 /* JsxSelfClosingElement */) { + emit(firstChild); + } else { - write(", "); - emit(children[i]); + // If the only child is jsx element, put it on a new indented line + increaseIndent(); + writeLine(); + emit(firstChild); + writeLine(); + decreaseIndent(); } } } @@ -31033,11 +33348,11 @@ var ts; write(")"); // closes "React.createElement(" emitTrailingComments(openingNode); } - if (node.kind === 233 /* JsxElement */) { + if (node.kind === 237 /* JsxElement */) { emitJsxElement(node.openingElement, node.children); } else { - ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(node.kind === 238 /* JsxSelfClosingElement */); emitJsxElement(node); } } @@ -31059,11 +33374,11 @@ var ts; if (i > 0) { write(" "); } - if (attribs[i].kind === 239 /* JsxSpreadAttribute */) { + if (attribs[i].kind === 243 /* JsxSpreadAttribute */) { emitJsxSpreadAttribute(attribs[i]); } else { - ts.Debug.assert(attribs[i].kind === 238 /* JsxAttribute */); + ts.Debug.assert(attribs[i].kind === 242 /* JsxAttribute */); emitJsxAttribute(attribs[i]); } } @@ -31071,11 +33386,11 @@ var ts; function emitJsxOpeningOrSelfClosingElement(node) { write("<"); emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 234 /* JsxSelfClosingElement */)) { + if (node.attributes.length > 0 || (node.kind === 238 /* JsxSelfClosingElement */)) { write(" "); } emitAttributes(node.attributes); - if (node.kind === 234 /* JsxSelfClosingElement */) { + if (node.kind === 238 /* JsxSelfClosingElement */) { write("/>"); } else { @@ -31094,11 +33409,11 @@ var ts; } emitJsxClosingElement(node.closingElement); } - if (node.kind === 233 /* JsxElement */) { + if (node.kind === 237 /* JsxElement */) { emitJsxElement(node); } else { - ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(node.kind === 238 /* JsxSelfClosingElement */); emitJsxOpeningOrSelfClosingElement(node); } } @@ -31106,11 +33421,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 !== 163 /* BindingElement */); + ts.Debug.assert(node.kind !== 167 /* BindingElement */); if (node.kind === 9 /* StringLiteral */) { emitLiteral(node); } - else if (node.kind === 136 /* ComputedPropertyName */) { + else if (node.kind === 138 /* 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: @@ -31146,7 +33461,7 @@ var ts; write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } write("\""); } @@ -31154,75 +33469,72 @@ var ts; function isExpressionIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 164 /* ArrayLiteralExpression */: - case 189 /* AsExpression */: - case 181 /* BinaryExpression */: - case 168 /* CallExpression */: - case 241 /* CaseClause */: - case 136 /* ComputedPropertyName */: - case 182 /* ConditionalExpression */: - case 139 /* Decorator */: - case 175 /* DeleteExpression */: - case 197 /* DoStatement */: - case 167 /* ElementAccessExpression */: - case 227 /* ExportAssignment */: - case 195 /* ExpressionStatement */: - case 188 /* ExpressionWithTypeArguments */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 196 /* IfStatement */: - case 234 /* JsxSelfClosingElement */: - case 235 /* JsxOpeningElement */: - case 239 /* JsxSpreadAttribute */: - case 240 /* JsxExpression */: - case 169 /* NewExpression */: - case 172 /* ParenthesizedExpression */: - case 180 /* PostfixUnaryExpression */: - case 179 /* PrefixUnaryExpression */: - case 204 /* ReturnStatement */: - case 246 /* ShorthandPropertyAssignment */: - case 185 /* SpreadElementExpression */: - case 206 /* SwitchStatement */: - case 170 /* TaggedTemplateExpression */: - case 190 /* TemplateSpan */: - case 208 /* ThrowStatement */: - case 171 /* TypeAssertionExpression */: - case 176 /* TypeOfExpression */: - case 177 /* VoidExpression */: - case 198 /* WhileStatement */: - case 205 /* WithStatement */: - case 184 /* YieldExpression */: + case 168 /* ArrayLiteralExpression */: + case 193 /* AsExpression */: + case 185 /* BinaryExpression */: + case 172 /* CallExpression */: + case 245 /* CaseClause */: + case 138 /* ComputedPropertyName */: + case 186 /* ConditionalExpression */: + case 141 /* Decorator */: + case 179 /* DeleteExpression */: + case 201 /* DoStatement */: + case 171 /* ElementAccessExpression */: + case 231 /* ExportAssignment */: + case 199 /* ExpressionStatement */: + case 192 /* ExpressionWithTypeArguments */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 200 /* IfStatement */: + case 241 /* JsxClosingElement */: + case 238 /* JsxSelfClosingElement */: + case 239 /* JsxOpeningElement */: + case 243 /* JsxSpreadAttribute */: + case 244 /* JsxExpression */: + case 173 /* NewExpression */: + case 176 /* ParenthesizedExpression */: + case 184 /* PostfixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: + case 208 /* ReturnStatement */: + case 250 /* ShorthandPropertyAssignment */: + case 189 /* SpreadElementExpression */: + case 210 /* SwitchStatement */: + case 174 /* TaggedTemplateExpression */: + case 194 /* TemplateSpan */: + case 212 /* ThrowStatement */: + case 175 /* TypeAssertionExpression */: + case 180 /* TypeOfExpression */: + case 181 /* VoidExpression */: + case 202 /* WhileStatement */: + case 209 /* WithStatement */: + case 188 /* YieldExpression */: return true; - case 163 /* BindingElement */: - case 247 /* EnumMember */: - case 138 /* Parameter */: - case 245 /* PropertyAssignment */: - case 141 /* PropertyDeclaration */: - case 211 /* VariableDeclaration */: + case 167 /* BindingElement */: + case 251 /* EnumMember */: + case 140 /* Parameter */: + case 249 /* PropertyAssignment */: + case 143 /* PropertyDeclaration */: + case 215 /* VariableDeclaration */: return parent.initializer === node; - case 166 /* PropertyAccessExpression */: + case 170 /* PropertyAccessExpression */: return parent.expression === node; - case 174 /* ArrowFunction */: - case 173 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 177 /* FunctionExpression */: return parent.body === node; - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return parent.moduleReference === node; - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: return parent.left === node; } return false; } function emitExpressionIdentifier(node) { - if (resolver.getNodeCheckFlags(node) & 2048 /* LexicalArguments */) { - write("_arguments"); - return; - } var container = resolver.getReferencedExportContainer(node); if (container) { - if (container.kind === 248 /* SourceFile */) { + if (container.kind === 252 /* SourceFile */) { // Identifier references module export - if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) { + if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { write("exports."); } } @@ -31233,20 +33545,20 @@ var ts; } } else { - if (modulekind !== 5 /* ES6 */) { + if (modulekind !== ts.ModuleKind.ES6) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { - if (declaration.kind === 223 /* ImportClause */) { + if (declaration.kind === 227 /* ImportClause */) { // Identifier references default import write(getGeneratedNameForNode(declaration.parent)); write(languageVersion === 0 /* ES3 */ ? "[\"default\"]" : ".default"); return; } - else if (declaration.kind === 226 /* ImportSpecifier */) { + else if (declaration.kind === 230 /* ImportSpecifier */) { // Identifier references named import write(getGeneratedNameForNode(declaration.parent.parent.parent)); var name_23 = declaration.propertyName || declaration.name; - var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_23); + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_23); if (languageVersion === 0 /* ES3 */ && identifier === "default") { write("[\"default\"]"); } @@ -31258,30 +33570,43 @@ var ts; } } } - if (languageVersion !== 2 /* ES6 */) { - var declaration = resolver.getReferencedNestedRedeclaration(node); + if (languageVersion < 2 /* ES6 */) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration) { write(getGeneratedNameForNode(declaration.name)); return; } } + else if (resolver.getNodeCheckFlags(node) & 1048576 /* BodyScopedClassBinding */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = decoratedClassAliases[ts.getNodeId(declaration)]; + if (classAlias !== undefined) { + write(classAlias); + return; + } + } + } } if (ts.nodeIsSynthesized(node)) { write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } } - function isNameOfNestedRedeclaration(node) { + function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node) { if (languageVersion < 2 /* ES6 */) { - var parent_6 = node.parent; - switch (parent_6.kind) { - case 163 /* BindingElement */: - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 211 /* VariableDeclaration */: - return parent_6.name === node && resolver.isNestedRedeclaration(parent_6); + var parent_8 = node.parent; + switch (parent_8.kind) { + case 167 /* BindingElement */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 215 /* VariableDeclaration */: + return parent_8.name === node && resolver.isDeclarationWithCollidingName(parent_8); } } return false; @@ -31301,20 +33626,23 @@ var ts; else if (isExpressionIdentifier(node)) { emitExpressionIdentifier(node); } - else if (isNameOfNestedRedeclaration(node)) { + else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { write(getGeneratedNameForNode(node)); } else if (ts.nodeIsSynthesized(node)) { write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } } function emitThis(node) { if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { write("_this"); } + else if (convertedLoopState) { + write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); + } else { write("this"); } @@ -31388,10 +33716,10 @@ var ts; } } function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 181 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { + if (node.parent.kind === 185 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { return true; } - else if (node.parent.kind === 182 /* ConditionalExpression */ && node.parent.condition === node) { + else if (node.parent.kind === 186 /* ConditionalExpression */ && node.parent.condition === node) { return true; } return false; @@ -31399,11 +33727,11 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 69 /* Identifier */: - case 164 /* ArrayLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 172 /* ParenthesizedExpression */: + case 168 /* ArrayLiteralExpression */: + case 170 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: + case 172 /* CallExpression */: + case 176 /* 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; @@ -31423,17 +33751,17 @@ var ts; write(", "); } var e = elements[pos]; - if (e.kind === 185 /* SpreadElementExpression */) { + if (e.kind === 189 /* SpreadElementExpression */) { e = e.expression; emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164 /* ArrayLiteralExpression */) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 168 /* ArrayLiteralExpression */) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 185 /* SpreadElementExpression */) { + while (i < length && elements[i].kind !== 189 /* SpreadElementExpression */) { i++; } write("["); @@ -31456,7 +33784,7 @@ var ts; } } function isSpreadElementExpression(node) { - return node.kind === 185 /* SpreadElementExpression */; + return node.kind === 189 /* SpreadElementExpression */; } function emitArrayLiteral(node) { var elements = node.elements; @@ -31465,11 +33793,11 @@ var ts; } else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) { write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces:*/ false); + emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces*/ false); write("]"); } else { - emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 1024 /* MultiLine */) !== 0, + emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ node.multiLine, /*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true); } } @@ -31485,10 +33813,10 @@ var ts; // then try to preserve the original shape of the object literal. // Otherwise just try to preserve the formatting. if (numElements === properties.length) { - emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= 1 /* ES5 */, /* spacesBetweenBraces */ true); + emitLinePreservingList(node, properties, /*allowTrailingComma*/ languageVersion >= 1 /* ES5 */, /*spacesBetweenBraces*/ true); } else { - var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; + var multiLine = node.multiLine; if (!multiLine) { write(" "); } @@ -31507,7 +33835,7 @@ var ts; write("}"); } function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; + var multiLine = node.multiLine; var properties = node.properties; write("("); if (multiLine) { @@ -31526,7 +33854,7 @@ var ts; writeComma(); var property = properties[i]; emitStart(property); - if (property.kind === 145 /* GetAccessor */ || property.kind === 146 /* SetAccessor */) { + if (property.kind === 147 /* GetAccessor */ || property.kind === 148 /* SetAccessor */) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { @@ -31578,13 +33906,13 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 245 /* PropertyAssignment */) { + if (property.kind === 249 /* PropertyAssignment */) { emit(property.initializer); } - else if (property.kind === 246 /* ShorthandPropertyAssignment */) { + else if (property.kind === 250 /* ShorthandPropertyAssignment */) { emitExpressionIdentifier(property.name); } - else if (property.kind === 143 /* MethodDeclaration */) { + else if (property.kind === 145 /* MethodDeclaration */) { emitFunctionDeclaration(property); } else { @@ -31618,7 +33946,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 === 136 /* ComputedPropertyName */) { + if (properties[i].name.kind === 138 /* ComputedPropertyName */) { numInitialNonComputedProperties = i; break; } @@ -31634,21 +33962,21 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(181 /* BinaryExpression */, startsOnNewLine); + var result = ts.createSynthesizedNode(185 /* BinaryExpression */, startsOnNewLine); result.operatorToken = ts.createSynthesizedNode(operator); result.left = left; result.right = right; return result; } function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(166 /* PropertyAccessExpression */); + var result = ts.createSynthesizedNode(170 /* PropertyAccessExpression */); result.expression = parenthesizeForAccess(expression); result.dotToken = ts.createSynthesizedNode(21 /* DotToken */); result.name = name; return result; } function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(167 /* ElementAccessExpression */); + var result = ts.createSynthesizedNode(171 /* ElementAccessExpression */); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; @@ -31656,7 +33984,7 @@ var ts; 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 === 171 /* TypeAssertionExpression */ || expr.kind === 189 /* AsExpression */) { + while (expr.kind === 175 /* TypeAssertionExpression */ || expr.kind === 193 /* AsExpression */) { expr = expr.expression; } // isLeftHandSideExpression is almost the correct criterion for when it is not necessary @@ -31668,11 +33996,11 @@ var ts; // 1.x -> not the same as (1).x // if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 169 /* NewExpression */ && + expr.kind !== 173 /* NewExpression */ && expr.kind !== 8 /* NumericLiteral */) { return expr; } - var node = ts.createSynthesizedNode(172 /* ParenthesizedExpression */); + var node = ts.createSynthesizedNode(176 /* ParenthesizedExpression */); node.expression = expr; return node; } @@ -31707,12 +34035,12 @@ var ts; // Return true if identifier resolves to an exported member of a namespace function isNamespaceExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 248 /* SourceFile */; + return container && container.kind !== 252 /* SourceFile */; } function emitShorthandPropertyAssignment(node) { // 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); + writeTextOfNode(currentText, 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 { @@ -31722,7 +34050,7 @@ var ts; // let obj = { y }; // } // Here we need to emit obj = { y : m.y } regardless of the output target. - if (languageVersion < 2 /* ES6 */ || isNamespaceExportReference(node.name)) { + if (modulekind !== ts.ModuleKind.ES6 || isNamespaceExportReference(node.name)) { // Emit identifier as an identifier write(": "); emit(node.name); @@ -31737,7 +34065,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 166 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 170 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -31748,7 +34076,7 @@ var ts; if (compilerOptions.isolatedModules) { return undefined; } - return node.kind === 166 /* PropertyAccessExpression */ || node.kind === 167 /* ElementAccessExpression */ + return node.kind === 170 /* PropertyAccessExpression */ || node.kind === 171 /* ElementAccessExpression */ ? resolver.getConstantValue(node) : undefined; } @@ -31775,15 +34103,23 @@ var ts; if (tryEmitConstantValue(node)) { return; } + if (languageVersion === 2 /* ES6 */ && + node.expression.kind === 95 /* SuperKeyword */ && + isInAsyncMethodWithSuperInES6(node)) { + var name_25 = ts.createSynthesizedNode(9 /* StringLiteral */); + name_25.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_25); + return; + } emit(node.expression); var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); // 1 .toString is a valid property access, emit a space after the literal // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal - var shouldEmitSpace; + var shouldEmitSpace = false; if (!indentedBeforeDot) { if (node.expression.kind === 8 /* NumericLiteral */) { // check if numeric literal was originally written with a dot - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); + var text = ts.getTextOfNodeFromSourceText(currentText, node.expression); shouldEmitSpace = text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; } else { @@ -31837,25 +34173,34 @@ var ts; } emitExpressionIdentifier(node); break; - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: emitQualifiedNameAsExpression(node, useFallback); break; + default: + emitNodeWithoutSourceMap(node); + break; } } function emitIndexedAccess(node) { if (tryEmitConstantValue(node)) { return; } + if (languageVersion === 2 /* ES6 */ && + node.expression.kind === 95 /* SuperKeyword */ && + isInAsyncMethodWithSuperInES6(node)) { + emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression); + return; + } emit(node.expression); write("["); emit(node.argumentExpression); write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 185 /* SpreadElementExpression */; }); + return ts.forEach(elements, function (e) { return e.kind === 189 /* SpreadElementExpression */; }); } function skipParentheses(node) { - while (node.kind === 172 /* ParenthesizedExpression */ || node.kind === 171 /* TypeAssertionExpression */ || node.kind === 189 /* AsExpression */) { + while (node.kind === 176 /* ParenthesizedExpression */ || node.kind === 175 /* TypeAssertionExpression */ || node.kind === 193 /* AsExpression */) { node = node.expression; } return node; @@ -31876,13 +34221,13 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 166 /* PropertyAccessExpression */) { + if (expr.kind === 170 /* PropertyAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 167 /* ElementAccessExpression */) { + else if (expr.kind === 171 /* ElementAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("["); @@ -31915,23 +34260,42 @@ var ts; emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ true); write(")"); } + function isInAsyncMethodWithSuperInES6(node) { + if (languageVersion === 2 /* ES6 */) { + var container = ts.getSuperContainer(node, /*includeFunctions*/ false); + if (container && resolver.getNodeCheckFlags(container) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */)) { + return true; + } + } + return false; + } + function emitSuperAccessInAsyncMethod(superNode, argumentExpression) { + var container = ts.getSuperContainer(superNode, /*includeFunctions*/ false); + var isSuperBinding = resolver.getNodeCheckFlags(container) & 4096 /* AsyncMethodWithSuperBinding */; + write("_super("); + emit(argumentExpression); + write(isSuperBinding ? ").value" : ")"); + } function emitCallExpression(node) { if (languageVersion < 2 /* ES6 */ && hasSpreadElement(node.arguments)) { emitCallWithSpread(node); return; } + var expression = node.expression; var superCall = false; - if (node.expression.kind === 95 /* SuperKeyword */) { - emitSuper(node.expression); + var isAsyncMethodWithSuper = false; + if (expression.kind === 95 /* SuperKeyword */) { + emitSuper(expression); superCall = true; } else { - emit(node.expression); - superCall = node.expression.kind === 166 /* PropertyAccessExpression */ && node.expression.expression.kind === 95 /* SuperKeyword */; + superCall = ts.isSuperPropertyOrElementAccess(expression); + isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node); + emit(expression); } - if (superCall && languageVersion < 2 /* ES6 */) { + if (superCall && (languageVersion < 2 /* ES6 */ || isAsyncMethodWithSuper)) { write(".call("); - emitThis(node.expression); + emitThis(expression); if (node.arguments.length) { write(", "); emitCommaList(node.arguments); @@ -31969,7 +34333,7 @@ var ts; write(".bind.apply("); emit(target); write(", [void 0].concat("); - emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiline*/ false, /*trailingComma*/ false, /*useConcat*/ false); + emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ false); write(")))"); write("()"); } @@ -31996,12 +34360,12 @@ var ts; // 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 !== 174 /* ArrowFunction */) { - if (node.expression.kind === 171 /* TypeAssertionExpression */ || node.expression.kind === 189 /* AsExpression */) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 178 /* ArrowFunction */) { + if (node.expression.kind === 175 /* TypeAssertionExpression */ || node.expression.kind === 193 /* AsExpression */) { var operand = node.expression.expression; // Make sure we consider all nested cast expressions, e.g.: // (-A).x; - while (operand.kind === 171 /* TypeAssertionExpression */ || operand.kind === 189 /* AsExpression */) { + while (operand.kind === 175 /* TypeAssertionExpression */ || operand.kind === 193 /* AsExpression */) { operand = operand.expression; } // We have an expression of the form: (SubExpr) @@ -32012,15 +34376,15 @@ 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 !== 179 /* PrefixUnaryExpression */ && - operand.kind !== 177 /* VoidExpression */ && - operand.kind !== 176 /* TypeOfExpression */ && - operand.kind !== 175 /* DeleteExpression */ && - operand.kind !== 180 /* PostfixUnaryExpression */ && - operand.kind !== 169 /* NewExpression */ && - !(operand.kind === 168 /* CallExpression */ && node.parent.kind === 169 /* NewExpression */) && - !(operand.kind === 173 /* FunctionExpression */ && node.parent.kind === 168 /* CallExpression */) && - !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 166 /* PropertyAccessExpression */)) { + if (operand.kind !== 183 /* PrefixUnaryExpression */ && + operand.kind !== 181 /* VoidExpression */ && + operand.kind !== 180 /* TypeOfExpression */ && + operand.kind !== 179 /* DeleteExpression */ && + operand.kind !== 184 /* PostfixUnaryExpression */ && + operand.kind !== 173 /* NewExpression */ && + !(operand.kind === 172 /* CallExpression */ && node.parent.kind === 173 /* NewExpression */) && + !(operand.kind === 177 /* FunctionExpression */ && node.parent.kind === 172 /* CallExpression */) && + !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 170 /* PropertyAccessExpression */)) { emit(operand); return; } @@ -32049,14 +34413,15 @@ var ts; if (!isCurrentFileSystemExternalModule() || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 /* VariableDeclaration */ || node.parent.kind === 163 /* BindingElement */); + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 215 /* VariableDeclaration */ || node.parent.kind === 167 /* BindingElement */); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, /*isExported*/ true); } function emitPrefixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + var exportChanged = (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) && + isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); if (exportChanged) { // emit // ++x @@ -32079,7 +34444,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 === 179 /* PrefixUnaryExpression */) { + if (node.operand.kind === 183 /* PrefixUnaryExpression */) { var operand = node.operand; if (node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) { write(" "); @@ -32133,12 +34498,12 @@ var ts; if (!node || !isCurrentFileSystemExternalModule()) { return false; } - var current = node; + var current = ts.getRootDeclaration(node).parent; while (current) { - if (current.kind === 248 /* SourceFile */) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 2 /* Export */) !== 0); + if (current.kind === 252 /* SourceFile */) { + return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 219 /* ModuleBlock */) { + else if (ts.isDeclaration(current)) { return false; } else { @@ -32153,19 +34518,19 @@ var ts; function emitExponentiationOperator(node) { var leftHandSideExpression = node.left; if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { - var synthesizedLHS; + var synthesizedLHS = void 0; var shouldEmitParentheses = false; if (ts.isElementAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(167 /* ElementAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false); + synthesizedLHS = ts.createSynthesizedNode(171 /* ElementAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ && leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) { var tempArgumentExpression = createAndRecordTempVariable(268435456 /* _i */); synthesizedLHS.argumentExpression = tempArgumentExpression; - emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true); + emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true, leftHandSideExpression.expression); } else { synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; @@ -32175,8 +34540,8 @@ var ts; else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { shouldEmitParentheses = true; write("("); - synthesizedLHS = ts.createSynthesizedNode(166 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); - var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false); + synthesizedLHS = ts.createSynthesizedNode(170 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; @@ -32203,8 +34568,8 @@ var ts; } function emitBinaryExpression(node) { if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 56 /* EqualsToken */ && - (node.left.kind === 165 /* ObjectLiteralExpression */ || node.left.kind === 164 /* ArrayLiteralExpression */)) { - emitDestructuring(node, node.parent.kind === 195 /* ExpressionStatement */); + (node.left.kind === 169 /* ObjectLiteralExpression */ || node.left.kind === 168 /* ArrayLiteralExpression */)) { + emitDestructuring(node, node.parent.kind === 199 /* ExpressionStatement */); } else { var exportChanged = node.operatorToken.kind >= 56 /* FirstAssignment */ && @@ -32269,7 +34634,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 192 /* Block */) { + if (node && node.kind === 196 /* Block */) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -32283,22 +34648,20 @@ var ts; } emitToken(15 /* OpenBraceToken */, node.pos); increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 219 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 218 /* ModuleDeclaration */); + if (node.kind === 223 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 222 /* ModuleDeclaration */); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 219 /* ModuleBlock */) { + if (node.kind === 223 /* ModuleBlock */) { emitTempDeclarations(/*newLine*/ true); } decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.statements.end); - scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 192 /* Block */) { + if (node.kind === 196 /* Block */) { write(" "); emit(node); } @@ -32310,7 +34673,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 174 /* ArrowFunction */); + emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 178 /* ArrowFunction */); write(";"); } function emitIfStatement(node) { @@ -32323,7 +34686,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(80 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 196 /* IfStatement */) { + if (node.elseStatement.kind === 200 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -32338,12 +34701,12 @@ var ts; function emitDoStatementWorker(node, loop) { write("do"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } - if (node.statement.kind === 192 /* Block */) { + if (node.statement.kind === 196 /* Block */) { write(" "); } else { @@ -32361,10 +34724,10 @@ var ts; emit(node.expression); write(")"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } /** @@ -32372,13 +34735,13 @@ var ts; * 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) { + function tryEmitStartOfVariableDeclarationList(decl) { if (shouldHoistVariable(decl, /*checkIfSourceFileLevelDecl*/ true)) { // variables in variable declaration list were already hoisted return false; } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576 /* BlockScoped */) === 0) { - // we are inside a converted loop - this can only happen in downlevel scenarios + if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 3072 /* BlockScoped */) === 0) { + // we are inside a converted loop - this can only happen in downlevel scenarios // record names for all variable declarations for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { var varDecl = _b[_a]; @@ -32386,32 +34749,23 @@ var ts; } return false; } - var tokenKind = 102 /* VarKeyword */; + emitStart(decl); if (decl && languageVersion >= 2 /* ES6 */) { if (ts.isLet(decl)) { - tokenKind = 108 /* LetKeyword */; + write("let "); } else if (ts.isConst(decl)) { - tokenKind = 74 /* ConstKeyword */; + write("const "); + } + else { + write("var "); } - } - if (startPos !== undefined) { - emitToken(tokenKind, startPos); - write(" "); } else { - switch (tokenKind) { - case 102 /* VarKeyword */: - write("var "); - break; - case 108 /* LetKeyword */: - write("let "); - break; - case 74 /* ConstKeyword */: - write("const "); - break; - } + write("var "); } + // Note here we specifically dont emit end so that if we are going to emit binding pattern + // we can alter the source map correctly return true; } function emitVariableDeclarationListSkippingUninitializedEntries(list) { @@ -32433,7 +34787,7 @@ var ts; } function shouldConvertLoopBody(node) { return languageVersion < 2 /* ES6 */ && - (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithBlockScopedBindingCapturedInFunction */) !== 0; + (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } function emitLoop(node, loopEmitter) { var shouldConvert = shouldConvertLoopBody(node); @@ -32442,7 +34796,7 @@ var ts; } else { var loop = convertLoopBody(node); - if (node.parent.kind === 207 /* LabeledStatement */) { + if (node.parent.kind === 211 /* LabeledStatement */) { // if parent of the loop was labeled statement - attach the label to loop skipping converted loop body emitLabelAndColon(node.parent); } @@ -32453,34 +34807,31 @@ var ts; var functionName = makeUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 216 /* VariableDeclarationList */) { loopInitializer = node.initializer; } break; } var loopParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 24576 /* BlockScoped */)) { + var loopOutParameters; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3072 /* BlockScoped */)) { // if loop initializer contains block scoped variables - they should be passed to converted loop body as parameters loopParameters = []; for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { var varDeclaration = _b[_a]; - collectNames(varDeclaration.name); + processVariableDeclaration(varDeclaration.name); } } - var bodyIsBlock = node.statement.kind === 192 /* Block */; + var bodyIsBlock = node.statement.kind === 196 /* Block */; var paramList = loopParameters ? loopParameters.join(", ") : ""; writeLine(); write("var " + functionName + " = function(" + paramList + ")"); - if (!bodyIsBlock) { - write(" {"); - writeLine(); - increaseIndent(); - } var convertedOuterLoopState = convertedLoopState; - convertedLoopState = {}; + convertedLoopState = { loopOutParameters: loopOutParameters }; if (convertedOuterLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through @@ -32489,20 +34840,45 @@ var ts; // use the same name in all nested loops convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; } + if (convertedOuterLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.thisName = convertedOuterLoopState.thisName; + } if (convertedOuterLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; } } - emitEmbeddedStatement(node.statement); - if (!bodyIsBlock) { - decreaseIndent(); - writeLine(); - write("}"); - } - write(";"); + write(" {"); writeLine(); + increaseIndent(); + if (bodyIsBlock) { + emitLines(node.statement.statements); + } + else { + emit(node.statement); + } + writeLine(); + // end of loop body -> copy out parameter + copyLoopOutParameters(convertedLoopState, 1 /* ToOutParameter */, /*emitAsStatements*/ true); + decreaseIndent(); + writeLine(); + write("};"); + writeLine(); + if (loopOutParameters) { + // declare variables to hold out params for loop body + write("var "); + for (var i = 0; i < loopOutParameters.length; i++) { + if (i !== 0) { + write(", "); + } + write(loopOutParameters[i].outParamName); + } + write(";"); + writeLine(); + } if (convertedLoopState.argumentsName) { // if alias for arguments is set if (convertedOuterLoopState) { @@ -32515,6 +34891,21 @@ var ts; writeLine(); } } + if (convertedLoopState.thisName) { + // if alias for this is set + if (convertedOuterLoopState) { + // pass it to outer converted loop + convertedOuterLoopState.thisName = convertedLoopState.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + write("var " + convertedLoopState.thisName + " = this;"); + writeLine(); + } + } if (convertedLoopState.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later if (convertedOuterLoopState) { @@ -32524,7 +34915,7 @@ var ts; else { // deduplicate and hoist collected variable declarations write("var "); - var seen; + var seen = void 0; for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { var id = _d[_c]; // Don't initialize seen unless we have at least one element. @@ -32547,15 +34938,21 @@ var ts; var currentLoopState = convertedLoopState; convertedLoopState = convertedOuterLoopState; return { functionName: functionName, paramList: paramList, state: currentLoopState }; - function collectNames(name) { + function processVariableDeclaration(name) { if (name.kind === 69 /* Identifier */) { - var nameText = isNameOfNestedRedeclaration(name) ? getGeneratedNameForNode(name) : name.text; + var nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(name) + ? getGeneratedNameForNode(name) + : name.text; loopParameters.push(nameText); + if (resolver.getNodeCheckFlags(name.parent) & 2097152 /* NeedsLoopOutParameter */) { + var reassignedVariable = { originalName: name, outParamName: makeUniqueName("out_" + nameText) }; + (loopOutParameters || (loopOutParameters = [])).push(reassignedVariable); + } } else { for (var _a = 0, _b = name.elements; _a < _b.length; _a++) { var element = _b[_a]; - collectNames(element.name); + processVariableDeclaration(element.name); } } } @@ -32571,7 +34968,7 @@ var ts; if (emitAsEmbeddedStatement) { emitEmbeddedStatement(node.statement); } - else if (node.statement.kind === 192 /* Block */) { + else if (node.statement.kind === 196 /* Block */) { emitLines(node.statement.statements); } else { @@ -32582,6 +34979,28 @@ var ts; convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; } } + function copyLoopOutParameters(state, copyDirection, emitAsStatements) { + if (state.loopOutParameters) { + for (var _a = 0, _b = state.loopOutParameters; _a < _b.length; _a++) { + var outParam = _b[_a]; + if (copyDirection === 0 /* ToOriginal */) { + emitIdentifier(outParam.originalName); + write(" = " + outParam.outParamName); + } + else { + write(outParam.outParamName + " = "); + emitIdentifier(outParam.originalName); + } + if (emitAsStatements) { + write(";"); + writeLine(); + } + else { + write(", "); + } + } + } + } function emitConvertedLoopCall(loop, emitAsBlock) { if (emitAsBlock) { write(" {"); @@ -32598,6 +35017,8 @@ var ts; write("var " + loopResult + " = "); } write(loop.functionName + "(" + loop.paramList + ");"); + writeLine(); + copyLoopOutParameters(loop.state, 0 /* ToOriginal */, /*emitAsStatements*/ true); if (!isSimpleLoop) { // for non simple loops we need to store result returned from converted loop function and use it to do dispatching // converted loop function can return: @@ -32615,7 +35036,7 @@ var ts; } else { // top level converted loop - return unwrapped value - write("return " + loopResult + ".value"); + write("return " + loopResult + ".value;"); } writeLine(); } @@ -32641,8 +35062,8 @@ var ts; } write("switch(" + loopResultVariable + ") {"); increaseIndent(); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /* isBreak */ true, loopResultVariable, outerLoop); - emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /* isBreak */ false, loopResultVariable, outerLoop); + emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /*isBreak*/ true, loopResultVariable, outerLoop); + emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /*isBreak*/ false, loopResultVariable, outerLoop); decreaseIndent(); writeLine(); write("}"); @@ -32657,7 +35078,7 @@ var ts; write("case \"" + labelMarker + "\": "); // if there are no outer converted loop or outer label in question is located inside outer converted loop // then emit labeled break\continue - // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { if (isBreak) { write("break "); @@ -32681,9 +35102,9 @@ var ts; var endPos = emitToken(86 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 216 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList); if (startIsEmitted) { emitCommaList(variableDeclarationList.declarations); } @@ -32700,14 +35121,14 @@ var ts; emitOptional(" ", node.incrementor); write(")"); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 /* ES6 */ && node.kind === 201 /* ForOfStatement */) { + if (languageVersion < 2 /* ES6 */ && node.kind === 205 /* ForOfStatement */) { emitLoop(node, emitDownLevelForOfStatementWorker); } else { @@ -32718,17 +35139,17 @@ var ts; var endPos = emitToken(86 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 216 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + tryEmitStartOfVariableDeclarationList(variableDeclarationList); emit(variableDeclarationList.declarations[0]); } } else { emit(node.initializer); } - if (node.kind === 200 /* ForInStatement */) { + if (node.kind === 204 /* ForInStatement */) { write(" in "); } else { @@ -32737,15 +35158,12 @@ var ts; emit(node.expression); emitToken(18 /* CloseParenToken */, node.expression.end); if (loop) { - emitConvertedLoopCall(loop, /* emitAsBlock */ true); + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ true); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); } } - function emitDownLevelForOfStatement(node) { - emitLoop(node, emitDownLevelForOfStatementWorker); - } function emitDownLevelForOfStatementWorker(node, loop) { // The following ES6 code: // @@ -32800,18 +35218,18 @@ var ts; emitEnd(node.expression); write("; "); // _i < _a.length; - emitStart(node.initializer); + emitStart(node.expression); emitNodeWithoutSourceMap(counter); write(" < "); emitNodeWithCommentsAndWithoutSourcemap(rhsReference); write(".length"); - emitEnd(node.initializer); + emitEnd(node.expression); write("; "); // _i++) - emitStart(node.initializer); + emitStart(node.expression); emitNodeWithoutSourceMap(counter); write("++"); - emitEnd(node.initializer); + emitEnd(node.expression); emitToken(18 /* CloseParenToken */, node.expression.end); // Body write(" {"); @@ -32821,7 +35239,7 @@ var ts; // let v = _a[_i]; var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 216 /* VariableDeclarationList */) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -32851,7 +35269,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, 56 /* EqualsToken */, rhsIterationValue, /*startsOnNewLine*/ false); - if (node.initializer.kind === 164 /* ArrayLiteralExpression */ || node.initializer.kind === 165 /* ObjectLiteralExpression */) { + if (node.initializer.kind === 168 /* ArrayLiteralExpression */ || node.initializer.kind === 169 /* 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, /*isAssignmentExpressionStatement*/ true, /*value*/ undefined); @@ -32864,10 +35282,10 @@ var ts; write(";"); if (loop) { writeLine(); - emitConvertedLoopCall(loop, /* emitAsBlock */ false); + emitConvertedLoopCall(loop, /*emitAsBlock*/ false); } else { - emitNormalLoopBody(node, /* emitAsEmbeddedStatement */ false); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ false); } writeLine(); decreaseIndent(); @@ -32879,36 +35297,39 @@ var ts; // it is possible if either // - break\continue is statement labeled and label is located inside the converted loop // - break\continue is non-labeled and located in non-converted loop\switch statement - var jump = node.kind === 203 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 207 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { + write("return "); + // explicit exit from loop -> copy out parameters + copyLoopOutParameters(convertedLoopState, 1 /* ToOutParameter */, /*emitAsStatements*/ false); if (!node.label) { - if (node.kind === 203 /* BreakStatement */) { + if (node.kind === 207 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; - write("return \"break\";"); + write("\"break\";"); } else { convertedLoopState.nonLocalJumps |= 4 /* Continue */; - write("return \"continue\";"); + write("\"continue\";"); } } else { - var labelMarker; - if (node.kind === 203 /* BreakStatement */) { + var labelMarker = void 0; + if (node.kind === 207 /* BreakStatement */) { labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, /* isBreak */ true, node.label.text, labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); } else { labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, /* isBreak */ false, node.label.text, labelMarker); + setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); } - write("return \"" + labelMarker + "\";"); + write("\"" + labelMarker + "\";"); } return; } } - emitToken(node.kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); + emitToken(node.kind === 207 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); emitOptional(" ", node.label); write(";"); } @@ -32962,19 +35383,19 @@ var ts; emitToken(16 /* CloseBraceToken */, node.clauses.end); } function nodeStartPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, node2.end); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end); } function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 241 /* CaseClause */) { + if (node.kind === 245 /* CaseClause */) { write("case "); emit(node.expression); write(":"); @@ -33043,7 +35464,7 @@ var ts; function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 218 /* ModuleDeclaration */); + } while (node && node.kind !== 222 /* ModuleDeclaration */); return node; } function emitContainingModuleName(node) { @@ -33052,13 +35473,13 @@ var ts; } function emitModuleMemberName(node) { emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 2 /* Export */) { + if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { var container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); write("."); } - else if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) { + else if (modulekind !== ts.ModuleKind.ES6 && modulekind !== ts.ModuleKind.System) { write("exports."); } } @@ -33068,22 +35489,22 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(8 /* NumericLiteral */); zero.text = "0"; - var result = ts.createSynthesizedNode(177 /* VoidExpression */); + var result = ts.createSynthesizedNode(181 /* VoidExpression */); result.expression = zero; return result; } function emitEs6ExportDefaultCompat(node) { - if (node.parent.kind === 248 /* SourceFile */) { - ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 227 /* ExportAssignment */); + if (node.parent.kind === 252 /* SourceFile */) { + ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 231 /* ExportAssignment */); // only allow export default at a source file level - if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) { - if (!currentSourceFile.symbol.exports["___esModule"]) { - if (languageVersion === 1 /* ES5 */) { + if (modulekind === ts.ModuleKind.CommonJS || modulekind === ts.ModuleKind.AMD || modulekind === ts.ModuleKind.UMD) { + if (!isEs6Module) { + if (languageVersion !== 0 /* ES3 */) { // default value of configurable, enumerable, writable are `false`. write("Object.defineProperty(exports, \"__esModule\", { value: true });"); writeLine(); } - else if (languageVersion === 0 /* ES3 */) { + else { write("exports.__esModule = true;"); writeLine(); } @@ -33092,11 +35513,11 @@ var ts; } } function emitExportMemberAssignment(node) { - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { writeLine(); emitStart(node); // emit call to exporter only for top level nodes - if (modulekind === 4 /* System */ && node.parent === currentSourceFile) { + if (modulekind === ts.ModuleKind.System && node.parent === currentSourceFile) { // emit export default as // export("default", ) write(exportFunctionForFile + "(\""); @@ -33131,7 +35552,7 @@ var ts; } } function emitExportMemberAssignments(name) { - if (modulekind === 4 /* System */) { + if (modulekind === ts.ModuleKind.System) { return; } if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { @@ -33150,7 +35571,7 @@ var ts; } } function emitExportSpecifierInSystemModule(specifier) { - ts.Debug.assert(modulekind === 4 /* System */); + ts.Debug.assert(modulekind === ts.ModuleKind.System); if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) { return; } @@ -33170,7 +35591,7 @@ var ts; * @param value an expression as a right-hand-side operand of the assignment * @param shouldEmitCommaBeforeAssignment a boolean indicating whether to prefix an assignment with comma */ - function emitAssignment(name, value, shouldEmitCommaBeforeAssignment) { + function emitAssignment(name, value, shouldEmitCommaBeforeAssignment, nodeForSourceMap) { if (shouldEmitCommaBeforeAssignment) { write(", "); } @@ -33180,15 +35601,21 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(name); write("\", "); } - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 /* VariableDeclaration */ || name.parent.kind === 163 /* BindingElement */); - if (isVariableDeclarationOrBindingElement) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 215 /* VariableDeclaration */ || name.parent.kind === 167 /* BindingElement */); + // If this is first var declaration, we need to start at var/let/const keyword instead + // otherwise use nodeForSourceMap as the start position + emitStart(isFirstVariableDeclaration(nodeForSourceMap) ? nodeForSourceMap.parent : nodeForSourceMap); + withTemporaryNoSourceMap(function () { + if (isVariableDeclarationOrBindingElement) { + emitModuleMemberName(name.parent); + } + else { + emit(name); + } + write(" = "); + emit(value); + }); + emitEnd(nodeForSourceMap, /*stopOverridingSpan*/ true); if (exportChanged) { write(")"); } @@ -33199,14 +35626,19 @@ var ts; * @param canDefineTempVariablesInPlace a boolean indicating whether you can define the temporary variable at an assignment location * @param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma */ - function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment) { + function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment, sourceMapNode) { var identifier = createTempVariable(0 /* Auto */); if (!canDefineTempVariablesInPlace) { recordTempDeclaration(identifier); } - emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment); + emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment, sourceMapNode || expression.parent); return identifier; } + function isFirstVariableDeclaration(root) { + return root.kind === 215 /* VariableDeclaration */ && + root.parent.kind === 216 /* VariableDeclarationList */ && + root.parent.declarations[0] === root; + } function emitDestructuring(root, isAssignmentExpressionStatement, value) { var emitCount = 0; // An exported declaration is actually emitted as an assignment (to a property on the module object), so @@ -33214,19 +35646,24 @@ 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 === 211 /* VariableDeclaration */) { - var isExported = ts.getCombinedNodeFlags(root) & 2 /* Export */; + if (root.kind === 215 /* VariableDeclaration */) { + var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } - else if (root.kind === 138 /* Parameter */) { + else if (root.kind === 140 /* Parameter */) { canDefineTempVariablesInPlace = true; } - if (root.kind === 181 /* BinaryExpression */) { + if (root.kind === 185 /* BinaryExpression */) { emitAssignmentExpression(root); } else { ts.Debug.assert(!isAssignmentExpressionStatement); + // If first variable declaration of variable statement correct the start location + if (isFirstVariableDeclaration(root)) { + // Use emit location of "var " as next emit start entry + sourceMap.changeEmitSourcePos(); + } emitBindingElement(root, value); } /** @@ -33238,27 +35675,28 @@ var ts; * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; * false if it is necessary to always emit an identifier. */ - function ensureIdentifier(expr, reuseIdentifierExpressions) { + function ensureIdentifier(expr, reuseIdentifierExpressions, sourceMapNode) { if (expr.kind === 69 /* Identifier */ && reuseIdentifierExpressions) { return expr; } - var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0); + var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0, sourceMapNode); emitCount++; return identifier; } - function createDefaultValueCheck(value, defaultValue) { + function createDefaultValueCheck(value, defaultValue, sourceMapNode) { // The value expression will be evaluated twice, so for anything but a simple identifier // we need to generate a temporary variable - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); + // If the temporary variable needs to be emitted use the source Map node for assignment of that statement + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); // Return the expression 'value === void 0 ? defaultValue : value' - var equals = ts.createSynthesizedNode(181 /* BinaryExpression */); + var equals = ts.createSynthesizedNode(185 /* BinaryExpression */); equals.left = value; equals.operatorToken = ts.createSynthesizedNode(32 /* EqualsEqualsEqualsToken */); equals.right = createVoidZero(); return createConditionalExpression(equals, defaultValue, value); } function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(182 /* ConditionalExpression */); + var cond = ts.createSynthesizedNode(186 /* ConditionalExpression */); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(53 /* QuestionToken */); cond.whenTrue = whenTrue; @@ -33272,17 +35710,28 @@ var ts; return node; } function createPropertyAccessForDestructuringProperty(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 !== 69 /* Identifier */) { - return createElementAccessExpression(object, syntheticName); + var index; + var nameIsComputed = propName.kind === 138 /* ComputedPropertyName */; + if (nameIsComputed) { + // TODO to handle when we look into sourcemaps for computed properties, for now use propName + index = ensureIdentifier(propName.expression, /*reuseIdentifierExpressions*/ false, propName); } - return createPropertyAccessExpression(object, syntheticName); + else { + // We create a synthetic copy of the identifier in order to avoid the rewriting that might + // otherwise occur when the identifier is emitted. + index = ts.createSynthesizedNode(propName.kind); + // We need to unescape identifier here because when parsing an identifier prefixing with "__" + // the parser need to append "_" in order to escape colliding with magic identifiers such as "__proto__" + // Therefore, in order to correctly emit identifiers that are written in original TypeScript file, + // we will unescapeIdentifier to remove additional underscore (if no underscore is added, the function will return original input string) + index.text = ts.unescapeIdentifier(propName.text); + } + return !nameIsComputed && index.kind === 69 /* Identifier */ + ? createPropertyAccessExpression(object, index) + : createElementAccessExpression(object, index); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(168 /* CallExpression */); + var call = ts.createSynthesizedNode(172 /* CallExpression */); var sliceIdentifier = ts.createSynthesizedNode(69 /* Identifier */); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -33290,60 +35739,65 @@ var ts; call.arguments[0] = createNumericLiteral(sliceIndex); return call; } - function emitObjectLiteralAssignment(target, value) { + function emitObjectLiteralAssignment(target, value, sourceMapNode) { var properties = target.properties; if (properties.length !== 1) { // For anything but a single element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); + // When doing so we want to highlight the passed in source map node since thats the one needing this temp assignment + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); } for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { var p = properties_5[_a]; - if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 249 /* PropertyAssignment */ || p.kind === 250 /* ShorthandPropertyAssignment */) { var propName = p.name; - var target_1 = p.kind === 246 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName)); + var target_1 = p.kind === 250 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; + // Assignment for target = value.propName should highlight whole property, hence use p as source map node + emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName), p); } } } - function emitArrayLiteralAssignment(target, value) { + function emitArrayLiteralAssignment(target, value, sourceMapNode) { var elements = target.elements; if (elements.length !== 1) { // For anything but a single element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); + // When doing so we want to highlight the passed in source map node since thats the one needing this temp assignment + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); } for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 187 /* OmittedExpression */) { - if (e.kind !== 185 /* SpreadElementExpression */) { - emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); + if (e.kind !== 191 /* OmittedExpression */) { + // Assignment for target = value.propName should highlight whole property, hence use e as source map node + if (e.kind !== 189 /* SpreadElementExpression */) { + emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e); } else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i)); + emitDestructuringAssignment(e.expression, createSliceCall(value, i), e); } } } } - function emitDestructuringAssignment(target, value) { - if (target.kind === 246 /* ShorthandPropertyAssignment */) { + function emitDestructuringAssignment(target, value, sourceMapNode) { + // When emitting target = value use source map node to highlight, including any temporary assignments needed for this + if (target.kind === 250 /* ShorthandPropertyAssignment */) { if (target.objectAssignmentInitializer) { - value = createDefaultValueCheck(value, target.objectAssignmentInitializer); + value = createDefaultValueCheck(value, target.objectAssignmentInitializer, sourceMapNode); } target = target.name; } - else if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { - value = createDefaultValueCheck(value, target.right); + else if (target.kind === 185 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + value = createDefaultValueCheck(value, target.right, sourceMapNode); target = target.left; } - if (target.kind === 165 /* ObjectLiteralExpression */) { - emitObjectLiteralAssignment(target, value); + if (target.kind === 169 /* ObjectLiteralExpression */) { + emitObjectLiteralAssignment(target, value, sourceMapNode); } - else if (target.kind === 164 /* ArrayLiteralExpression */) { - emitArrayLiteralAssignment(target, value); + else if (target.kind === 168 /* ArrayLiteralExpression */) { + emitArrayLiteralAssignment(target, value, sourceMapNode); } else { - emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0); + emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0, sourceMapNode); emitCount++; } } @@ -33354,25 +35808,32 @@ var ts; emit(value); } else if (isAssignmentExpressionStatement) { - emitDestructuringAssignment(target, value); + // Source map node for root.left = root.right is root + // but if root is synthetic, which could be in below case, use the target which is { a } + // for ({a} of {a: string}) { + // } + emitDestructuringAssignment(target, value, ts.nodeIsSynthesized(root) ? target : root); } else { - if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + if (root.parent.kind !== 176 /* ParenthesizedExpression */) { write("("); } - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); - emitDestructuringAssignment(target, value); + // Temporary assignment needed to emit root should highlight whole binary expression + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, root); + // Source map node for root.left = root.right is root + emitDestructuringAssignment(target, value, root); write(", "); emit(value); - if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + if (root.parent.kind !== 176 /* ParenthesizedExpression */) { write(")"); } } } function emitBindingElement(target, value) { + // Any temporary assignments needed to emit target = value should point to target if (target.initializer) { // Combine value and initializer - value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; + value = value ? createDefaultValueCheck(value, target.initializer, target) : target.initializer; } else if (!value) { // Use 'void 0' in absence of value and initializer @@ -33387,16 +35848,16 @@ var ts; // to ensure value is evaluated exactly once. Additionally, if we have zero elements // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, // so in that case, we'll intentionally create that temporary. - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0); + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target); } for (var i = 0; i < numElements; i++) { var element = elements[i]; - if (pattern.kind === 161 /* ObjectBindingPattern */) { + if (pattern.kind === 165 /* 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 !== 187 /* OmittedExpression */) { + else if (element.kind !== 191 /* OmittedExpression */) { if (!element.dotDotDotToken) { // Rewrite element to a declaration that accesses array element at index i emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); @@ -33408,7 +35869,7 @@ var ts; } } else { - emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0); + emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0, target); emitCount++; } } @@ -33425,19 +35886,46 @@ var ts; } else { var initializer = node.initializer; - if (!initializer && languageVersion < 2 /* ES6 */) { - // downlevel emit for non-initialized let bindings defined in loops - // for (...) { let x; } - // should be - // for (...) { var = void 0; } - // this is necessary to preserve ES6 semantic in scenarios like - // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations - var isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & 16384 /* BlockScopedBindingInLoop */) && - (getCombinedFlagsForIdentifier(node.name) & 8192 /* Let */); - // NOTE: default initialization should not be added to let bindings in for-in\for-of statements - if (isLetDefinedInLoop && - node.parent.parent.kind !== 200 /* ForInStatement */ && - node.parent.parent.kind !== 201 /* ForOfStatement */) { + if (!initializer && + languageVersion < 2 /* ES6 */ && + // for names - binding patterns that lack initializer there is no point to emit explicit initializer + // since downlevel codegen for destructuring will fail in the absence of initializer so all binding elements will say uninitialized + node.name.kind === 69 /* Identifier */) { + var container = ts.getEnclosingBlockScopeContainer(node); + var flags = resolver.getNodeCheckFlags(node); + // nested let bindings might need to be initialized explicitly to preserve ES6 semantic + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // NOTES: + // Top level bindings never collide with anything and thus don't require explicit initialization. + // As for nested let bindings there are two cases: + // - nested let bindings that were not renamed definitely should be initialized explicitly + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // Without explicit initialization code in /*1*/ can be executed even if some-condition is evaluated to false + // - renaming introduces fresh name that should not collide with any existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding declared inside loop body (but not in loop initializer) + // let x; + // for (;;) { + // let x; + // } + // in downlevel codegen inner 'x' will be renamed so it won't collide with outer 'x' however it will should be reset on every iteration + // as if it was declared anew. + // * Why non-captured binding - because if loop contains block scoped binding captured in some function then loop body will be rewritten + // to have a fresh scope on every iteration so everything will just work. + // * Why loop initializer is excluded - since we've introduced a fresh name it already will be undefined. + var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(container) || + (isCapturedInFunction && isDeclaredInLoop && container.kind === 196 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false)); + var emittedAsNestedLetDeclaration = ts.getCombinedNodeFlags(node) & 1024 /* Let */ && + !emittedAsTopLevel; + var emitExplicitInitializer = emittedAsNestedLetDeclaration && + container.kind !== 204 /* ForInStatement */ && + container.kind !== 205 /* ForOfStatement */ && + (!resolver.isDeclarationWithCollidingName(node) || + (isDeclaredInLoop && !isCapturedInFunction && !ts.isIterationStatement(container, /*lookInLabeledStatements*/ false))); + if (emitExplicitInitializer) { initializer = createVoidZero(); } } @@ -33455,7 +35943,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 187 /* OmittedExpression */) { + if (node.kind === 191 /* OmittedExpression */) { return; } var name = node.name; @@ -33466,20 +35954,14 @@ var ts; ts.forEach(name.elements, emitExportVariableAssignments); } } - function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 211 /* VariableDeclaration */ && node.parent.kind !== 163 /* BindingElement */)) { - return 0; - } - return ts.getCombinedNodeFlags(node.parent); - } function isES6ExportedDeclaration(node) { - return !!(node.flags & 2 /* Export */) && - modulekind === 5 /* ES6 */ && - node.parent.kind === 248 /* SourceFile */; + return !!(node.flags & 1 /* Export */) && + modulekind === ts.ModuleKind.ES6 && + node.parent.kind === 252 /* SourceFile */; } function emitVariableStatement(node) { var startIsEmitted = false; - if (node.flags & 2 /* Export */) { + if (node.flags & 1 /* Export */) { if (isES6ExportedDeclaration(node)) { // Exported ES6 module member write("export "); @@ -33499,14 +35981,14 @@ var ts; write(";"); } } - if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { 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 & 2 /* Export */)) { + if (!(node.flags & 1 /* Export */)) { return true; } // If we are exporting, but it's a top-level ES6 module exports, @@ -33526,12 +36008,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2 /* ES6 */) { if (ts.isBindingPattern(node.name)) { - var name_25 = createTempVariable(0 /* Auto */); + var name_26 = createTempVariable(0 /* Auto */); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_25); - emit(name_25); + tempParameters.push(name_26); + emit(name_26); } else { emit(node.name); @@ -33547,7 +36029,7 @@ var ts; } function emitDefaultValueAssignments(node) { if (languageVersion < 2 /* ES6 */) { - var tempIndex = 0; + var tempIndex_1 = 0; ts.forEach(node.parameters, function (parameter) { // A rest parameter cannot have a binding pattern or an initializer, // so let's just ignore it. @@ -33564,15 +36046,15 @@ var ts; writeLine(); write("var "); if (hasBindingElements) { - emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]); + emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex_1]); } else { - emit(tempParameters[tempIndex]); + emit(tempParameters[tempIndex_1]); write(" = "); emit(initializer); } write(";"); - tempIndex++; + tempIndex_1++; } } else if (initializer) { @@ -33636,12 +36118,12 @@ var ts; } } function emitAccessor(node) { - write(node.kind === 145 /* GetAccessor */ ? "get " : "set "); + write(node.kind === 147 /* GetAccessor */ ? "get " : "set "); emit(node.name); emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 174 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; + return node.kind === 178 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; } function emitDeclarationName(node) { if (node.name) { @@ -33652,13 +36134,13 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 173 /* FunctionExpression */) { + if (node.kind === 177 /* FunctionExpression */) { // Emit name if one is present return !!node.name; } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 217 /* 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 */; + return !!node.name || modulekind !== ts.ModuleKind.ES6; } } function emitFunctionDeclaration(node) { @@ -33667,20 +36149,29 @@ var ts; } // TODO (yuisu) : we should not have special cases to condition emitting comments // but have one place to fix check for these conditions. - if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */ && - node.parent && node.parent.kind !== 245 /* PropertyAssignment */ && - node.parent.kind !== 168 /* CallExpression */) { - // 1. Methods will emit the comments as part of emitting method declaration + var kind = node.kind, parent = node.parent; + if (kind !== 145 /* MethodDeclaration */ && + kind !== 144 /* MethodSignature */ && + parent && + parent.kind !== 249 /* PropertyAssignment */ && + parent.kind !== 172 /* CallExpression */ && + parent.kind !== 168 /* ArrayLiteralExpression */) { + // 1. Methods will emit comments at their assignment declaration sites. + // // 2. If the function is a property of object literal, emitting leading-comments - // is done by emitNodeWithoutSourceMap which then call this function. - // In particular, we would like to avoid emit comments twice in following case: - // For example: + // is done by emitNodeWithoutSourceMap which then call this function. + // In particular, we would like to avoid emit comments twice in following case: + // // var obj = { // id: // /*comment*/ () => void // } + // // 3. If the function is an argument in call expression, emitting of comments will be - // taken care of in emit list of arguments inside of emitCallexpression + // taken care of in emit list of arguments inside of 'emitCallExpression'. + // + // 4. If the function is in an array literal, 'emitLinePreservingList' will take care + // of leading comments. emitLeadingComments(node); } emitStart(node); @@ -33703,11 +36194,11 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (modulekind !== 5 /* ES6 */ && node.kind === 213 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { + if (modulekind !== ts.ModuleKind.ES6 && kind === 217 /* FunctionDeclaration */ && parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } emitEnd(node); - if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) { + if (kind !== 145 /* MethodDeclaration */ && kind !== 144 /* MethodSignature */) { emitTrailingComments(node); } } @@ -33740,9 +36231,8 @@ var ts; } function emitAsyncFunctionBodyForES6(node) { var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); - var isArrowFunction = node.kind === 174 /* ArrowFunction */; - var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096 /* CaptureArguments */) !== 0; - var args; + var isArrowFunction = node.kind === 178 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current // `this` and `arguments` objects to `__awaiter`. The generator function @@ -33820,29 +36310,31 @@ var ts; write(" {"); increaseIndent(); writeLine(); + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + writeLines("\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"); + writeLine(); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + write("const _super = name => super[name];"); + writeLine(); + } write("return"); } write(" __awaiter(this"); if (hasLexicalArguments) { - write(", arguments"); + write(", arguments, "); } else { - write(", void 0"); + write(", void 0, "); } - if (promiseConstructor) { - write(", "); - emitNodeWithoutSourceMap(promiseConstructor); + if (languageVersion >= 2 /* ES6 */ || !promiseConstructor) { + write("void 0"); } else { - write(", Promise"); + emitEntityNameAsExpression(promiseConstructor, /*useFallback*/ false); } // Emit the call to __awaiter. - if (hasLexicalArguments) { - write(", function* (_arguments)"); - } - else { - write(", function* ()"); - } + write(", function* ()"); // Emit the signature and body for the inner generator function. emitFunctionBody(node); write(")"); @@ -33861,7 +36353,7 @@ var ts; write(" { }"); } else { - if (node.body.kind === 192 /* Block */) { + if (node.body.kind === 196 /* Block */) { emitBlockFunctionBody(node, node.body); } else { @@ -33887,7 +36379,7 @@ var ts; emitSignatureParameters(node); } var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync && languageVersion === 2 /* ES6 */) { + if (isAsync) { emitAsyncFunctionBodyForES6(node); } else { @@ -33920,14 +36412,13 @@ var ts; write(" "); // Unwrap all type assertions. var current = body; - while (current.kind === 171 /* TypeAssertionExpression */) { + while (current.kind === 175 /* TypeAssertionExpression */) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 165 /* ObjectLiteralExpression */); + emitParenthesizedIf(body, current.kind === 169 /* ObjectLiteralExpression */); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); emitDetachedCommentsAndUpdateCommentsInfo(node.body); @@ -33950,8 +36441,10 @@ var ts; increaseIndent(); writeLine(); emitLeadingComments(node.body); + emitStart(body); write("return "); emit(body); + emitEnd(body); write(";"); emitTrailingComments(node.body); emitTempDeclarations(/*newLine*/ true); @@ -33961,11 +36454,9 @@ var ts; emitStart(node.body); write("}"); emitEnd(node.body); - scopeEmitEnd(); } function emitBlockFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); emitDetachedCommentsAndUpdateCommentsInfo(body.statements); @@ -33994,25 +36485,28 @@ var ts; decreaseIndent(); } emitToken(16 /* CloseBraceToken */, body.statements.end); - scopeEmitEnd(); } - function findInitialSuperCall(ctor) { - if (ctor.body) { - var statement = ctor.body.statements[0]; - if (statement && statement.kind === 195 /* ExpressionStatement */) { - var expr = statement.expression; - if (expr && expr.kind === 168 /* CallExpression */) { - var func = expr.expression; - if (func && func.kind === 95 /* SuperKeyword */) { - return statement; - } - } - } + /** + * Return the statement at a given index if it is a super-call statement + * @param ctor a constructor declaration + * @param index an index to constructor's body to check + */ + function getSuperCallAtGivenIndex(ctor, index) { + if (!ctor.body) { + return undefined; + } + var statements = ctor.body.statements; + if (!statements || index >= statements.length) { + return undefined; + } + var statement = statements[index]; + if (statement.kind === 199 /* ExpressionStatement */) { + return ts.isSuperCallExpression(statement.expression) ? statement : undefined; } } function emitParameterPropertyAssignments(node) { ts.forEach(node.parameters, function (param) { - if (param.flags & 56 /* AccessibilityModifier */) { + if (param.flags & 28 /* AccessibilityModifier */) { writeLine(); emitStart(param); emitStart(param.name); @@ -34035,7 +36529,7 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(memberName); write("]"); } - else if (memberName.kind === 136 /* ComputedPropertyName */) { + else if (memberName.kind === 138 /* ComputedPropertyName */) { emitComputedPropertyName(memberName); } else { @@ -34047,7 +36541,7 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 141 /* PropertyDeclaration */ && isStatic === ((member.flags & 64 /* Static */) !== 0) && member.initializer) { + if (member.kind === 143 /* PropertyDeclaration */ && isStatic === ((member.flags & 32 /* Static */) !== 0) && member.initializer) { properties.push(member); } } @@ -34068,7 +36562,7 @@ var ts; emit(receiver); } else { - if (property.flags & 64 /* Static */) { + if (property.flags & 32 /* Static */) { emitDeclarationName(node); } else { @@ -34087,11 +36581,11 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 191 /* SemicolonClassElement */) { + if (member.kind === 195 /* SemicolonClassElement */) { writeLine(); write(";"); } - else if (member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) { + else if (member.kind === 145 /* MethodDeclaration */ || node.kind === 144 /* MethodSignature */) { if (!member.body) { return emitCommentsOnNotEmittedNode(member); } @@ -34108,7 +36602,7 @@ var ts; write(";"); emitTrailingComments(member); } - else if (member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) { + else if (member.kind === 147 /* GetAccessor */ || member.kind === 148 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); @@ -34158,22 +36652,22 @@ var ts; function emitMemberFunctionsForES6AndHigher(node) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) && !member.body) { + if ((member.kind === 145 /* MethodDeclaration */ || node.kind === 144 /* MethodSignature */) && !member.body) { emitCommentsOnNotEmittedNode(member); } - else if (member.kind === 143 /* MethodDeclaration */ || - member.kind === 145 /* GetAccessor */ || - member.kind === 146 /* SetAccessor */) { + else if (member.kind === 145 /* MethodDeclaration */ || + member.kind === 147 /* GetAccessor */ || + member.kind === 148 /* SetAccessor */) { writeLine(); emitLeadingComments(member); emitStart(member); - if (member.flags & 64 /* Static */) { + if (member.flags & 32 /* Static */) { write("static "); } - if (member.kind === 145 /* GetAccessor */) { + if (member.kind === 147 /* GetAccessor */) { write("get "); } - else if (member.kind === 146 /* SetAccessor */) { + else if (member.kind === 148 /* SetAccessor */) { write("set "); } if (member.asteriskToken) { @@ -34184,7 +36678,7 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 191 /* SemicolonClassElement */) { + else if (member.kind === 195 /* SemicolonClassElement */) { writeLine(); write(";"); } @@ -34213,11 +36707,11 @@ var ts; var hasInstancePropertyWithInitializer = false; // Emit the constructor overload pinned comments ts.forEach(node.members, function (member) { - if (member.kind === 144 /* Constructor */ && !member.body) { + if (member.kind === 146 /* Constructor */ && !member.body) { emitCommentsOnNotEmittedNode(member); } // Check if there is any non-static property assignment - if (member.kind === 141 /* PropertyDeclaration */ && member.initializer && (member.flags & 64 /* Static */) === 0) { + if (member.kind === 143 /* PropertyDeclaration */ && member.initializer && (member.flags & 32 /* Static */) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -34258,7 +36752,6 @@ var ts; } var startIndex = 0; write(" {"); - scopeEmitStart(node, "constructor"); increaseIndent(); if (ctor) { // Emit all the directive prologues (like "use strict"). These have to come before @@ -34272,7 +36765,7 @@ var ts; emitDefaultValueAssignments(ctor); emitRestParameter(ctor); if (baseTypeElement) { - superCall = findInitialSuperCall(ctor); + superCall = getSuperCallAtGivenIndex(ctor, startIndex); if (superCall) { writeLine(); emit(superCall); @@ -34293,7 +36786,7 @@ var ts; emitEnd(baseTypeElement); } } - emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false)); + emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ false)); if (ctor) { var statements = ctor.body.statements; if (superCall) { @@ -34308,7 +36801,6 @@ var ts; } decreaseIndent(); emitToken(16 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); emitEnd(ctor || node); if (ctor) { emitTrailingComments(ctor); @@ -34327,68 +36819,108 @@ var ts; else { emitClassLikeDeclarationForES6AndHigher(node); } - if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile && node.name) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } } function emitClassLikeDeclarationForES6AndHigher(node) { + var decoratedClassAlias; var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* 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: + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. // - // * For a local class declaration: + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: // - // @dec class C { - // } + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------|------------------------------------ + // @dec | export let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // [Example 1] // - // The emit should be: + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. // - // let C = class { - // }; - // C = __decorate([dec], C); + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: // - // * For an exported class declaration: + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let C_1; + // class C { | let C = C_1 = class C { + // static x() { return C.y; } | static x() { return C_1.y; } + // static y = 1; | } + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // --------------------------------|------------------------------------ + // @dec | let C_1; + // export class C { | export let C = C_1 = class C { + // static x() { return C.y; } | static x() { return C_1.y; } + // static y = 1; | } + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // --------------------------------------------------------------------- + // [Example 2] // - // @dec export class C { - // } + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: // - // The emit should be: + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------|------------------------------------ + // @dec | let C = class C { + // export default class { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // [Example 3] // - // export let C = class { - // }; - // C = __decorate([dec], C); + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: // - // * For a default export of a class declaration with a name: - // - // @dec default export class C { - // } - // - // The emit should be: - // - // let C = class { - // } - // C = __decorate([dec], C); - // export default C; - // - // * For a default export of a class declaration without a name: - // - // @dec default export class { - // } - // - // The emit should be: - // - // let _default = class { - // } - // _default = __decorate([dec], _default); - // export default _default; + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let C_1; + // export default class C { | let C = C_1 = class C { + // static x() { return C.y; } | static x() { return C_1.y; } + // static y = 1; | } + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // [Example 4] // + if (resolver.getNodeCheckFlags(node) & 524288 /* ClassWithBodyScopedClassBinding */) { + decoratedClassAlias = ts.unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default")); + decoratedClassAliases[ts.getNodeId(node)] = decoratedClassAlias; + write("let " + decoratedClassAlias + ";"); + writeLine(); + } if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */)) { write("export "); } write("let "); emitDeclarationName(node); + if (decoratedClassAlias !== undefined) { + write(" = " + decoratedClassAlias); + } write(" = "); } else if (isES6ExportedDeclaration(node)) { @@ -34409,8 +36941,8 @@ 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, /*static:*/ true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186 /* ClassExpression */; + var staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 190 /* ClassExpression */; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0 /* Auto */); @@ -34423,7 +36955,7 @@ var ts; // emit name if // - node has a name // - this is default export with static initializers - if ((node.name || (node.flags & 512 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if (node.name || (node.flags & 512 /* Default */ && (staticProperties.length > 0 || modulekind !== ts.ModuleKind.ES6) && !thisNodeIsDecorated)) { write(" "); emitDeclarationName(node); } @@ -34434,23 +36966,14 @@ var ts; } write(" {"); increaseIndent(); - scopeEmitStart(node); writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES6AndHigher(node); decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); - // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now. - // For a decorated class, we need to assign its name (if it has one). This is because we emit - // the class as a class expression to avoid the double-binding of the identifier: - // - // let C = class { - // } - // Object.defineProperty(C, "name", { value: "C", configurable: true }); - // if (thisNodeIsDecorated) { + decoratedClassAliases[ts.getNodeId(node)] = undefined; write(";"); } // Emit static property assignment. Because classDeclaration is lexically evaluated, @@ -34463,7 +36986,7 @@ var ts; var property = staticProperties_1[_a]; write(","); writeLine(); - emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true); + emitPropertyDeclaration(node, property, /*receiver*/ tempVariable, /*isExpression*/ true); } write(","); writeLine(); @@ -34474,29 +36997,39 @@ var ts; else { writeLine(); emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node); + emitDecoratorsOfClass(node, decoratedClassAlias); } - // If this is an exported class, but not on the top level (i.e. on an internal - // module), export it - if (!isES6ExportedDeclaration(node) && (node.flags & 2 /* Export */)) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); + if (!(node.flags & 1 /* Export */)) { + return; } - else if (isES6ExportedDeclaration(node) && (node.flags & 512 /* Default */) && thisNodeIsDecorated) { - // if this is a top level default export of decorated class, write the export after the declaration. - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); + if (modulekind !== ts.ModuleKind.ES6) { + emitExportMemberAssignment(node); + } + else { + // If this is an exported class, but not on the top level (i.e. on an internal + // module), export it + if (node.flags & 512 /* Default */) { + // if this is a top level default export of decorated class, write the export after the declaration. + if (thisNodeIsDecorated) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } + } + else if (node.parent.kind !== 252 /* SourceFile */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emitDeclarationName(node); + emitEnd(node); + write(";"); + } } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* ClassDeclaration */) { // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -34521,7 +37054,6 @@ var ts; tempParameters = undefined; computedPropertyNamesToGeneratedNames = undefined; increaseIndent(); - scopeEmitStart(node); if (baseTypeNode) { writeLine(); emitStart(baseTypeNode); @@ -34533,9 +37065,9 @@ var ts; writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ true)); + emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ true)); writeLine(); - emitDecoratorsOfClass(node); + emitDecoratorsOfClass(node, /*decoratedClassAlias*/ undefined); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end, function () { write("return "); @@ -34552,38 +37084,37 @@ var ts; decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); emitStart(node); - write(")("); + write("("); if (baseTypeNode) { emit(baseTypeNode.expression); } - write(")"); - if (node.kind === 214 /* ClassDeclaration */) { + write("))"); + if (node.kind === 218 /* ClassDeclaration */) { write(";"); } emitEnd(node); - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* ClassDeclaration */) { emitExportMemberAssignment(node); } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); - if (!(member.flags & 64 /* Static */)) { + if (!(member.flags & 32 /* Static */)) { write(".prototype"); } } - function emitDecoratorsOfClass(node) { + function emitDecoratorsOfClass(node, decoratedClassAlias) { emitDecoratorsOfMembers(node, /*staticFlag*/ 0); - emitDecoratorsOfMembers(node, 64 /* Static */); - emitDecoratorsOfConstructor(node); + emitDecoratorsOfMembers(node, 32 /* Static */); + emitDecoratorsOfConstructor(node, decoratedClassAlias); } - function emitDecoratorsOfConstructor(node) { + function emitDecoratorsOfConstructor(node, decoratedClassAlias) { var decorators = node.decorators; var constructor = ts.getFirstConstructorWithBody(node); - var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); + var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); // skip decoration of the constructor if neither it nor its parameters are decorated - if (!decorators && !hasDecoratedParameters) { + if (!decorators && !firstParameterDecorator) { return; } // Emit the call to __decorate. Given the class: @@ -34597,42 +37128,40 @@ var ts; // C = __decorate([dec], C); // writeLine(); - emitStart(node); + emitStart(node.decorators || firstParameterDecorator); emitDeclarationName(node); + if (decoratedClassAlias !== undefined) { + write(" = " + decoratedClassAlias); + } write(" = __decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); + } emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0); decreaseIndent(); writeLine(); write("], "); emitDeclarationName(node); - write(");"); - emitEnd(node); + write(")"); + emitEnd(node.decorators || firstParameterDecorator); + write(";"); writeLine(); } function emitDecoratorsOfMembers(node, staticFlag) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; // only emit members in the correct group - if ((member.flags & 64 /* Static */) !== staticFlag) { + if ((member.flags & 32 /* Static */) !== staticFlag) { continue; } // skip members that cannot be decorated (such as the constructor) if (!ts.nodeCanBeDecorated(member)) { continue; } - // skip a member if it or any of its parameters are not decorated - if (!ts.nodeOrChildIsDecorated(member)) { - continue; - } // skip an accessor declaration if it is not the first accessor var decorators = void 0; var functionLikeMember = void 0; @@ -34652,10 +37181,15 @@ var ts; else { decorators = member.decorators; // we only decorate the parameters here if this is a method - if (member.kind === 143 /* MethodDeclaration */) { + if (member.kind === 145 /* MethodDeclaration */) { functionLikeMember = member; } } + var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); + // skip a member if it or any of its parameters are not decorated + if (!decorators && !firstParameterDecorator) { + continue; + } // Emit the call to __decorate. Given the following: // // class C { @@ -34687,28 +37221,24 @@ var ts; // ], C.prototype, "prop"); // writeLine(); - emitStart(member); + emitStart(decorators || firstParameterDecorator); write("__decorate(["); increaseIndent(); writeLine(); var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + } emitSerializedTypeMetadata(member, argumentsWritten > 0); decreaseIndent(); writeLine(); write("], "); - emitStart(member.name); emitClassMemberPrefix(node, member); write(", "); emitExpressionForPropertyName(member.name); - emitEnd(member.name); if (languageVersion > 0 /* ES3 */) { - if (member.kind !== 141 /* PropertyDeclaration */) { + if (member.kind !== 143 /* PropertyDeclaration */) { // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. // We have this extra argument here so that we can inject an explicit property descriptor at a later date. write(", null"); @@ -34719,29 +37249,28 @@ var ts; write(", void 0"); } } - write(");"); - emitEnd(member); + write(")"); + emitEnd(decorators || firstParameterDecorator); + write(";"); writeLine(); } } function emitDecoratorsOfParameters(node, leadingComma) { var argumentsWritten = 0; if (node) { - var parameterIndex = 0; + var parameterIndex_1 = 0; for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) { var parameter = _b[_a]; if (ts.nodeIsDecorated(parameter)) { var decorators = parameter.decorators; argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, function (decorator) { - emitStart(decorator); - write("__param(" + parameterIndex + ", "); + write("__param(" + parameterIndex_1 + ", "); emit(decorator.expression); write(")"); - emitEnd(decorator); }); leadingComma = true; } - ++parameterIndex; + parameterIndex_1++; } } return argumentsWritten; @@ -34751,10 +37280,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 143 /* MethodDeclaration */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 141 /* PropertyDeclaration */: + case 145 /* MethodDeclaration */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 143 /* PropertyDeclaration */: return true; } return false; @@ -34764,7 +37293,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 143 /* MethodDeclaration */: + case 145 /* MethodDeclaration */: return true; } return false; @@ -34774,9 +37303,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 214 /* ClassDeclaration */: - case 143 /* MethodDeclaration */: - case 146 /* SetAccessor */: + case 218 /* ClassDeclaration */: + case 145 /* MethodDeclaration */: + case 148 /* SetAccessor */: return true; } return false; @@ -34794,19 +37323,19 @@ var ts; // // For rules on serializing type annotations, see `serializeTypeNode`. switch (node.kind) { - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: write("Function"); return; - case 141 /* PropertyDeclaration */: + case 143 /* PropertyDeclaration */: emitSerializedTypeNode(node.type); return; - case 138 /* Parameter */: + case 140 /* Parameter */: emitSerializedTypeNode(node.type); return; - case 145 /* GetAccessor */: + case 147 /* GetAccessor */: emitSerializedTypeNode(node.type); return; - case 146 /* SetAccessor */: + case 148 /* SetAccessor */: emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); return; } @@ -34822,39 +37351,40 @@ var ts; case 103 /* VoidKeyword */: write("void 0"); return; - case 160 /* ParenthesizedType */: + case 162 /* ParenthesizedType */: emitSerializedTypeNode(node.type); return; - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: write("Function"); return; - case 156 /* ArrayType */: - case 157 /* TupleType */: + case 158 /* ArrayType */: + case 159 /* TupleType */: write("Array"); return; - case 150 /* TypePredicate */: + case 152 /* TypePredicate */: case 120 /* BooleanKeyword */: write("Boolean"); return; - case 130 /* StringKeyword */: - case 9 /* StringLiteral */: + case 131 /* StringKeyword */: + case 164 /* StringLiteralType */: write("String"); return; - case 128 /* NumberKeyword */: + case 129 /* NumberKeyword */: write("Number"); return; - case 131 /* SymbolKeyword */: + case 132 /* SymbolKeyword */: write("Symbol"); return; - case 151 /* TypeReference */: + case 153 /* TypeReference */: emitSerializedTypeReferenceNode(node); return; - case 154 /* TypeQuery */: - case 155 /* TypeLiteral */: - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 156 /* TypeQuery */: + case 157 /* TypeLiteral */: + case 160 /* UnionType */: + case 161 /* IntersectionType */: case 117 /* AnyKeyword */: + case 163 /* ThisType */: break; default: ts.Debug.fail("Cannot serialize unexpected type node."); @@ -34870,8 +37400,7 @@ var ts; location = location.parent; } // Clone the type name and parent it to a location outside of the current declaration. - var typeName = ts.cloneEntityName(node.typeName); - typeName.parent = location; + var typeName = ts.cloneEntityName(node.typeName, location); var result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case ts.TypeReferenceSerializationKind.Unknown: @@ -34927,8 +37456,8 @@ var ts; // // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. if (node) { - var valueDeclaration; - if (node.kind === 214 /* ClassDeclaration */) { + var valueDeclaration = void 0; + if (node.kind === 218 /* ClassDeclaration */) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -34944,10 +37473,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 156 /* ArrayType */) { + if (parameterType.kind === 158 /* ArrayType */) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 151 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType.kind === 153 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -35023,9 +37552,10 @@ var ts; } if (!shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted - if (!(node.flags & 2 /* Export */) || isES6ExportedDeclaration(node)) { + var isES6ExportedEnum = isES6ExportedDeclaration(node); + if (!(node.flags & 1 /* Export */) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 221 /* EnumDeclaration */))) { emitStart(node); - if (isES6ExportedDeclaration(node)) { + if (isES6ExportedEnum) { write("export "); } write("var "); @@ -35042,19 +37572,17 @@ var ts; emitEnd(node.name); write(") {"); increaseIndent(); - scopeEmitStart(node); emitLines(node.members); decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); write(")("); emitModuleMemberName(node); write(" || ("); emitModuleMemberName(node); write(" = {}));"); emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 2 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { + if (!isES6ExportedDeclaration(node) && node.flags & 1 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted writeLine(); emitStart(node); @@ -35065,8 +37593,8 @@ var ts; emitEnd(node); write(";"); } - if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) { - if (modulekind === 4 /* System */ && (node.flags & 2 /* Export */)) { + if (modulekind !== ts.ModuleKind.ES6 && node.parent === currentSourceFile) { + if (modulekind === ts.ModuleKind.System && (node.flags & 1 /* Export */)) { // write the call to exporter for enum writeLine(); write(exportFunctionForFile + "(\""); @@ -35107,7 +37635,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 222 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -35118,6 +37646,9 @@ var ts; function isModuleMergedWithES6Class(node) { return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 32768 /* LexicalModuleMergesWithClass */); } + function isFirstDeclarationOfKind(node, declarations, kind) { + return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); + } function emitModuleDeclaration(node) { // Emit only if this module is non-ambient. var shouldEmit = shouldEmitModuleDeclaration(node); @@ -35127,15 +37658,18 @@ var ts; var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); + var isES6ExportedNamespace = isES6ExportedDeclaration(node); + if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 222 /* ModuleDeclaration */)) { + emitStart(node); + if (isES6ExportedNamespace) { + write("export "); + } + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); } emitStart(node); write("(function ("); @@ -35143,7 +37677,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 219 /* ModuleBlock */) { + if (node.body.kind === 223 /* ModuleBlock */) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; @@ -35159,7 +37693,6 @@ var ts; else { write("{"); increaseIndent(); - scopeEmitStart(node); emitCaptureThisForNodeIfNecessary(node); writeLine(); emit(node.body); @@ -35167,11 +37700,10 @@ var ts; writeLine(); var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(16 /* CloseBraceToken */, moduleBlock.statements.end); - scopeEmitEnd(); } write(")("); // write moduleDecl = containingModule.m only if it is not exported es6 module member - if ((node.flags & 2 /* Export */) && !isES6ExportedDeclaration(node)) { + if ((node.flags & 1 /* Export */) && !isES6ExportedDeclaration(node)) { emit(node.name); write(" = "); } @@ -35181,7 +37713,7 @@ var ts; write(" = {}));"); emitEnd(node); if (!isES6ExportedDeclaration(node) && node.name.kind === 69 /* Identifier */ && node.parent === currentSourceFile) { - if (modulekind === 4 /* System */ && (node.flags & 2 /* Export */)) { + if (modulekind === ts.ModuleKind.System && (node.flags & 1 /* Export */)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -35197,8 +37729,8 @@ var ts; * Here we check if alternative name was provided for a given moduleName and return it if possible. */ function tryRenameExternalModule(moduleName) { - if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) { - return "\"" + currentSourceFile.renamedDependencies[moduleName.text] + "\""; + if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { + return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; } @@ -35221,16 +37753,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 225 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 228 /* NamespaceImport */) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 222 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 226 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -35239,7 +37771,7 @@ var ts; ts.forEachChild(node, emitExportImportAssignments); } function emitImportDeclaration(node) { - if (modulekind !== 5 /* ES6 */) { + if (modulekind !== ts.ModuleKind.ES6) { return emitExternalImportDeclaration(node); } // ES6 import @@ -35258,7 +37790,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 228 /* NamespaceImport */) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -35284,16 +37816,19 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 2 /* Export */) !== 0; + var isExportedImport = node.kind === 225 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); - if (modulekind !== 2 /* AMD */) { + var varOrConst = (languageVersion <= 1 /* ES5 */) ? "var " : "const "; + if (modulekind !== ts.ModuleKind.AMD) { emitLeadingComments(node); emitStart(node); if (namespaceDeclaration && !isDefaultImport(node)) { // import x = require("foo") // import * as x from "foo" - if (!isExportedImport) - write("var "); + if (!isExportedImport) { + write(varOrConst); + } + ; emitModuleMemberName(namespaceDeclaration); write(" = "); } @@ -35303,9 +37838,9 @@ var ts; // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - var isNakedImport = 222 /* ImportDeclaration */ && !node.importClause; + var isNakedImport = 226 /* ImportDeclaration */ && !node.importClause; if (!isNakedImport) { - write("var "); + write(varOrConst); write(getGeneratedNameForNode(node)); write(" = "); } @@ -35332,7 +37867,7 @@ var ts; } else if (namespaceDeclaration && isDefaultImport(node)) { // import d, * as x from "foo" - write("var "); + write(varOrConst); emitModuleMemberName(namespaceDeclaration); write(" = "); write(getGeneratedNameForNode(node)); @@ -35351,7 +37886,7 @@ var ts; // - current file is not external module // - import declaration is top level and target is value imported by entity name if (resolver.isReferencedAliasDeclaration(node) || - (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { + (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { emitLeadingComments(node); emitStart(node); // variable declaration for import-equals declaration can be hoisted in system modules @@ -35366,7 +37901,7 @@ var ts; write("export "); write("var "); } - else if (!(node.flags & 2 /* Export */)) { + else if (!(node.flags & 1 /* Export */)) { write("var "); } } @@ -35388,14 +37923,14 @@ var ts; } } function emitExportDeclaration(node) { - ts.Debug.assert(modulekind !== 4 /* System */); - if (modulekind !== 5 /* ES6 */) { + ts.Debug.assert(modulekind !== ts.ModuleKind.System); + if (modulekind !== ts.ModuleKind.ES6) { if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { emitStart(node); var generatedName = getGeneratedNameForNode(node); if (node.exportClause) { // export { x, y, ... } from "foo" - if (modulekind !== 2 /* AMD */) { + if (modulekind !== ts.ModuleKind.AMD) { write("var "); write(generatedName); write(" = "); @@ -35421,15 +37956,17 @@ var ts; } else { // export * from "foo" - writeLine(); - write("__export("); - if (modulekind !== 2 /* AMD */) { - emitRequire(ts.getExternalModuleName(node)); + if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + writeLine(); + write("__export("); + if (modulekind !== ts.ModuleKind.AMD) { + emitRequire(ts.getExternalModuleName(node)); + } + else { + write(generatedName); + } + write(");"); } - else { - write(generatedName); - } - write(");"); } emitEnd(node); } @@ -35455,7 +37992,7 @@ var ts; } } function emitExportOrImportSpecifierList(specifiers, shouldEmit) { - ts.Debug.assert(modulekind === 5 /* ES6 */); + ts.Debug.assert(modulekind === ts.ModuleKind.ES6); var needsComma = false; for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { var specifier = specifiers_1[_a]; @@ -35474,14 +38011,14 @@ var ts; } function emitExportAssignment(node) { if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { - if (modulekind === 5 /* ES6 */) { + if (modulekind === ts.ModuleKind.ES6) { writeLine(); emitStart(node); write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 213 /* FunctionDeclaration */ && - expression.kind !== 214 /* ClassDeclaration */) { + if (expression.kind !== 217 /* FunctionDeclaration */ && + expression.kind !== 218 /* ClassDeclaration */) { write(";"); } emitEnd(node); @@ -35489,7 +38026,7 @@ var ts; else { writeLine(); emitStart(node); - if (modulekind === 4 /* System */) { + if (modulekind === ts.ModuleKind.System) { write(exportFunctionForFile + "(\"default\","); emit(node.expression); write(")"); @@ -35514,11 +38051,11 @@ var ts; externalImports = []; exportSpecifiers = {}; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { // import "mod" @@ -35528,18 +38065,20 @@ var ts; externalImports.push(node); } break; - case 221 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 232 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { + case 225 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 236 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { // import x = require("mod") where x is referenced externalImports.push(node); } break; - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" - externalImports.push(node); - hasExportStars = true; + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } } else if (resolver.isValueAliasDeclaration(node)) { // export { x, y } from "mod" where at least one export is a value symbol @@ -35550,12 +38089,12 @@ var ts; // export { x, y } for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_26 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_26] || (exportSpecifiers[name_26] = [])).push(specifier); + var name_27 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_27] || (exportSpecifiers[name_27] = [])).push(specifier); } } break; - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; @@ -35565,7 +38104,7 @@ var ts; } } function emitExportStarHelper() { - if (hasExportStars) { + if (hasExportStarsToExportValues) { writeLine(); write("function __export(m) {"); increaseIndent(); @@ -35579,16 +38118,22 @@ var ts; function getLocalNameForExternalImport(node) { var namespaceDeclaration = getNamespaceDeclarationNode(node); if (namespaceDeclaration && !isDefaultImport(node)) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); + return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); } - if (node.kind === 222 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 226 /* ImportDeclaration */ && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 228 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 232 /* ExportDeclaration */ && node.moduleSpecifier) { return getGeneratedNameForNode(node); } } - function getExternalModuleNameText(importNode) { + function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { + if (emitRelativePathAsModuleName) { + var name_28 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_28) { + return "\"" + name_28 + "\""; + } + } var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); @@ -35604,8 +38149,8 @@ var ts; for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { var importNode = externalImports_1[_a]; // do not create variable declaration for exports and imports that lack import clause - var skipNode = importNode.kind === 228 /* ExportDeclaration */ || - (importNode.kind === 222 /* ImportDeclaration */ && !importNode.importClause); + var skipNode = importNode.kind === 232 /* ExportDeclaration */ || + (importNode.kind === 226 /* ImportDeclaration */ && !importNode.importClause); if (skipNode) { continue; } @@ -35626,8 +38171,8 @@ var ts; // when resolving exports local exported entries/indirect exported entries in the module // should always win over entries with similar names that were added via star exports // to support this we store names of local/indirect exported entries in a set. - // this set is used to filter names brought by star expors. - if (!hasExportStars) { + // this set is used to filter names brought by star exports. + if (!hasExportStarsToExportValues) { // local names set is needed only in presence of star exports return undefined; } @@ -35638,7 +38183,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { var externalImport = externalImports_2[_a]; - if (externalImport.kind === 228 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 232 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -35654,7 +38199,7 @@ var ts; increaseIndent(); var started = false; if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; ++i) { + for (var i = 0; i < exportedDeclarations.length; i++) { // write name of exported declaration, i.e 'export var x...' writeExportedName(exportedDeclarations[i]); } @@ -35670,7 +38215,7 @@ var ts; } for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { var externalImport = externalImports_3[_d]; - if (externalImport.kind !== 228 /* ExportDeclaration */) { + if (externalImport.kind !== 232 /* ExportDeclaration */) { continue; } var exportDecl = externalImport; @@ -35756,14 +38301,14 @@ var ts; writeLine(); write("var "); var seen = {}; - for (var i = 0; i < hoistedVars.length; ++i) { + for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_27 = local.kind === 69 /* Identifier */ + var name_29 = local.kind === 69 /* Identifier */ ? local : local.name; - if (name_27) { + if (name_29) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - var text = ts.unescapeIdentifier(name_27.text); + var text = ts.unescapeIdentifier(name_29.text); if (ts.hasProperty(seen, text)) { continue; } @@ -35774,14 +38319,14 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 214 /* ClassDeclaration */ || local.kind === 218 /* ModuleDeclaration */ || local.kind === 217 /* EnumDeclaration */) { + if (local.kind === 218 /* ClassDeclaration */ || local.kind === 222 /* ModuleDeclaration */ || local.kind === 221 /* EnumDeclaration */) { emitDeclarationName(local); } else { emit(local); } var flags = ts.getCombinedNodeFlags(local.kind === 69 /* Identifier */ ? local.parent : local); - if (flags & 2 /* Export */) { + if (flags & 1 /* Export */) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -35795,7 +38340,7 @@ var ts; var f = hoistedFunctionDeclarations_1[_a]; writeLine(); emit(f); - if (f.flags & 2 /* Export */) { + if (f.flags & 1 /* Export */) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -35805,24 +38350,24 @@ var ts; } return exportedDeclarations; function visit(node) { - if (node.flags & 4 /* Ambient */) { + if (node.flags & 2 /* Ambient */) { return; } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 217 /* FunctionDeclaration */) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 218 /* ClassDeclaration */) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 217 /* EnumDeclaration */) { + if (node.kind === 221 /* EnumDeclaration */) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -35831,7 +38376,7 @@ var ts; } return; } - if (node.kind === 218 /* ModuleDeclaration */) { + if (node.kind === 222 /* ModuleDeclaration */) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -35840,17 +38385,17 @@ var ts; } return; } - if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + if (node.kind === 215 /* VariableDeclaration */ || node.kind === 167 /* BindingElement */) { if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) { - var name_28 = node.name; - if (name_28.kind === 69 /* Identifier */) { + var name_30 = node.name; + if (name_30.kind === 69 /* Identifier */) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_28); + hoistedVars.push(name_30); } else { - ts.forEachChild(name_28, visit); + ts.forEachChild(name_30, visit); } } return; @@ -35880,11 +38425,11 @@ var ts; // - it is top level block scoped // 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) & 24576 /* BlockScoped */) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */; + return (ts.getCombinedNodeFlags(node) & 3072 /* BlockScoped */) === 0 || + ts.getEnclosingBlockScopeContainer(node).kind === 252 /* SourceFile */; } function isCurrentFileSystemExternalModule() { - return modulekind === 4 /* System */ && ts.isExternalModule(currentSourceFile); + return modulekind === ts.ModuleKind.System && isCurrentFileExternalModule; } function emitSystemModuleBody(node, dependencyGroups, startIndex) { // shape of the body in system modules: @@ -35941,7 +38486,7 @@ var ts; } function emitSetters(exportStarFunction, dependencyGroups) { write("setters:["); - for (var i = 0; i < dependencyGroups.length; ++i) { + for (var i = 0; i < dependencyGroups.length; i++) { if (i !== 0) { write(","); } @@ -35956,21 +38501,21 @@ var ts; var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // fall-through - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== ""); writeLine(); // save import into the local write(importVariableName + " = " + parameterName + ";"); writeLine(); break; - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== ""); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -35983,12 +38528,12 @@ var ts; write(exportFunctionForFile + "({"); writeLine(); increaseIndent(); - for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) { - if (i_2 !== 0) { + for (var i_1 = 0, len = entry.exportClause.elements.length; i_1 < len; i_1++) { + if (i_1 !== 0) { write(","); writeLine(); } - var e = entry.exportClause.elements[i_2]; + var e = entry.exportClause.elements[i_1]; write("\""); emitNodeWithCommentsAndWithoutSourcemap(e.name); write("\": " + parameterName + "[\""); @@ -36000,6 +38545,8 @@ var ts; write("});"); } else { + // collectExternalModuleInfo prefilters star exports to keep only ones that export values + // this means that check 'resolver.moduleExportsSomeValue' is redundant and can be omitted here writeLine(); // export * from 'foo' // emit as: @@ -36020,17 +38567,17 @@ var ts; write("execute: function() {"); increaseIndent(); writeLine(); - for (var i = startIndex; i < node.statements.length; ++i) { + for (var i = startIndex; i < node.statements.length; i++) { var statement = node.statements[i]; switch (statement.kind) { // - function declarations are not emitted because they were already hoisted // - import declarations are not emitted since they are already handled in setters // - export declarations with module specifiers are not emitted since they were already written in setters // - export declarations without module specifiers are emitted preserving the order - case 213 /* FunctionDeclaration */: - case 222 /* ImportDeclaration */: + case 217 /* FunctionDeclaration */: + case 226 /* ImportDeclaration */: continue; - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: if (!statement.moduleSpecifier) { for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { var element = _b[_a]; @@ -36039,7 +38586,7 @@ var ts; } } continue; - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { // - import equals declarations that import external modules are not emitted continue; @@ -36054,7 +38601,13 @@ var ts; writeLine(); write("}"); // execute } - function emitSystemModule(node) { + function writeModuleName(node, emitRelativePathAsModuleName) { + var moduleName = node.moduleName; + if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) { + write("\"" + moduleName + "\", "); + } + } + function emitSystemModule(node, emitRelativePathAsModuleName) { collectExternalModuleInfo(node); // System modules has the following shape // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) @@ -36067,24 +38620,29 @@ var ts; ts.Debug.assert(!exportFunctionForFile); // make sure that name of 'exports' function does not conflict with existing identifiers exportFunctionForFile = makeUniqueName("exports"); + contextObjectForFile = makeUniqueName("context"); writeLine(); write("System.register("); - if (node.moduleName) { - write("\"" + node.moduleName + "\", "); - } + writeModuleName(node, emitRelativePathAsModuleName); write("["); var groupIndices = {}; var dependencyGroups = []; - for (var i = 0; i < externalImports.length; ++i) { - var text = getExternalModuleNameText(externalImports[i]); - if (ts.hasProperty(groupIndices, text)) { + for (var i = 0; i < externalImports.length; i++) { + var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); + if (text === undefined) { + continue; + } + // text should be quoted string + // for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same + var key = text.substr(1, text.length - 2); + if (ts.hasProperty(groupIndices, key)) { // deduplicate/group entries in dependency list by the dependency name - var groupIndex = groupIndices[text]; + var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; } else { - groupIndices[text] = dependencyGroups.length; + groupIndices[key] = dependencyGroups.length; dependencyGroups.push([externalImports[i]]); } if (i !== 0) { @@ -36092,10 +38650,13 @@ var ts; } write(text); } - write("], function(" + exportFunctionForFile + ") {"); + write("], function(" + exportFunctionForFile + ", " + contextObjectForFile + ") {"); writeLine(); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); + writeLine(); + write("var __moduleName = " + contextObjectForFile + " && " + contextObjectForFile + ".id;"); + writeLine(); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -36103,7 +38664,7 @@ var ts; writeLine(); write("});"); } - function getAMDDependencyNames(node, includeNonAmdDependencies) { + function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { // names of modules with corresponding parameter in the factory function var aliasedModuleNames = []; // names of modules with no corresponding parameters in factory function @@ -36125,7 +38686,7 @@ var ts; for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { var importNode = externalImports_4[_c]; // Find the name of the external module - var externalModuleName = getExternalModuleNameText(importNode); + var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); // Find the name of the module alias, if there is one var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { @@ -36138,7 +38699,7 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } - function emitAMDDependencies(node, includeNonAmdDependencies) { + function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { // An AMD define function has the following shape: // define(id?, dependencies?, factory); // @@ -36150,7 +38711,7 @@ var ts; // To ensure this is true in cases of modules with no aliases, e.g.: // `import "module"` or `` // we need to add modules without alias names to the end of the dependencies list - var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies); + var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName); emitAMDDependencyList(dependencyNames); write(", "); emitAMDFactoryHeader(dependencyNames); @@ -36177,17 +38738,15 @@ var ts; } write(") {"); } - function emitAMDModule(node) { + function emitAMDModule(node, emitRelativePathAsModuleName) { emitEmitHelpers(node); collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.moduleName) { - write("\"" + node.moduleName + "\", "); - } - emitAMDDependencies(node, /*includeNonAmdDependencies*/ true); + writeModuleName(node, emitRelativePathAsModuleName); + emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36198,7 +38757,7 @@ var ts; write("});"); } function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -36218,7 +38777,7 @@ var ts; writeLines(" }\n})("); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36232,7 +38791,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); @@ -36295,7 +38854,9 @@ var ts; // Replace entities like   result = result.replace(/&(\w+);/g, function (s, m) { if (entities[m] !== undefined) { - return String.fromCharCode(entities[m]); + var ch = String.fromCharCode(entities[m]); + // " needs to be escaped + return ch === "\"" ? "\\\"" : ch; } else { return s; @@ -36304,6 +38865,18 @@ var ts; } return result; } + function isJsxChildEmittable(child) { + if (child.kind === 244 /* JsxExpression */) { + // Don't emit empty expressions + return !!child.expression; + } + else if (child.kind === 240 /* JsxText */) { + // Don't emit empty strings + return !!getTextToEmit(child); + } + return true; + } + ; function getTextToEmit(node) { switch (compilerOptions.jsx) { case 2 /* React */: @@ -36347,24 +38920,41 @@ var ts; } } } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { + function isUseStrictPrologue(node) { + return !!node.expression.text.match(/use strict/); + } + function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { + if (writeUseStrict) { + if (startWithNewLine) { + writeLine(); + } + write("\"use strict\";"); + } + } + function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { + var foundUseStrict = false; + for (var i = 0; i < statements.length; i++) { if (ts.isPrologueDirective(statements[i])) { + if (isUseStrictPrologue(statements[i])) { + foundUseStrict = true; + } if (startWithNewLine || i > 0) { writeLine(); } emit(statements[i]); } else { + ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); // return index of the first non prologue directive return i; } } + ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); return statements.length; } function writeLines(text) { var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; ++i) { + for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line.length) { writeLine(); @@ -36377,22 +38967,22 @@ var ts; if (!compilerOptions.noEmitHelpers) { // Only Emit __extends function when target ES5. // For target ES6 and above, we can emit classDeclaration as is. - if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */)) { + if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && node.flags & 262144 /* HasClassExtends */)) { writeLines(extendsHelper); extendsEmitted = true; } - if (!decorateEmitted && resolver.getNodeCheckFlags(node) & 16 /* EmitDecorate */) { + if (!decorateEmitted && node.flags & 524288 /* HasDecorators */) { writeLines(decorateHelper); if (compilerOptions.emitDecoratorMetadata) { writeLines(metadataHelper); } decorateEmitted = true; } - if (!paramEmitted && resolver.getNodeCheckFlags(node) & 32 /* EmitParam */) { + if (!paramEmitted && node.flags & 1048576 /* HasParamDecorators */) { writeLines(paramHelper); paramEmitted = true; } - if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & 64 /* EmitAwaiter */) { + if (!awaiterEmitted && node.flags & 2097152 /* HasAsyncFunctions */) { writeLines(awaiterHelper); awaiterEmitted = true; } @@ -36404,8 +38994,13 @@ var ts; emitShebang(); emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */]; - emitModule(node); + if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { + var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ts.ModuleKind.CommonJS]; + emitModule(node); + } + else { + bundleEmitDelegates[modulekind](node, /*emitRelativePathAsModuleName*/ true); + } } else { // emit prologue directives prior to __extends @@ -36413,7 +39008,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -36421,12 +39016,15 @@ var ts; } emitLeadingComments(node.endOfFileToken); } + function emit(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + } function emitNodeWithCommentsAndWithoutSourcemap(node) { emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); } function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { if (node) { - if (node.flags & 4 /* Ambient */) { + if (node.flags & 2 /* Ambient */) { return emitCommentsOnNotEmittedNode(node); } if (isSpecializedCommentHandling(node)) { @@ -36443,33 +39041,53 @@ var ts; } } } + function emitNodeWithSourceMap(node) { + if (node) { + emitStart(node); + emitNodeWithoutSourceMap(node); + emitEnd(node); + } + } function emitNodeWithoutSourceMap(node) { if (node) { emitJavaScriptWorker(node); } } + function changeSourceMapEmit(writer) { + sourceMap = writer; + emitStart = writer.emitStart; + emitEnd = writer.emitEnd; + emitPos = writer.emitPos; + setSourceFile = writer.setSourceFile; + } + function withTemporaryNoSourceMap(callback) { + var prevSourceMap = sourceMap; + setSourceMapWriterEmit(ts.getNullSourceMapWriter()); + callback(); + setSourceMapWriterEmit(prevSourceMap); + } function isSpecializedCommentHandling(node) { 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 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 227 /* ExportAssignment */: + case 219 /* InterfaceDeclaration */: + case 217 /* FunctionDeclaration */: + case 226 /* ImportDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 231 /* ExportAssignment */: return true; } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: // Only emit the leading/trailing comments for a module if we're actually // emitting the module as well. return shouldEmitModuleDeclaration(node); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: // Only emit the leading/trailing comments for an enum if we're actually // emitting the module as well. return shouldEmitEnumDeclaration(node); @@ -36481,9 +39099,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 !== 192 /* Block */ && + if (node.kind !== 196 /* Block */ && node.parent && - node.parent.kind === 174 /* ArrowFunction */ && + node.parent.kind === 178 /* ArrowFunction */ && node.parent.body === node && compilerOptions.target <= 1 /* ES5 */) { return false; @@ -36496,13 +39114,13 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return emitIdentifier(node); - case 138 /* Parameter */: + case 140 /* Parameter */: return emitParameter(node); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return emitMethod(node); - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: return emitAccessor(node); case 97 /* ThisKeyword */: return emitThis(node); @@ -36522,142 +39140,142 @@ var ts; case 13 /* TemplateMiddle */: case 14 /* TemplateTail */: return emitLiteral(node); - case 183 /* TemplateExpression */: + case 187 /* TemplateExpression */: return emitTemplateExpression(node); - case 190 /* TemplateSpan */: + case 194 /* TemplateSpan */: return emitTemplateSpan(node); - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: + case 237 /* JsxElement */: + case 238 /* JsxSelfClosingElement */: return emitJsxElement(node); - case 236 /* JsxText */: + case 240 /* JsxText */: return emitJsxText(node); - case 240 /* JsxExpression */: + case 244 /* JsxExpression */: return emitJsxExpression(node); - case 135 /* QualifiedName */: + case 137 /* QualifiedName */: return emitQualifiedName(node); - case 161 /* ObjectBindingPattern */: + case 165 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 162 /* ArrayBindingPattern */: + case 166 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 163 /* BindingElement */: + case 167 /* BindingElement */: return emitBindingElement(node); - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return emitArrayLiteral(node); - case 165 /* ObjectLiteralExpression */: + case 169 /* ObjectLiteralExpression */: return emitObjectLiteral(node); - case 245 /* PropertyAssignment */: + case 249 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 246 /* ShorthandPropertyAssignment */: + case 250 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 136 /* ComputedPropertyName */: + case 138 /* ComputedPropertyName */: return emitComputedPropertyName(node); - case 166 /* PropertyAccessExpression */: + case 170 /* PropertyAccessExpression */: return emitPropertyAccess(node); - case 167 /* ElementAccessExpression */: + case 171 /* ElementAccessExpression */: return emitIndexedAccess(node); - case 168 /* CallExpression */: + case 172 /* CallExpression */: return emitCallExpression(node); - case 169 /* NewExpression */: + case 173 /* NewExpression */: return emitNewExpression(node); - case 170 /* TaggedTemplateExpression */: + case 174 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 171 /* TypeAssertionExpression */: + case 175 /* TypeAssertionExpression */: return emit(node.expression); - case 189 /* AsExpression */: + case 193 /* AsExpression */: return emit(node.expression); - case 172 /* ParenthesizedExpression */: + case 176 /* ParenthesizedExpression */: return emitParenExpression(node); - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return emitFunctionDeclaration(node); - case 175 /* DeleteExpression */: + case 179 /* DeleteExpression */: return emitDeleteExpression(node); - case 176 /* TypeOfExpression */: + case 180 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 177 /* VoidExpression */: + case 181 /* VoidExpression */: return emitVoidExpression(node); - case 178 /* AwaitExpression */: + case 182 /* AwaitExpression */: return emitAwaitExpression(node); - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 180 /* PostfixUnaryExpression */: + case 184 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return emitBinaryExpression(node); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return emitConditionalExpression(node); - case 185 /* SpreadElementExpression */: + case 189 /* SpreadElementExpression */: return emitSpreadElementExpression(node); - case 184 /* YieldExpression */: + case 188 /* YieldExpression */: return emitYieldExpression(node); - case 187 /* OmittedExpression */: + case 191 /* OmittedExpression */: return; - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 196 /* Block */: + case 223 /* ModuleBlock */: return emitBlock(node); - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: return emitVariableStatement(node); - case 194 /* EmptyStatement */: + case 198 /* EmptyStatement */: return write(";"); - case 195 /* ExpressionStatement */: + case 199 /* ExpressionStatement */: return emitExpressionStatement(node); - case 196 /* IfStatement */: + case 200 /* IfStatement */: return emitIfStatement(node); - case 197 /* DoStatement */: + case 201 /* DoStatement */: return emitDoStatement(node); - case 198 /* WhileStatement */: + case 202 /* WhileStatement */: return emitWhileStatement(node); - case 199 /* ForStatement */: + case 203 /* ForStatement */: return emitForStatement(node); - case 201 /* ForOfStatement */: - case 200 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 204 /* ForInStatement */: return emitForInOrForOfStatement(node); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 206 /* ContinueStatement */: + case 207 /* BreakStatement */: return emitBreakOrContinueStatement(node); - case 204 /* ReturnStatement */: + case 208 /* ReturnStatement */: return emitReturnStatement(node); - case 205 /* WithStatement */: + case 209 /* WithStatement */: return emitWithStatement(node); - case 206 /* SwitchStatement */: + case 210 /* SwitchStatement */: return emitSwitchStatement(node); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 245 /* CaseClause */: + case 246 /* DefaultClause */: return emitCaseOrDefaultClause(node); - case 207 /* LabeledStatement */: + case 211 /* LabeledStatement */: return emitLabeledStatement(node); - case 208 /* ThrowStatement */: + case 212 /* ThrowStatement */: return emitThrowStatement(node); - case 209 /* TryStatement */: + case 213 /* TryStatement */: return emitTryStatement(node); - case 244 /* CatchClause */: + case 248 /* CatchClause */: return emitCatchClause(node); - case 210 /* DebuggerStatement */: + case 214 /* DebuggerStatement */: return emitDebuggerStatement(node); - case 211 /* VariableDeclaration */: + case 215 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: return emitClassExpression(node); - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: return emitClassDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 247 /* EnumMember */: + case 251 /* EnumMember */: return emitEnumMember(node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: return emitImportDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: return emitExportDeclaration(node); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: return emitExportAssignment(node); - case 248 /* SourceFile */: + case 252 /* SourceFile */: return emitSourceFileNode(node); } } @@ -36666,7 +39284,7 @@ var ts; } function getLeadingCommentsWithoutDetachedComments() { // get the leading comments from detachedPos - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); + var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -36683,10 +39301,10 @@ var ts; function isTripleSlashComment(comment) { // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text // so that we don't end up computing comment string and doing match for all // comments - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ && + if (currentText.charCodeAt(comment.pos + 1) === 47 /* slash */ && comment.pos + 2 < comment.end && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */) { - var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end); + currentText.charCodeAt(comment.pos + 2) === 47 /* slash */) { + var textSubStr = currentText.substring(comment.pos, comment.end); return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? true : false; @@ -36696,14 +39314,14 @@ 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 === 248 /* SourceFile */ || node.pos !== node.parent.pos) { + if (node.parent.kind === 252 /* SourceFile */ || node.pos !== node.parent.pos) { if (hasDetachedComments(node.pos)) { // get comments without detached comments return getLeadingCommentsWithoutDetachedComments(); } else { // get the leading comments from the node - return ts.getLeadingCommentRangesOfNode(node, currentSourceFile); + return ts.getLeadingCommentRangesOfNodeFromText(node, currentText); } } } @@ -36711,8 +39329,8 @@ 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 === 248 /* SourceFile */ || node.end !== node.parent.end) { - return ts.getTrailingCommentRanges(currentSourceFile.text, node.end); + if (node.parent.kind === 252 /* SourceFile */ || node.end !== node.parent.end) { + return ts.getTrailingCommentRanges(currentText, node.end); } } } @@ -36720,10 +39338,10 @@ var ts; * Emit comments associated with node that will not be emitted into JS file */ function emitCommentsOnNotEmittedNode(node) { - emitLeadingCommentsWorker(node, /*isEmittedNode:*/ false); + emitLeadingCommentsWorker(node, /*isEmittedNode*/ false); } function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, /*isEmittedNode:*/ true); + return emitLeadingCommentsWorker(node, /*isEmittedNode*/ true); } function emitLeadingCommentsWorker(node, isEmittedNode) { if (compilerOptions.removeComments) { @@ -36741,14 +39359,14 @@ var ts; // declare var x; // /// // interface F {} - // The first /// will NOT be removed while the second one will be removed eventhough both node will not be emitted + // The first /// will NOT be removed while the second one will be removed even though both node will not be emitted if (node.pos === 0) { leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); } } - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); } function emitTrailingComments(node) { if (compilerOptions.removeComments) { @@ -36757,7 +39375,7 @@ var ts; // Emit the trailing comments only if the parent's end doesn't match var trailingComments = getTrailingCommentsToEmit(node); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ - ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); } /** * Emit trailing comments at the position. The term trailing comment is used here to describe following comment: @@ -36768,9 +39386,9 @@ var ts; if (compilerOptions.removeComments) { return; } - var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos); + var trailingComments = ts.getTrailingCommentRanges(currentText, pos); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ - ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); } function emitLeadingCommentsOfPositionWorker(pos) { if (compilerOptions.removeComments) { @@ -36783,14 +39401,14 @@ var ts; } else { // get the leading comments from the node - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); + leadingComments = ts.getLeadingCommentRanges(currentText, pos); } - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments); // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); } function emitDetachedCommentsAndUpdateCommentsInfo(node) { - var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); + var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments); if (currentDetachedCommentInfo) { if (detachedCommentsInfo) { detachedCommentsInfo.push(currentDetachedCommentInfo); @@ -36800,18 +39418,31 @@ var ts; } } } + function writeComment(text, lineMap, writer, comment, newLine) { + emitPos(comment.pos); + ts.writeCommentRange(text, lineMap, writer, comment, newLine); + emitPos(comment.end); + } function emitShebang() { - var shebang = ts.getShebang(currentSourceFile.text); + var shebang = ts.getShebang(currentText); if (shebang) { write(shebang); + writeLine(); } } - var _a; + var _a, _b; } - function emitFile(jsFilePath, sourceFile) { - emitJavaScript(jsFilePath, sourceFile); - if (compilerOptions.declaration) { - ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); + function emitFile(_a, sourceFiles, isBundledEmit) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + // Make sure not to write js File and source map file if any of them cannot be written + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; + } + if (declarationFilePath) { + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } } } @@ -36828,11 +39459,11 @@ var ts; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ var emptyArray = []; - ts.version = "1.8.0"; - function findConfigFile(searchPath) { + ts.version = "1.9.0"; + function findConfigFile(searchPath, fileExists) { var fileName = "tsconfig.json"; while (true) { - if (ts.sys.fileExists(fileName)) { + if (fileExists(fileName)) { return fileName; } var parentPath = ts.getDirectoryPath(searchPath); @@ -36851,88 +39482,409 @@ var ts; return ts.normalizePath(referencedFileName); } ts.resolveTripleslashReference = resolveTripleslashReference; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var moduleResolution = compilerOptions.moduleResolution !== undefined - ? compilerOptions.moduleResolution - : compilerOptions.module === 1 /* CommonJS */ ? 2 /* NodeJs */ : 1 /* Classic */; - switch (moduleResolution) { - case 2 /* NodeJs */: return nodeModuleNameResolver(moduleName, containingFile, host); - case 1 /* Classic */: return classicNameResolver(moduleName, containingFile, compilerOptions, host); - } + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); } - ts.resolveModuleName = resolveModuleName; - function nodeModuleNameResolver(moduleName, containingFile, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { - var failedLookupLocations = []; - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host); - if (resolvedFileName) { - return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceModuleResolution && host.trace !== undefined; + } + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return str.indexOf(suffix, expectedPos) === expectedPos; + } + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + function moduleHasNonRelativeName(moduleName) { + if (ts.isRootedDiskPath(moduleName)) { + return false; + } + var i = moduleName.lastIndexOf("./", 1); + var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */); + return !startsWithDotSlashOrDotDotSlash; + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); } - resolvedFileName = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); - return resolvedFileName - ? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } else { - return loadModuleFromNodeModules(moduleName, containingDirectory, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); } } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var longestMatchPrefixLength = -1; + var matchedPattern; + var matchedStar; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + for (var key in state.compilerOptions.paths) { + var pattern = key; + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (moduleName.length >= prefix.length + suffix.length && + startsWith(moduleName, prefix) && + endsWith(moduleName, suffix)) { + // use length of prefix as betterness criteria + if (prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = prefix.length; + matchedPattern = pattern; + matchedStar = moduleName.substr(prefix.length, moduleName.length - suffix.length); + } + } + } + else if (pattern === moduleName) { + // pattern was matched as is - no need to search further + matchedPattern = pattern; + matchedStar = undefined; + break; + } + } + } + if (matchedPattern) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPattern); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPattern]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("\*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); + } + var isExternalLibraryImport = false; + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function loadNodeModuleFromFile(candidate, failedLookupLocation, host) { - return ts.forEach(ts.moduleFileExtensions, tryLoad); + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + return ts.forEach(extensions, tryLoad); function tryLoad(ext) { + if (ext === ".tsx" && state.skipTsx) { + return undefined; + } var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (host.fileExists(fileName)) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName); + } return fileName; } else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } failedLookupLocation.push(fileName); return undefined; } } } - function loadNodeModuleFromDirectory(candidate, failedLookupLocation, host) { + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { var packageJsonPath = ts.combinePaths(candidate, "package.json"); - if (host.fileExists(packageJsonPath)) { - var jsonContent; + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var jsonContent = void 0; try { - var jsonText = host.readFile(packageJsonPath); + var jsonText = state.host.readFile(packageJsonPath); jsonContent = jsonText ? JSON.parse(jsonText) : { typings: undefined }; } catch (e) { - // gracefully handle if readFile fails or returns not JSON + // gracefully handle if readFile fails or returns not JSON jsonContent = { typings: undefined }; } if (jsonContent.typings) { - var result = loadNodeModuleFromFile(ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); - if (result) { - return result; + if (typeof jsonContent.typings === "string") { + var typingsFile = ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile); + } + var result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(typingsFile), state.host), state); + if (result) { + return result; + } + } + else if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings); + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_typings_field); } } } else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocation.push(packageJsonPath); } - return loadNodeModuleFromFile(ts.combinePaths(candidate, "index"), failedLookupLocation, host); + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); } - function loadModuleFromNodeModules(moduleName, directory, host) { - var failedLookupLocations = []; + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { directory = ts.normalizeSlashes(directory); while (true) { var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var result = loadNodeModuleFromFile(candidate, failedLookupLocations, host); + // Load only typescript files irrespective of allowJs option if loading from node modules + var result = loadModuleFromFile(candidate, ts.supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { - return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; + return result; } - result = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); + result = loadNodeModuleFromDirectory(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); if (result) { - return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; + return result; } } var parentPath = ts.getDirectoryPath(directory); @@ -36941,45 +39893,36 @@ var ts; } directory = parentPath; } - return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - function nameStartsWithDotSlashOrDotDotSlash(name) { - var i = name.lastIndexOf("./", 1); - return i === 0 || (i === 1 && name.charCodeAt(0) === 46 /* dot */); + return undefined; } function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - // module names that contain '!' are used to reference resources and are not resolved to actual files on disk - if (moduleName.indexOf("!") != -1) { - return { resolvedModule: undefined, failedLookupLocations: [] }; - } - var searchPath = ts.getDirectoryPath(containingFile); - var searchName; + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); + } var referencedSourceFile; - while (true) { - searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - referencedSourceFile = ts.forEach(ts.supportedExtensions, function (extension) { - if (extension === ".tsx" && !compilerOptions.jsx) { - // resolve .tsx files only if jsx support is enabled - // 'logical not' handles both undefined and None cases - return undefined; + if (moduleHasNonRelativeName(moduleName)) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + if (referencedSourceFile) { + break; } - var candidate = searchName + extension; - if (host.fileExists(candidate)) { - return candidate; + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + break; } - else { - failedLookupLocations.push(candidate); - } - }); - if (referencedSourceFile) { - break; + containingDirectory = parentPath; } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); } return referencedSourceFile ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } @@ -36988,11 +39931,9 @@ var ts; ts.classicNameResolver = classicNameResolver; /* @internal */ ts.defaultInitCompilerOptions = { - module: 1 /* CommonJS */, - target: 0 /* ES3 */, + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, noImplicitAny: false, - outDir: "built", - rootDir: ".", sourceMap: false }; function createCompilerHost(options, setParentNodes) { @@ -37061,14 +40002,16 @@ var ts; getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); } + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + trace: function (s) { return ts.sys.write(s + newLine); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); } }; } ts.createCompilerHost = createCompilerHost; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -37106,15 +40049,36 @@ var ts; var noDiagnosticsTypeChecker; var classifiableNames; var skipDefaultLib = options.noLib; + var supportedExtensions = ts.getSupportedExtensions(options); var start = new Date().getTime(); host = host || createCompilerHost(options); + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); var currentDirectory = host.getCurrentDirectory(); var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) - : (function (moduleNames, containingFile) { return ts.map(moduleNames, function (moduleName) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }); }); + : (function (moduleNames, containingFile) { + var resolvedModuleNames = []; + // resolveModuleName does not store any results between calls. + // lookup is a local cache to avoid resolving the same module name several times + var lookup = {}; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedName = void 0; + if (ts.hasProperty(lookup, moduleName)) { + resolvedName = lookup[moduleName]; + } + else { + resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule; + lookup[moduleName] = resolvedName; + } + resolvedModuleNames.push(resolvedName); + } + return resolvedModuleNames; + }); var filesByName = ts.createFileMap(); // stores 'filename -> file association' ignoring case - // used to track cases when two file names differ only in casing + // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (oldProgram) { // check properties that can affect structure of the program or module resolution strategy @@ -37124,24 +40088,23 @@ var ts; (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx)) { + (oldOptions.jsx !== options.jsx) || + (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } if (!tryReuseStructureFromOldProgram()) { - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + ts.forEach(rootNames, function (name) { return 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), true); + processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true); } } - verifyCompilerOptions(); // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; - ts.programTime += new Date().getTime() - start; program = { getRootFileNames: function () { return rootNames; }, getSourceFile: getSourceFile, @@ -37155,7 +40118,7 @@ var ts; getTypeChecker: getTypeChecker, getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: function () { return commonSourceDirectory; }, + getCommonSourceDirectory: getCommonSourceDirectory, emit: emit, getCurrentDirectory: function () { return currentDirectory; }, getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, @@ -37164,7 +40127,27 @@ var ts; getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; } }; + verifyCompilerOptions(); + ts.programTime += new Date().getTime() - start; return program; + function getCommonSourceDirectory() { + if (typeof commonSourceDirectory === "undefined") { + if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + // If a rootDir is specified and is valid use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(files); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } function getClassifiableNames() { if (!classifiableNames) { // Initialize a checker so that all our files are bound. @@ -37210,17 +40193,21 @@ var ts; // tripleslash references has changed return false; } - // check imports + // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed return false; } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + return false; + } if (resolveModuleNamesWorker) { - var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); + var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct - for (var i = 0; i < moduleNames.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); var resolutionChanged = oldResolution @@ -37245,7 +40232,7 @@ var ts; newSourceFiles.push(newSourceFile); } // update fileName -> file mapping - for (var i = 0, len = newSourceFiles.length; i < len; ++i) { + for (var i = 0, len = newSourceFiles.length; i < len; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; @@ -37266,7 +40253,8 @@ var ts; getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFiles: program.getSourceFiles, - writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }) + writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }), + isEmitBlocked: isEmitBlocked }; } function getDiagnosticsProducingTypeChecker() { @@ -37279,12 +40267,25 @@ var ts; var _this = this; return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + var declarationDiagnostics = []; + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emitSkipped: true }; + } // If the noEmitOnError flag is set, then check if we have any errors so far. If so, // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError && getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken).length > 0) { - return { diagnostics: [], sourceMaps: undefined, emitSkipped: true }; + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { diagnostics: diagnostics, sourceMaps: undefined, emitSkipped: true }; + } } // Create the emit resolver outside of the "emitTime" tracking code below. That way // any cost associated with it (like type checking) are appropriate associated with @@ -37337,7 +40338,7 @@ var ts; // We were canceled while performing the operation. Because our type checker // might be a bad state, we need to throw it away. // - // Note: we are overly agressive here. We do not actually *have* to throw away + // Note: we are overly aggressive here. We do not actually *have* to throw away // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep // the lifetimes of these two TypeCheckers the same. Also, we generally only // cancel when the user has made a change anyways. And, in that case, we (the @@ -37354,12 +40355,170 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + // For JavaScript files, we don't want to report the normal typescript semantic errors. + // Instead, we just report errors for using TypeScript-only constructs from within a + // JavaScript file. + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? + getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : + typeChecker.getDiagnostics(sourceFile, cancellationToken); var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); } + function getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var diagnostics = []; + walk(sourceFile); + return diagnostics; + function walk(node) { + if (!node) { + return false; + } + switch (node.kind) { + case 225 /* ImportEqualsDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return true; + case 231 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 218 /* ClassDeclaration */: + var classDeclaration = node; + if (checkModifiers(classDeclaration.modifiers) || + checkTypeParameters(classDeclaration.typeParameters)) { + return true; + } + break; + case 247 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 106 /* ImplementsKeyword */) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 219 /* InterfaceDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 222 /* ModuleDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 220 /* TypeAliasDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return true; + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 177 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: + case 178 /* ArrowFunction */: + case 217 /* FunctionDeclaration */: + var functionDeclaration = node; + if (checkModifiers(functionDeclaration.modifiers) || + checkTypeParameters(functionDeclaration.typeParameters) || + checkTypeAnnotation(functionDeclaration.type)) { + return true; + } + break; + case 197 /* VariableStatement */: + var variableStatement = node; + if (checkModifiers(variableStatement.modifiers)) { + return true; + } + break; + case 215 /* VariableDeclaration */: + var variableDeclaration = node; + if (checkTypeAnnotation(variableDeclaration.type)) { + return true; + } + break; + case 172 /* CallExpression */: + case 173 /* NewExpression */: + var expression = node; + if (expression.typeArguments && expression.typeArguments.length > 0) { + var start_2 = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 140 /* Parameter */: + var parameter = node; + if (parameter.modifiers) { + var start_3 = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return true; + } + if (parameter.questionToken) { + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return true; + } + if (parameter.type) { + diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 143 /* PropertyDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 221 /* EnumDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 175 /* 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 141 /* Decorator */: + if (!options.experimentalDecorators) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + return true; + } + return ts.forEachChild(node, walk); + } + function checkTypeParameters(typeParameters) { + if (typeParameters) { + var start_4 = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkTypeAnnotation(type) { + if (type) { + diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkModifiers(modifiers) { + if (modifiers) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 127 /* ReadonlyKeyword */: + case 122 /* DeclareKeyword */: + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + // These are all legal modifiers. + case 113 /* StaticKeyword */: + case 82 /* ExportKeyword */: + case 74 /* ConstKeyword */: + case 77 /* DefaultKeyword */: + case 115 /* AbstractKeyword */: + } + } + } + return false; + } + }); + } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (!ts.isDeclarationFile(sourceFile)) { @@ -37393,21 +40552,32 @@ var ts; function moduleNameIsEqualTo(a, b) { return a.text === b.text; } + function getTextOfLiteral(literal) { + return literal.text; + } function collectExternalModuleReferences(file) { if (file.imports) { return; } + var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isExternalModuleFile = ts.isExternalModule(file); var imports; + var moduleAugmentations; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; - collect(node, /* allowRelativeModuleNames */ true); + collectModuleReferences(node, /*inAmbientModule*/ false); + if (isJavaScriptFile) { + collectRequireCalls(node); + } } file.imports = imports || emptyArray; - function collect(node, allowRelativeModuleNames) { + file.moduleAugmentations = moduleAugmentations || emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: + case 226 /* ImportDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 232 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) { break; @@ -37415,25 +40585,44 @@ var ts; if (!moduleNameExpr.text) { break; } - if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + if (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { (imports || (imports = [])).push(moduleNameExpr); } break; - case 218 /* ModuleDeclaration */: - if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* 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. - // The StringLiteral must specify a top - level external module name. - // Relative external module names are not permitted - ts.forEachChild(node.body, function (node) { - // TypeScript 1.0 spec (April 2014): 12.1.6 - // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules - // only through top - level external module names. Relative external module names are not permitted. - collect(node, /* allowRelativeModuleNames */ false); - }); + case 222 /* ModuleDeclaration */: + if (ts.isAmbientModule(node) && (inAmbientModule || node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + var moduleName = node.name; + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { + (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); + } + else if (!inAmbientModule) { + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + // NOTE: body of ambient module is always a module block + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } + } } - break; + } + } + function collectRequireCalls(node) { + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + (imports || (imports = [])).push(node.arguments[0]); + } + else { + ts.forEachChild(node, collectRequireCalls); } } } @@ -37441,9 +40630,9 @@ var ts; var diagnosticArgument; var diagnostic; if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; - diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; + diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; @@ -37461,7 +40650,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -37486,12 +40675,12 @@ var ts; } } // Get source file from normalized fileName - function findSourceFile(fileName, normalizedAbsolutePath, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(normalizedAbsolutePath)) { - var file_1 = filesByName.get(normalizedAbsolutePath); + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + if (filesByName.contains(path)) { + var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== normalizedAbsolutePath) { + if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } return file_1; @@ -37505,17 +40694,17 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); - filesByName.set(normalizedAbsolutePath, file); + filesByName.set(path, file); if (file) { - file.path = normalizedAbsolutePath; + file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case - var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); + var existingFile = filesByNameIgnoreCase.get(path); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(normalizedAbsolutePath, file); + filesByNameIgnoreCase.set(path, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -37526,7 +40715,6 @@ var ts; // always process imported modules to record module name resolutions processImportedModules(file, basePath); if (isDefaultLib) { - file.isDefaultLib = true; files.unshift(file); } else { @@ -37538,7 +40726,7 @@ var ts; function processReferencedFiles(file, basePath) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end); + processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end); }); } function getCanonicalFileName(fileName) { @@ -37546,19 +40734,28 @@ var ts; } function processImportedModules(file, basePath) { collectExternalModuleReferences(file); - if (file.imports.length) { + if (file.imports.length || file.moduleAugmentations.length) { file.resolvedModules = {}; - var moduleNames = ts.map(file.imports, function (name) { return name.text; }); + var moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); - for (var i = 0; i < file.imports.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - if (resolution && !options.noResolve) { - var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + // add file to program only if: + // - resolution was successful + // - noResolve is falsy + // - module name come from the list fo imports + var shouldAddFile = resolution && + !options.noResolve && + i < file.imports.length; + if (shouldAddFile) { + var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { - if (!ts.isExternalModule(importedFile)) { - var start_2 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); + // Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files, + // this check is ok. Otherwise this would be never true for javascript file + if (!ts.isExternalModule(importedFile) && importedFile.statements.length) { + var start_5 = ts.getTokenPosOfNode(file.imports[i], file); + fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { var firstRef = importedFile.referencedFiles[0]; @@ -37576,7 +40773,7 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var commonPathComponents; - ts.forEach(files, function (sourceFile) { + var failed = ts.forEach(files, function (sourceFile) { // Each file contributes into common source file path if (ts.isDeclarationFile(sourceFile)) { return; @@ -37589,10 +40786,10 @@ var ts; return; } for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; + // Failed to find any common path component + return true; } // New common path found that is 0 -> i-1 commonPathComponents.length = i; @@ -37604,14 +40801,21 @@ var ts; commonPathComponents.length = sourcePathComponents.length; } }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } + if (!commonPathComponents) { + return currentDirectory; + } return ts.getNormalizedPathFromPathComponents(commonPathComponents); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -37645,14 +40849,33 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); } - if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap")); + } + if (options.paths && options.baseUrl === undefined) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!hasZeroOrOneAsteriskCharacter(key)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); + } + for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { + var subst = _a[_i]; + if (!hasZeroOrOneAsteriskCharacter(subst)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); + } + } } } if (options.inlineSources) { if (!options.sourceMap && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); } + if (options.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); + } } if (options.out && options.outFile) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); @@ -37662,16 +40885,15 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } - if (options.sourceRoot) { + if (options.sourceRoot && !options.inlineSourceMap) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); } - return; } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); if (options.isolatedModules) { - if (!options.module && languageVersion < 2 /* ES6 */) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES6 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -37680,34 +40902,29 @@ var ts; programDiagnostics.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) { + else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } // Cannot specify module gen target of es6 when below es6 - if (options.module === 5 /* ES6 */ && languageVersion < 2 /* ES6 */) { + if (options.module === ts.ModuleKind.ES6 && languageVersion < 2 /* ES6 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } + // Cannot specify module gen that isn't amd or system with --out + if (outFile && options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || options.sourceRoot || - (options.mapRoot && - (!outFile || firstExternalModuleSourceFile !== undefined))) { - if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { - // If a rootDir is specified and is valid use it as the commonSourceDirectory - commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); - } - else { - // Compute the commonSourceDirectory from the input files - commonSourceDirectory = computeCommonSourceDirectory(files); - } - if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { - // Make sure directory path ends with directory separator so this string can directly - // used to replace with "" to get the relative path of the source file and the relative path doesn't - // start with / making it rooted path - commonSourceDirectory += ts.directorySeparator; + options.mapRoot) { + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { @@ -37724,10 +40941,47 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } + else if (options.allowJs && options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } + if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + // Report error if the output overwrites input file + if (filesByName.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + } + // Report error if multiple files write into same file + if (emitFilesSeen.contains(emitFilePath)) { + // Already seen the same emit file - report error + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + } + else { + emitFilesSeen.set(emitFilePath, true); + } + } + } + } + function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); } } ts.createProgram = createProgram; @@ -37788,6 +41042,11 @@ var ts; description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, error: ts.Diagnostics.Argument_for_jsx_must_be_preserve_or_react }, + { + name: "reactNamespace", + type: "string", + description: ts.Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit + }, { name: "listFiles", type: "boolean" @@ -37807,16 +41066,17 @@ var ts; name: "module", shortName: "m", type: { - "commonjs": 1 /* CommonJS */, - "amd": 2 /* AMD */, - "system": 4 /* System */, - "umd": 3 /* UMD */, - "es6": 5 /* ES6 */, - "es2015": 5 /* ES2015 */ + "none": ts.ModuleKind.None, + "commonjs": ts.ModuleKind.CommonJS, + "amd": ts.ModuleKind.AMD, + "system": ts.ModuleKind.System, + "umd": ts.ModuleKind.UMD, + "es6": ts.ModuleKind.ES6, + "es2015": ts.ModuleKind.ES2015 }, description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND, - error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015 + error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none }, { name: "newLine", @@ -37983,8 +41243,8 @@ var ts; { name: "moduleResolution", type: { - "node": 2 /* NodeJs */, - "classic": 1 /* Classic */ + "node": ts.ModuleResolutionKind.NodeJs, + "classic": ts.ModuleResolutionKind.Classic }, description: ts.Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, error: ts.Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic @@ -38013,6 +41273,47 @@ var ts; name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "baseUrl", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + isTSConfigOnly: true + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "object", + isTSConfigOnly: true, + isFilePath: true + }, + { + name: "traceModuleResolution", + type: "boolean", + description: ts.Diagnostics.Enable_tracing_of_the_module_resolution_process + }, + { + name: "allowJs", + type: "boolean", + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "noImplicitUseStrict", + type: "boolean", + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output } ]; var optionNameMapCache; @@ -38047,7 +41348,8 @@ var ts; function parseStrings(args) { var i = 0; while (i < args.length) { - var s = args[i++]; + var s = args[i]; + i++; if (s.charCodeAt(0) === 64 /* at */) { parseResponseFile(s.slice(1)); } @@ -38059,30 +41361,38 @@ var ts; } if (ts.hasProperty(optionNameMap, s)) { var opt = optionNameMap[s]; - // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). - if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); } - switch (opt.type) { - case "number": - options[opt.name] = parseInt(args[i++]); - break; - case "boolean": - options[opt.name] = true; - break; - case "string": - options[opt.name] = args[i++] || ""; - break; - // If not a primitive, the possible types are specified in what is effectively a map of options. - default: - var map_2 = opt.type; - var key = (args[i++] || "").toLowerCase(); - if (ts.hasProperty(map_2, key)) { - options[opt.name] = map_2[key]; - } - else { - errors.push(ts.createCompilerDiagnostic(opt.error)); - } + else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + options[opt.name] = true; + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + var map_1 = opt.type; + var key = (args[i] || "").toLowerCase(); + i++; + if (ts.hasProperty(map_1, key)) { + options[opt.name] = map_1[key]; + } + else { + errors.push(ts.createCompilerDiagnostic(opt.error)); + } + } } } else { @@ -38191,8 +41501,10 @@ var ts; * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json, host, basePath) { - var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors; + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { + if (existingOptions === void 0) { existingOptions = {}; } + var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath, configFileName), optionsFromJsonConfigFile = _a.options, errors = _a.errors; + var options = ts.extend(existingOptions, optionsFromJsonConfigFile); return { options: options, fileNames: getFileNames(), @@ -38209,23 +41521,47 @@ var ts; } } else { - var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; - var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); - for (var i = 0; i < sysFiles.length; i++) { - var name_29 = sysFiles[i]; - if (ts.fileExtensionIs(name_29, ".d.ts")) { - var baseName = name_29.substr(0, name_29.length - ".d.ts".length); - if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) { - fileNames.push(name_29); - } + var filesSeen = {}; + var exclude = []; + if (json["exclude"] instanceof Array) { + exclude = json["exclude"]; + } + else { + // by default exclude node_modules, and any specificied output directory + exclude = ["node_modules"]; + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + exclude.push(outDir); } - else if (ts.fileExtensionIs(name_29, ".ts")) { - if (!ts.contains(sysFiles, name_29 + "x")) { - fileNames.push(name_29); + } + exclude = ts.map(exclude, ts.normalizeSlashes); + var supportedExtensions = ts.getSupportedExtensions(options); + ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); + // Get files of supported extensions in their order of resolution + for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; + var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); + for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { + var fileName = filesInDirWithExtension_1[_a]; + // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension, + // lets pick them when its turn comes up + if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { + continue; } - } - else { - fileNames.push(name_29); + // Skip over any minified JavaScript files (ending in ".min.js") + if (/\.min\.js$/.test(fileName)) { + continue; + } + // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) + // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation + if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { + var baseName = fileName.substr(0, fileName.length - extension.length); + if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { + continue; + } + } + filesSeen[fileName] = true; + fileNames.push(fileName); } } } @@ -38233,9 +41569,12 @@ var ts; } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function convertCompilerOptionsFromJson(jsonOptions, basePath) { + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var options = {}; var errors = []; + if (configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json") { + options.allowJs = true; + } if (!jsonOptions) { return { options: options, errors: errors }; } @@ -38258,7 +41597,37 @@ var ts; } } if (opt.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + switch (typeof value) { + case "string": + value = ts.normalizePath(ts.combinePaths(basePath, value)); + break; + case "object": + // "object" options with 'isFilePath' = true expected to be string arrays + var paths = []; + var invalidOptionType = false; + if (!ts.isArray(value)) { + invalidOptionType = true; + } + else { + for (var _i = 0, _a = value; _i < _a.length; _i++) { + var element = _a[_i]; + if (typeof element === "string") { + paths.push(ts.normalizePath(ts.combinePaths(basePath, element))); + } + else { + invalidOptionType = true; + break; + } + } + } + if (invalidOptionType) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_should_have_array_of_strings_as_a_value, opt.name)); + } + else { + value = paths; + } + break; + } if (value === "") { value = "."; } @@ -38349,7 +41718,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 174 /* ArrowFunction */; + return ts.isFunctionBlock(node) && node.parent.kind !== 178 /* ArrowFunction */; } var depth = 0; var maxDepth = 20; @@ -38361,30 +41730,30 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 192 /* Block */: + case 196 /* Block */: if (!ts.isFunctionBlock(n)) { - var parent_7 = n.parent; + var parent_9 = n.parent; var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* 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_7.kind === 197 /* DoStatement */ || - parent_7.kind === 200 /* ForInStatement */ || - parent_7.kind === 201 /* ForOfStatement */ || - parent_7.kind === 199 /* ForStatement */ || - parent_7.kind === 196 /* IfStatement */ || - parent_7.kind === 198 /* WhileStatement */ || - parent_7.kind === 205 /* WithStatement */ || - parent_7.kind === 244 /* CatchClause */) { - addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); + if (parent_9.kind === 201 /* DoStatement */ || + parent_9.kind === 204 /* ForInStatement */ || + parent_9.kind === 205 /* ForOfStatement */ || + parent_9.kind === 203 /* ForStatement */ || + parent_9.kind === 200 /* IfStatement */ || + parent_9.kind === 202 /* WhileStatement */ || + parent_9.kind === 209 /* WithStatement */ || + parent_9.kind === 248 /* CatchClause */) { + addOutliningSpan(parent_9, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_7.kind === 209 /* TryStatement */) { + if (parent_9.kind === 213 /* TryStatement */) { // Could be the try-block, or the finally-block. - var tryStatement = parent_7; + var tryStatement = parent_9; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_9, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -38407,23 +41776,23 @@ var ts; break; } // Fallthrough. - case 219 /* ModuleBlock */: { + case 223 /* ModuleBlock */: { var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; } - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 165 /* ObjectLiteralExpression */: - case 220 /* CaseBlock */: { + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 169 /* ObjectLiteralExpression */: + case 224 /* CaseBlock */: { var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; } - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); @@ -38453,17 +41822,17 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_30 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_30); + for (var name_31 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_31); 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_30); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_31); if (!matches) { continue; } - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. if (patternMatcher.patternContainsDots) { @@ -38471,14 +41840,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_30); + matches = patternMatcher.getMatches(containers, name_31); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_30, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_31, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -38516,8 +41885,8 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 136 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ true); + else if (declaration.name.kind === 138 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); } else { // Don't know how to add this. @@ -38537,12 +41906,12 @@ var ts; } return true; } - if (expression.kind === 166 /* PropertyAccessExpression */) { + if (expression.kind === 170 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); } - return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion:*/ true); + return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); } return false; } @@ -38550,8 +41919,8 @@ 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 === 136 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ false)) { + if (declaration.name.kind === 138 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -38612,7 +41981,7 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile) { + function getNavigationBarItems(sourceFile, compilerOptions) { // If the source file has any child items, then it included in the tree // and takes lexical ownership of all other top-level items. var hasGlobalNode = false; @@ -38624,17 +41993,17 @@ var ts; var current = node.parent; while (current) { switch (current.kind) { - case 218 /* ModuleDeclaration */: + case 222 /* 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 === 218 /* ModuleDeclaration */); + } while (current.kind === 222 /* ModuleDeclaration */); // fall through - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 219 /* InterfaceDeclaration */: + case 217 /* FunctionDeclaration */: indent++; } current = current.parent; @@ -38645,21 +42014,21 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 193 /* VariableStatement */: + case 197 /* VariableStatement */: ts.forEach(node.declarationList.declarations, visit); break; - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: + case 165 /* ObjectBindingPattern */: + case 166 /* ArrayBindingPattern */: ts.forEach(node.elements, visit); break; - case 228 /* ExportDeclaration */: + case 232 /* 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 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -38671,7 +42040,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 228 /* NamespaceImport */) { childNodes.push(importClause.namedBindings); } else { @@ -38680,21 +42049,21 @@ var ts; } } break; - case 163 /* BindingElement */: - case 211 /* VariableDeclaration */: + case 167 /* BindingElement */: + case 215 /* VariableDeclaration */: if (ts.isBindingPattern(node.name)) { visit(node.name); break; } // Fall through - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 218 /* ModuleDeclaration */: - case 213 /* FunctionDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 219 /* InterfaceDeclaration */: + case 222 /* ModuleDeclaration */: + case 217 /* FunctionDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 230 /* ImportSpecifier */: + case 234 /* ExportSpecifier */: childNodes.push(node); break; } @@ -38742,17 +42111,17 @@ var ts; for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { var node = nodes_4[_i]; switch (node.kind) { - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 219 /* InterfaceDeclaration */: topLevelNodes.push(node); break; - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: var moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); break; - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: var functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); @@ -38763,12 +42132,12 @@ var ts; } } function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 213 /* FunctionDeclaration */) { + if (functionDeclaration.kind === 217 /* FunctionDeclaration */) { // A function declaration is 'top level' if it contains any function declarations // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 192 /* Block */) { + if (functionDeclaration.body && functionDeclaration.body.kind === 196 /* Block */) { // Proper function declarations can only have identifier names - if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 213 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 217 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { return true; } // Or if it is not parented by another function. i.e all functions @@ -38828,44 +42197,44 @@ var ts; } function createChildItem(node) { switch (node.kind) { - case 138 /* Parameter */: + case 140 /* Parameter */: if (ts.isBindingPattern(node.name)) { break; } - if ((node.flags & 1022 /* Modifier */) === 0) { + if ((node.flags & 959 /* Modifier */) === 0) { return undefined; } return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 145 /* GetAccessor */: + case 147 /* GetAccessor */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 146 /* SetAccessor */: + case 148 /* SetAccessor */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 149 /* IndexSignature */: + case 151 /* IndexSignature */: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 247 /* EnumMember */: + case 251 /* EnumMember */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147 /* CallSignature */: + case 149 /* CallSignature */: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 148 /* ConstructSignature */: + case 150 /* ConstructSignature */: return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: - var variableDeclarationNode; - var name_31; - if (node.kind === 163 /* BindingElement */) { - name_31 = node.name; + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: + var variableDeclarationNode = void 0; + var name_32; + if (node.kind === 167 /* BindingElement */) { + name_32 = node.name; variableDeclarationNode = node; // binding elements are added only for variable declarations // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 211 /* VariableDeclaration */) { + while (variableDeclarationNode && variableDeclarationNode.kind !== 215 /* VariableDeclaration */) { variableDeclarationNode = variableDeclarationNode.parent; } ts.Debug.assert(variableDeclarationNode !== undefined); @@ -38873,24 +42242,24 @@ var ts; else { ts.Debug.assert(!ts.isBindingPattern(node.name)); variableDeclarationNode = node; - name_31 = node.name; + name_32 = node.name; } if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.constElement); + return createItem(node, getTextOfNode(name_32), ts.ScriptElementKind.constElement); } else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.letElement); + return createItem(node, getTextOfNode(name_32), ts.ScriptElementKind.letElement); } else { - return createItem(node, getTextOfNode(name_31), ts.ScriptElementKind.variableElement); + return createItem(node, getTextOfNode(name_32), ts.ScriptElementKind.variableElement); } - case 144 /* Constructor */: + case 146 /* Constructor */: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 230 /* ExportSpecifier */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: + case 234 /* ExportSpecifier */: + case 230 /* ImportSpecifier */: + case 225 /* ImportEqualsDeclaration */: + case 227 /* ImportClause */: + case 228 /* NamespaceImport */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); } return undefined; @@ -38920,29 +42289,29 @@ var ts; } function createTopLevelItem(node) { switch (node.kind) { - case 248 /* SourceFile */: + case 252 /* SourceFile */: return createSourceFileItem(node); - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: return createClassItem(node); - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: return createEnumItem(node); - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return createIterfaceItem(node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return createModuleItem(node); - case 213 /* FunctionDeclaration */: + case 217 /* FunctionDeclaration */: return createFunctionItem(node); } return undefined; function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. - if (moduleDeclaration.name.kind === 9 /* StringLiteral */) { + if (ts.isAmbientModule(moduleDeclaration)) { return getTextOfNode(moduleDeclaration.name); } // 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 === 218 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 222 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -38954,7 +42323,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 === 192 /* Block */) { + if (node.body && node.body.kind === 196 /* 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)); } @@ -38975,7 +42344,7 @@ var ts; var childItems; if (node.members) { var constructor = ts.forEach(node.members, function (member) { - return member.kind === 144 /* Constructor */ && member; + return member.kind === 146 /* 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 @@ -38999,7 +42368,7 @@ var ts; } } function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 136 /* ComputedPropertyName */; }); + return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 138 /* ComputedPropertyName */; }); } /** * Like removeComputedProperties, but retains the properties with well known symbol names @@ -39008,13 +42377,13 @@ var ts; return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); } function getInnermostModule(node) { - while (node.body.kind === 218 /* ModuleDeclaration */) { + while (node.body.kind === 222 /* ModuleDeclaration */) { node = node.body; } return node; } function getNodeSpan(node) { - return node.kind === 248 /* SourceFile */ + return node.kind === 252 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } @@ -39046,12 +42415,11 @@ var ts; } function createPatternMatcher(pattern) { // We'll often see the same candidate string many times when searching (For example, when - // we see the name of a module that is used everywhere, or the name of an overload). As - // such, we cache the information we compute about the candidate for the life of this + // we see the name of a module that is used everywhere, or the name of an overload). As + // such, we cache the information we compute about the candidate for the life of this // pattern matcher so we don't have to compute it multiple times. var stringToWordSpans = {}; pattern = pattern.trim(); - var fullPatternSegment = createSegment(pattern); var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); return { @@ -39091,7 +42459,7 @@ var ts; // So far so good. Now break up the container for the candidate and check if all // the dotted parts match up correctly. var totalMatch = candidateMatch; - for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i--, j--) { + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { var segment = dotSeparatedSegments[i]; var containerName = candidateContainers[j]; var containerMatch = matchSegment(containerName, segment); @@ -39130,7 +42498,7 @@ var ts; if (index > 0) { // c) If the part is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring - // match. + // match. // // Note: We only have a substring match if the lowercase part is prefix match of some // word part. That way we don't match something like 'Class' when the user types 'a'. @@ -39170,8 +42538,8 @@ var ts; if (isLowercase) { // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? // We could check every character boundary start of the candidate for the pattern. However, that's - // an m * n operation in the wost case. Instead, find the first instance of the pattern - // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to // filter the list based on a substring that starts on a capital letter and also with a lowercase one. // (Pattern: fogbar, Candidate: quuxfogbarFogBar). if (chunk.text.length < candidate.length) { @@ -39223,7 +42591,7 @@ var ts; // // c) If the word is entirely lowercase, then check if it is contained anywhere in the // candidate in a case insensitive manner. If so, return that there was a substring - // match. + // match. // // Note: We only have a substring match if the lowercase part is prefix match of // some word part. That way we don't match something like 'Class' when the user @@ -39237,7 +42605,7 @@ var ts; // e) If the word was not entirely lowercase, then attempt a camel cased match as // well. // - // f) The word is all lower case. Is it a case insensitive substring of the candidate starting + // f) The word is all lower case. Is it a case insensitive substring of the candidate starting // on a part boundary of the candidate? // // Only if all words have some sort of match is the pattern considered matched. @@ -39287,7 +42655,7 @@ var ts; // Note: we may have more pattern parts than candidate parts. This is because multiple // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U - // and I will both match in UI. + // and I will both match in UI. var currentCandidate = 0; var currentChunkSpan = 0; var firstMatch = undefined; @@ -39316,13 +42684,13 @@ var ts; // Consider the case of matching SiUI against SimpleUIElement. The candidate parts // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to - // still keep matching pattern parts against that candidate part. + // still keep matching pattern parts against that candidate part. for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; if (gotOneMatchThisCandidate) { // We've already gotten one pattern part match in this candidate. We will // only continue trying to consumer pattern parts if the last part and this - // part are both upper case. + // part are both upper case. if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { break; @@ -39352,42 +42720,6 @@ var ts; } } ts.createPatternMatcher = createPatternMatcher; - // Helper function to compare two matches to determine which is better. Matches are first - // ordered by kind (so all prefix matches always beat all substring matches). Then, if the - // match is a camel case match, the relative weights of the match are used to determine - // which is better (with a greater weight being better). Then if the match is of the same - // type, then a case sensitive match is considered better than an insensitive one. - function patternMatchCompareTo(match1, match2) { - return compareType(match1, match2) || - compareCamelCase(match1, match2) || - compareCase(match1, match2) || - comparePunctuation(match1, match2); - } - function comparePunctuation(result1, result2) { - // Consider a match to be better if it was successful without stripping punctuation - // versus a match that had to strip punctuation to succeed. - if (result1.punctuationStripped !== result2.punctuationStripped) { - return result1.punctuationStripped ? 1 : -1; - } - return 0; - } - function compareCase(result1, result2) { - if (result1.isCaseSensitive !== result2.isCaseSensitive) { - return result1.isCaseSensitive ? -1 : 1; - } - return 0; - } - function compareType(result1, result2) { - return result1.kind - result2.kind; - } - function compareCamelCase(result1, result2) { - if (result1.kind === PatternMatchKind.camelCase && result2.kind === PatternMatchKind.camelCase) { - // Swap the values here. If result1 has a higher weight, then we want it to come - // first. - return result2.camelCaseWeight - result1.camelCaseWeight; - } - return 0; - } function createSegment(text) { return { totalTextChunk: createTextChunk(text), @@ -39406,7 +42738,7 @@ var ts; if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { return false; } - // TODO: find a way to determine this for any unicode characters in a + // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. var str = String.fromCharCode(ch); return str === str.toUpperCase(); @@ -39419,19 +42751,11 @@ var ts; if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { return false; } - // TODO: find a way to determine this for any unicode characters in a + // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. var str = String.fromCharCode(ch); return str === str.toLowerCase(); } - function containsUpperCaseLetter(string) { - for (var i = 0, n = string.length; i < n; i++) { - if (isUpperCaseLetter(string.charCodeAt(i))) { - return true; - } - } - return false; - } function startsWith(string, search) { for (var i = 0, n = search.length; i < n; i++) { if (string.charCodeAt(i) !== search.charCodeAt(i)) { @@ -39468,7 +42792,7 @@ var ts; if (ch < 127 /* maxAsciiCharacter */) { return ch; } - // TODO: find a way to compute this for any unicode characters in a + // TODO: find a way to compute this for any unicode characters in a // non-allocating manner. return String.fromCharCode(ch).toLowerCase().charCodeAt(0); } @@ -39486,9 +42810,10 @@ var ts; for (var i = 0; i < pattern.length; i++) { var ch = pattern.charCodeAt(i); if (isWordChar(ch)) { - if (wordLength++ === 0) { + if (wordLength === 0) { wordStart = i; } + wordLength++; } else { if (wordLength > 0) { @@ -39619,7 +42944,7 @@ var ts; var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); // See if the casing indicates we're starting a new word. Note: if we're breaking on // words, then just seeing an upper case character isn't enough. Instead, it has to - // be uppercase and the previous character can't be uppercase. + // be uppercase and the previous character can't be uppercase. // // For example, breaking "AddMetadata" on words would make: Add Metadata // @@ -39802,14 +43127,14 @@ var ts; if (!candidates.length) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - if (ts.isJavaScript(sourceFile.fileName)) { + if (ts.isSourceFileJavaScript(sourceFile)) { return createJavaScriptSignatureHelpItems(argumentInfo); } return undefined; } return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo); function createJavaScriptSignatureHelpItems(argumentInfo) { - if (argumentInfo.invocation.kind !== 168 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 172 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. @@ -39817,7 +43142,7 @@ var ts; var expression = callExpression.expression; var name = expression.kind === 69 /* Identifier */ ? expression - : expression.kind === 166 /* PropertyAccessExpression */ + : expression.kind === 170 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.text) { @@ -39829,8 +43154,8 @@ var ts; var nameToDeclarations = sourceFile_1.getNamedDeclarations(); var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { - for (var _b = 0, declarations_7 = declarations; _b < declarations_7.length; _b++) { - var declaration = declarations_7[_b]; + for (var _b = 0, declarations_8 = declarations; _b < declarations_8.length; _b++) { + var declaration = declarations_8[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -39850,7 +43175,7 @@ var ts; * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node) { - if (node.parent.kind === 168 /* CallExpression */ || node.parent.kind === 169 /* NewExpression */) { + if (node.parent.kind === 172 /* CallExpression */ || node.parent.kind === 173 /* NewExpression */) { var callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session @@ -39903,25 +43228,25 @@ var ts; }; } } - else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 174 /* 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, /*argumentIndex*/ 0); } } - else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 174 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 187 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - else if (node.parent.kind === 190 /* TemplateSpan */ && node.parent.parent.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 194 /* TemplateSpan */ && node.parent.parent.parent.kind === 174 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 187 /* TemplateExpression */); // If we're just after a template tail, don't show signature help. if (node.kind === 14 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { return undefined; @@ -40039,7 +43364,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 === 183 /* TemplateExpression */) { + if (template.kind === 187 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -40048,7 +43373,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { - for (var n = node; n.kind !== 248 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 252 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -40248,40 +43573,40 @@ var ts; return false; } switch (n.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 165 /* ObjectLiteralExpression */: - case 161 /* ObjectBindingPattern */: - case 155 /* TypeLiteral */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 220 /* CaseBlock */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 169 /* ObjectLiteralExpression */: + case 165 /* ObjectBindingPattern */: + case 157 /* TypeLiteral */: + case 196 /* Block */: + case 223 /* ModuleBlock */: + case 224 /* CaseBlock */: return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); - case 244 /* CatchClause */: + case 248 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 169 /* NewExpression */: + case 173 /* NewExpression */: if (!n.arguments) { return true; } // fall through - case 168 /* CallExpression */: - case 172 /* ParenthesizedExpression */: - case 160 /* ParenthesizedType */: + case 172 /* CallExpression */: + case 176 /* ParenthesizedExpression */: + case 162 /* ParenthesizedType */: return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 148 /* ConstructSignature */: - case 147 /* CallSignature */: - case 174 /* ArrowFunction */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 150 /* ConstructSignature */: + case 149 /* CallSignature */: + case 178 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -40291,64 +43616,64 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 196 /* IfStatement */: + case 200 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 195 /* ExpressionStatement */: + case 199 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 23 /* SemicolonToken */); - case 164 /* ArrayLiteralExpression */: - case 162 /* ArrayBindingPattern */: - case 167 /* ElementAccessExpression */: - case 136 /* ComputedPropertyName */: - case 157 /* TupleType */: + case 168 /* ArrayLiteralExpression */: + case 166 /* ArrayBindingPattern */: + case 171 /* ElementAccessExpression */: + case 138 /* ComputedPropertyName */: + case 159 /* TupleType */: return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); - case 149 /* IndexSignature */: + case 151 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 245 /* CaseClause */: + case 246 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicitly always consider them non-completed return false; - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 202 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 197 /* DoStatement */: + case 201 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); } return isCompletedNode(n.statement, sourceFile); - case 154 /* TypeQuery */: + case 156 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 176 /* TypeOfExpression */: - case 175 /* DeleteExpression */: - case 177 /* VoidExpression */: - case 184 /* YieldExpression */: - case 185 /* SpreadElementExpression */: + case 180 /* TypeOfExpression */: + case 179 /* DeleteExpression */: + case 181 /* VoidExpression */: + case 188 /* YieldExpression */: + case 189 /* SpreadElementExpression */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 170 /* TaggedTemplateExpression */: + case 174 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 183 /* TemplateExpression */: + case 187 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 190 /* TemplateSpan */: + case 194 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 179 /* PrefixUnaryExpression */: + case 183 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 181 /* BinaryExpression */: + case 185 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 182 /* ConditionalExpression */: + case 186 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -40404,7 +43729,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 === 271 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 275 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -40510,7 +43835,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 236 /* JsxText */) { + if (isToken(n) || n.kind === 240 /* JsxText */) { return n; } var children = n.getChildren(); @@ -40518,7 +43843,7 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 236 /* JsxText */) { + if (isToken(n) || n.kind === 240 /* JsxText */) { return n; } var children = n.getChildren(); @@ -40532,10 +43857,10 @@ var ts; // if no - position is in the node itself so we should recurse in it. // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). // if this is the case - then we should assume that token in question is located in previous child. - if (position < child.end && (nodeHasTokens(child) || child.kind === 236 /* JsxText */)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 240 /* JsxText */)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 236 /* JsxText */ && start === child.end); // whitespace only JsxText + (child.kind === 240 /* JsxText */ && start === child.end); // whitespace only JsxText if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); @@ -40547,8 +43872,8 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 248 /* SourceFile */); - // Here we know that none of child token nodes embrace the position, + ts.Debug.assert(startNode !== undefined || n.kind === 252 /* 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. // Namely we are skipping the check: 'position < node.end' @@ -40569,7 +43894,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); - return token && token.kind === 9 /* StringLiteral */ && position > token.getStart(); + return token && (token.kind === 9 /* StringLiteral */ || token.kind === 164 /* StringLiteralType */) && position > token.getStart(); } ts.isInString = isInString; function isInComment(sourceFile, position) { @@ -40655,17 +43980,17 @@ var ts; function getNodeModifiers(node) { var flags = ts.getCombinedNodeFlags(node); var result = []; - if (flags & 16 /* Private */) + if (flags & 8 /* Private */) result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 32 /* Protected */) + if (flags & 16 /* Protected */) result.push(ts.ScriptElementKindModifier.protectedMemberModifier); - if (flags & 8 /* Public */) + if (flags & 4 /* Public */) result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 64 /* Static */) + if (flags & 32 /* Static */) result.push(ts.ScriptElementKindModifier.staticModifier); if (flags & 128 /* Abstract */) result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 2 /* Export */) + if (flags & 1 /* Export */) result.push(ts.ScriptElementKindModifier.exportedModifier); if (ts.isInAmbientContext(node)) result.push(ts.ScriptElementKindModifier.ambientModifier); @@ -40673,17 +43998,17 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 151 /* TypeReference */ || node.kind === 168 /* CallExpression */) { + if (node.kind === 153 /* TypeReference */ || node.kind === 172 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 214 /* ClassDeclaration */ || node.kind === 215 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 218 /* ClassDeclaration */ || node.kind === 219 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 134 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 136 /* LastToken */; } ts.isToken = isToken; function isWord(kind) { @@ -40699,6 +44024,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ + || kind === 164 /* StringLiteralType */ || kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; @@ -40741,13 +44067,40 @@ var ts; return true; } ts.compareDataObjects = compareDataObjects; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 168 /* ArrayLiteralExpression */ || + node.kind === 169 /* ObjectLiteralExpression */) { + // [a,b,c] from: + // [a, b, c] = someExpression; + if (node.parent.kind === 185 /* BinaryExpression */ && + node.parent.left === node && + node.parent.operatorToken.kind === 56 /* EqualsToken */) { + return true; + } + // [a, b, c] from: + // for([a, b, c] of expression) + if (node.parent.kind === 205 /* ForOfStatement */ && + node.parent.initializer === node) { + return true; + } + // [a, b, c] of + // [x, [a, b, c] ] = someExpression + // or + // {x, a: {a, b, c} } = someExpression + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 249 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 138 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 140 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -40935,7 +44288,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 226 /* ImportSpecifier */ || location.parent.kind === 230 /* ExportSpecifier */) && + (location.parent.kind === 230 /* ImportSpecifier */ || location.parent.kind === 234 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -40992,6 +44345,7 @@ var ts; advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, close: function () { ts.Debug.assert(scanner !== undefined); @@ -41057,10 +44411,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 238 /* JsxAttribute */: - case 235 /* JsxOpeningElement */: - case 237 /* JsxClosingElement */: - case 234 /* JsxSelfClosingElement */: + case 242 /* JsxAttribute */: + case 239 /* JsxOpeningElement */: + case 241 /* JsxClosingElement */: + case 238 /* JsxSelfClosingElement */: return node.kind === 69 /* Identifier */; } } @@ -41267,7 +44621,7 @@ var ts; return false; }; return FormattingContext; - })(); + }()); formatting.FormattingContext = FormattingContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41306,7 +44660,7 @@ var ts; "flag=" + this.Flag + "]"; }; return Rule; - })(); + }()); formatting.Rule = Rule; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41353,7 +44707,7 @@ var ts; return new RuleDescriptor(left, right); }; return RuleDescriptor; - })(); + }()); formatting.RuleDescriptor = RuleDescriptor; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41395,7 +44749,7 @@ var ts; return result; }; return RuleOperation; - })(); + }()); formatting.RuleOperation = RuleOperation; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41430,7 +44784,7 @@ var ts; }; RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; - })(); + }()); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41449,25 +44803,25 @@ var ts; this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */)); this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */)); // Space after keyword but not before ; or : or ? - this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); - this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); - this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); + this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); + this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Space after }. - this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); + this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied - this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 80 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 104 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 20 /* CloseBracketToken */, 24 /* CommaToken */, 23 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 80 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 104 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 20 /* CloseBracketToken */, 24 /* CommaToken */, 23 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // No space for dot - this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // No space before and after indexer - this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); // Place a space before open brace in a function declaration this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); @@ -41480,7 +44834,7 @@ var ts; // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); - this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); + this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); // Insert new line after { and before } in multi-line contexts. this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); // For functions and control block place } on a new line [multi-line rule] @@ -41488,149 +44842,146 @@ var ts; // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. - this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // More unary operator special-casing. // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: // 1 - -2 --X--> 1--2 // a + ++b --X--> a+++b - this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41 /* PlusPlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42 /* MinusMinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102 /* VarKeyword */, 98 /* ThrowKeyword */, 92 /* NewKeyword */, 78 /* DeleteKeyword */, 94 /* ReturnKeyword */, 101 /* TypeOfKeyword */, 119 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108 /* LetKeyword */, 74 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); + this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41 /* PlusPlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42 /* MinusMinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102 /* VarKeyword */, 98 /* ThrowKeyword */, 92 /* NewKeyword */, 78 /* DeleteKeyword */, 94 /* ReturnKeyword */, 101 /* TypeOfKeyword */, 119 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108 /* LetKeyword */, 74 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); + this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(87 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); - this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); - this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); - this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); + this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); + this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] - this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotForContext), 2 /* Space */)); + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotForContext), 2 /* Space */)); // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. - this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // get x() {} // set x(val) {} - this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123 /* GetKeyword */, 129 /* SetKeyword */]), 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123 /* GetKeyword */, 130 /* SetKeyword */]), 69 /* 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 */)); + this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); // TypeScript-specific higher priority rules // 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(121 /* ConstructorKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(121 /* ConstructorKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 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([125 /* ModuleKeyword */, 127 /* RequireKeyword */]), 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125 /* ModuleKeyword */, 128 /* RequireKeyword */]), 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Add a space around certain TypeScript keywords - this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 73 /* ClassKeyword */, 122 /* DeclareKeyword */, 77 /* DefaultKeyword */, 81 /* EnumKeyword */, 82 /* ExportKeyword */, 83 /* ExtendsKeyword */, 123 /* GetKeyword */, 106 /* ImplementsKeyword */, 89 /* ImportKeyword */, 107 /* InterfaceKeyword */, 125 /* ModuleKeyword */, 126 /* NamespaceKeyword */, 110 /* PrivateKeyword */, 112 /* PublicKeyword */, 111 /* ProtectedKeyword */, 129 /* SetKeyword */, 113 /* StaticKeyword */, 132 /* TypeKeyword */]), 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([83 /* ExtendsKeyword */, 106 /* ImplementsKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 73 /* ClassKeyword */, 122 /* DeclareKeyword */, 77 /* DefaultKeyword */, 81 /* EnumKeyword */, 82 /* ExportKeyword */, 83 /* ExtendsKeyword */, 123 /* GetKeyword */, 106 /* ImplementsKeyword */, 89 /* ImportKeyword */, 107 /* InterfaceKeyword */, 125 /* ModuleKeyword */, 126 /* NamespaceKeyword */, 110 /* PrivateKeyword */, 112 /* PublicKeyword */, 111 /* ProtectedKeyword */, 130 /* SetKeyword */, 113 /* StaticKeyword */, 133 /* TypeKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([83 /* ExtendsKeyword */, 106 /* ImplementsKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 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(9 /* StringLiteral */, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); // Lambda expressions - this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Optional parameters and let args - this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22 /* DotDotDotToken */, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22 /* DotDotDotToken */, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); // generics and type assertions - this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseParenToken */, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([17 /* OpenParenToken */, 19 /* OpenBracketToken */, 27 /* GreaterThanToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); - this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); + this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseParenToken */, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([17 /* OpenParenToken */, 19 /* OpenBracketToken */, 27 /* GreaterThanToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); // Remove spaces in empty interface literals. e.g.: x: {} - this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); + this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); // decorators - this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* 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([115 /* AbstractKeyword */, 69 /* Identifier */, 82 /* ExportKeyword */, 77 /* DefaultKeyword */, 73 /* ClassKeyword */, 113 /* StaticKeyword */, 112 /* PublicKeyword */, 110 /* PrivateKeyword */, 111 /* ProtectedKeyword */, 123 /* GetKeyword */, 129 /* SetKeyword */, 19 /* OpenBracketToken */, 37 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); + this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 69 /* Identifier */, 82 /* ExportKeyword */, 77 /* DefaultKeyword */, 73 /* ClassKeyword */, 113 /* StaticKeyword */, 112 /* PublicKeyword */, 110 /* PrivateKeyword */, 111 /* ProtectedKeyword */, 123 /* GetKeyword */, 130 /* SetKeyword */, 19 /* OpenBracketToken */, 37 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(37 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); - this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114 /* YieldKeyword */, 37 /* 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([114 /* YieldKeyword */, 37 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114 /* YieldKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114 /* YieldKeyword */, 37 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); // Async-await - this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsSameLineTokenContext), 2 /* Space */)); - this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // template string - this.SpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // These rules are higher in priority than user-configurable rules. - this.HighPriorityCommonRules = - [ - this.IgnoreBeforeComment, this.IgnoreAfterLineComment, - this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, - this.NoSpaceAfterQuestionMark, - this.NoSpaceBeforeDot, this.NoSpaceAfterDot, - this.NoSpaceAfterUnaryPrefixOperator, - this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, - this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, - this.SpaceAfterPostincrementWhenFollowedByAdd, - this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, - this.SpaceAfterPostdecrementWhenFollowedBySubtract, - this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, - 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, - this.NoSpaceBeforeOpenParenInFuncCall, - this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, - this.SpaceAfterVoidOperator, - this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, - this.SpaceBetweenTagAndTemplateString, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, - // TypeScript-specific rules - this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, - this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, - this.SpaceAfterModuleName, - this.SpaceAfterArrow, - this.NoSpaceAfterEllipsis, - this.NoSpaceAfterOptionalParameters, - this.NoSpaceBetweenEmptyInterfaceBraceBrackets, - this.NoSpaceBeforeOpenAngularBracket, - this.NoSpaceBetweenCloseParenAndAngularBracket, - this.NoSpaceAfterOpenAngularBracket, - this.NoSpaceBeforeCloseAngularBracket, - this.NoSpaceAfterCloseAngularBracket, - this.NoSpaceAfterTypeAssertion, - this.SpaceBeforeAt, - this.NoSpaceAfterAt, - this.SpaceAfterDecorator, - ]; + this.HighPriorityCommonRules = [ + this.IgnoreBeforeComment, this.IgnoreAfterLineComment, + this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, + this.NoSpaceAfterQuestionMark, + this.NoSpaceBeforeDot, this.NoSpaceAfterDot, + this.NoSpaceAfterUnaryPrefixOperator, + this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, + this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, + this.SpaceAfterPostincrementWhenFollowedByAdd, + this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, + this.SpaceAfterPostdecrementWhenFollowedBySubtract, + this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, + 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, + this.NoSpaceBeforeOpenParenInFuncCall, + this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, + this.SpaceAfterVoidOperator, + this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, + this.NoSpaceBetweenTagAndTemplateString, + // TypeScript-specific rules + this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, + this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, + this.SpaceAfterModuleName, + this.SpaceBeforeArrow, this.SpaceAfterArrow, + this.NoSpaceAfterEllipsis, + this.NoSpaceAfterOptionalParameters, + this.NoSpaceBetweenEmptyInterfaceBraceBrackets, + this.NoSpaceBeforeOpenAngularBracket, + this.NoSpaceBetweenCloseParenAndAngularBracket, + this.NoSpaceAfterOpenAngularBracket, + this.NoSpaceBeforeCloseAngularBracket, + this.NoSpaceAfterCloseAngularBracket, + this.NoSpaceAfterTypeAssertion, + this.SpaceBeforeAt, + this.NoSpaceAfterAt, + this.SpaceAfterDecorator, + ]; // These rules are lower in priority than user-configurable rules. - this.LowPriorityCommonRules = - [ - this.NoSpaceBeforeSemicolon, - this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, - this.NoSpaceBeforeComma, - this.NoSpaceBeforeOpenBracket, - this.NoSpaceAfterCloseBracket, - this.SpaceAfterSemicolon, - this.NoSpaceBeforeOpenParenInFuncDecl, - this.SpaceBetweenStatements, this.SpaceAfterTryFinally - ]; + this.LowPriorityCommonRules = [ + this.NoSpaceBeforeSemicolon, + this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, + this.NoSpaceBeforeComma, + this.NoSpaceBeforeOpenBracket, + this.NoSpaceAfterCloseBracket, + this.SpaceAfterSemicolon, + this.NoSpaceBeforeOpenParenInFuncDecl, + this.SpaceBetweenStatements, this.SpaceAfterTryFinally + ]; /// /// Rules controlled by user options /// // Insert space after comma delimiter - this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNextTokenNotCloseBracket), 2 /* Space */)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Insert space before and after binary operators - this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); - this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); - this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); + this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); + this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); // Insert space after keywords in control flow statements this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2 /* Space */)); this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8 /* Delete */)); @@ -41642,29 +44993,34 @@ var ts; // Open Brace braces after control block this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Insert space after semicolon in for statement - this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); - this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); // Insert space after opening and before closing nonempty parenthesis - this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenParenToken */, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenParenToken */, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); // Insert space after opening and before closing nonempty brackets - this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); - this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenBracketToken */, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); - this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* 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, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenBracketToken */, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + // Insert space after opening and before closing template string braces + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */)); + this.SpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */)); // Insert space after function keyword for anonymous functions this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_32 in o) { - if (o[name_32] === rule) { - return name_32; + for (var name_33 in o) { + if (o[name_33] === rule) { + return name_33; } } throw new Error("Unknown rule"); @@ -41673,40 +45029,40 @@ var ts; /// Contexts /// Rules.IsForContext = function (context) { - return context.contextNode.kind === 199 /* ForStatement */; + return context.contextNode.kind === 203 /* ForStatement */; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); }; Rules.IsBinaryOpContext = function (context) { switch (context.contextNode.kind) { - case 181 /* BinaryExpression */: - case 182 /* ConditionalExpression */: - case 189 /* AsExpression */: - case 150 /* TypePredicate */: - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 185 /* BinaryExpression */: + case 186 /* ConditionalExpression */: + case 193 /* AsExpression */: + case 152 /* TypePredicate */: + case 160 /* UnionType */: + case 161 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 163 /* BindingElement */: + case 167 /* BindingElement */: // equals in type X = ... - case 216 /* TypeAliasDeclaration */: + case 220 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 211 /* VariableDeclaration */: + case 215 /* VariableDeclaration */: // equal in p = 0; - case 138 /* Parameter */: - case 247 /* EnumMember */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 140 /* Parameter */: + case 251 /* EnumMember */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return context.currentTokenSpan.kind === 56 /* EqualsToken */ || context.nextTokenSpan.kind === 56 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 200 /* ForInStatement */: + case 204 /* ForInStatement */: return context.currentTokenSpan.kind === 90 /* InKeyword */ || context.nextTokenSpan.kind === 90 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 201 /* ForOfStatement */: - return context.currentTokenSpan.kind === 134 /* OfKeyword */ || context.nextTokenSpan.kind === 134 /* OfKeyword */; + case 205 /* ForOfStatement */: + return context.currentTokenSpan.kind === 136 /* OfKeyword */ || context.nextTokenSpan.kind === 136 /* OfKeyword */; } return false; }; @@ -41714,7 +45070,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 182 /* ConditionalExpression */; + return context.contextNode.kind === 186 /* ConditionalExpression */; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. @@ -41758,93 +45114,93 @@ var ts; return true; } switch (node.kind) { - case 192 /* Block */: - case 220 /* CaseBlock */: - case 165 /* ObjectLiteralExpression */: - case 219 /* ModuleBlock */: + case 196 /* Block */: + case 224 /* CaseBlock */: + case 169 /* ObjectLiteralExpression */: + case 223 /* ModuleBlock */: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: //case SyntaxKind.MemberFunctionDeclaration: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: ///case SyntaxKind.MethodSignature: - case 147 /* CallSignature */: - case 173 /* FunctionExpression */: - case 144 /* Constructor */: - case 174 /* ArrowFunction */: + case 149 /* CallSignature */: + case 177 /* FunctionExpression */: + case 146 /* Constructor */: + case 178 /* ArrowFunction */: //case SyntaxKind.ConstructorDeclaration: //case SyntaxKind.SimpleArrowFunctionExpression: //case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 213 /* FunctionDeclaration */ || context.contextNode.kind === 173 /* FunctionExpression */; + return context.contextNode.kind === 217 /* FunctionDeclaration */ || context.contextNode.kind === 177 /* FunctionExpression */; }; Rules.IsTypeScriptDeclWithBlockContext = function (context) { return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); }; Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { switch (node.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 155 /* TypeLiteral */: - case 218 /* ModuleDeclaration */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 157 /* TypeLiteral */: + case 222 /* ModuleDeclaration */: return true; } return false; }; Rules.IsAfterCodeBlockContext = function (context) { switch (context.currentTokenParent.kind) { - case 214 /* ClassDeclaration */: - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: - case 192 /* Block */: - case 244 /* CatchClause */: - case 219 /* ModuleBlock */: - case 206 /* SwitchStatement */: + case 218 /* ClassDeclaration */: + case 222 /* ModuleDeclaration */: + case 221 /* EnumDeclaration */: + case 196 /* Block */: + case 248 /* CatchClause */: + case 223 /* ModuleBlock */: + case 210 /* SwitchStatement */: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 196 /* IfStatement */: - case 206 /* SwitchStatement */: - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: - case 209 /* TryStatement */: - case 197 /* DoStatement */: - case 205 /* WithStatement */: + case 200 /* IfStatement */: + case 210 /* SwitchStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 202 /* WhileStatement */: + case 213 /* TryStatement */: + case 201 /* DoStatement */: + case 209 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 244 /* CatchClause */: + case 248 /* CatchClause */: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 165 /* ObjectLiteralExpression */; + return context.contextNode.kind === 169 /* ObjectLiteralExpression */; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 168 /* CallExpression */; + return context.contextNode.kind === 172 /* CallExpression */; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 169 /* NewExpression */; + return context.contextNode.kind === 173 /* NewExpression */; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); @@ -41852,11 +45208,14 @@ var ts; Rules.IsPreviousTokenNotComma = function (context) { return context.currentTokenSpan.kind !== 24 /* CommaToken */; }; - Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 174 /* ArrowFunction */; + Rules.IsNextTokenNotCloseBracket = function (context) { + return context.nextTokenSpan.kind !== 20 /* CloseBracketToken */; }; - Rules.IsSameLineTokenContext = function (context) { - return context.TokensAreOnSameLine(); + Rules.IsArrowFunctionContext = function (context) { + return context.contextNode.kind === 178 /* ArrowFunction */; + }; + Rules.IsNonJsxSameLineTokenContext = function (context) { + return context.TokensAreOnSameLine() && context.contextNode.kind !== 240 /* JsxText */; }; Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); @@ -41871,41 +45230,41 @@ var ts; while (ts.isExpression(node)) { node = node.parent; } - return node.kind === 139 /* Decorator */; + return node.kind === 141 /* Decorator */; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 212 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 216 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; }; Rules.IsNotFormatOnEnter = function (context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; }; Rules.IsModuleDeclContext = function (context) { - return context.contextNode.kind === 218 /* ModuleDeclaration */; + return context.contextNode.kind === 222 /* ModuleDeclaration */; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 155 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 157 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; }; Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { if (token.kind !== 25 /* LessThanToken */ && token.kind !== 27 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 151 /* TypeReference */: - case 171 /* TypeAssertionExpression */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 188 /* ExpressionWithTypeArguments */: + case 153 /* TypeReference */: + case 175 /* TypeAssertionExpression */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 219 /* InterfaceDeclaration */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 192 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -41916,16 +45275,16 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 171 /* TypeAssertionExpression */; + return context.contextNode.kind === 175 /* TypeAssertionExpression */; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 177 /* VoidExpression */; + return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 181 /* VoidExpression */; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 184 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 188 /* YieldExpression */ && context.contextNode.expression !== undefined; }; return Rules; - })(); + }()); formatting.Rules = Rules; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41946,7 +45305,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 134 /* LastToken */ + 1; + this.mapRowLength = 136 /* 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); @@ -41993,7 +45352,7 @@ var ts; return null; }; return RulesMap; - })(); + }()); formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; @@ -42045,7 +45404,7 @@ var ts; this.rulesInsertionIndexBitmap = temp; }; return RulesBucketConstructionState; - })(); + }()); formatting.RulesBucketConstructionState = RulesBucketConstructionState; var RulesBucket = (function () { function RulesBucket() { @@ -42080,7 +45439,7 @@ var ts; state.IncreaseInsertionIndex(position); }; return RulesBucket; - })(); + }()); formatting.RulesBucket = RulesBucket; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42096,7 +45455,7 @@ var ts; function TokenRangeAccess(from, to, except) { this.tokens = []; for (var token = from; token <= to; token++) { - if (except.indexOf(token) < 0) { + if (ts.indexOf(except, token) < 0) { this.tokens.push(token); } } @@ -42108,7 +45467,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenRangeAccess; - })(); + }()); Shared.TokenRangeAccess = TokenRangeAccess; var TokenValuesAccess = (function () { function TokenValuesAccess(tks) { @@ -42121,7 +45480,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenValuesAccess; - })(); + }()); Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { @@ -42134,14 +45493,14 @@ var ts; return tokenValue === this.token; }; return TokenSingleValueAccess; - })(); + }()); Shared.TokenSingleValueAccess = TokenSingleValueAccess; var TokenAllAccess = (function () { function TokenAllAccess() { } TokenAllAccess.prototype.GetTokens = function () { var result = []; - for (var token = 0 /* FirstToken */; token <= 134 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 136 /* LastToken */; token++) { result.push(token); } return result; @@ -42153,7 +45512,7 @@ var ts; return "[allTokens]"; }; return TokenAllAccess; - })(); + }()); Shared.TokenAllAccess = TokenAllAccess; var TokenRange = (function () { function TokenRange(tokenAccess) { @@ -42183,9 +45542,9 @@ var ts; }; TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 134 /* LastKeyword */); + TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 136 /* LastKeyword */); TokenRange.BinaryOperators = TokenRange.FromRange(25 /* FirstBinaryOperator */, 68 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 134 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 136 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41 /* PlusPlusToken */, 42 /* MinusMinusToken */, 50 /* TildeToken */, 49 /* ExclamationToken */]); TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 69 /* Identifier */, 17 /* OpenParenToken */, 19 /* OpenBracketToken */, 15 /* OpenBraceToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); @@ -42193,9 +45552,9 @@ var ts; TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); - TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 128 /* NumberKeyword */, 130 /* StringKeyword */, 120 /* BooleanKeyword */, 131 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); + TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 129 /* NumberKeyword */, 131 /* StringKeyword */, 120 /* BooleanKeyword */, 132 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); return TokenRange; - })(); + }()); Shared.TokenRange = TokenRange; })(Shared = formatting.Shared || (formatting.Shared = {})); })(formatting = ts.formatting || (ts.formatting = {})); @@ -42281,6 +45640,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); + } + else { + rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); + } if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } @@ -42306,7 +45673,7 @@ var ts; return rules; }; return RulesProvider; - })(); + }()); formatting.RulesProvider = RulesProvider; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -42407,17 +45774,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 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 192 /* Block */ && ts.rangeContainsRange(body.statements, node); - case 248 /* SourceFile */: - case 192 /* Block */: - case 219 /* ModuleBlock */: + return body && body.kind === 196 /* Block */ && ts.rangeContainsRange(body.statements, node); + case 252 /* SourceFile */: + case 196 /* Block */: + case 223 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 244 /* CatchClause */: + case 248 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -42515,17 +45882,17 @@ var ts; */ function getOwnOrInheritedDelta(n, options, sourceFile) { var previousLine = -1 /* Unknown */; - var childKind = 0 /* Unknown */; + var child; while (n) { var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; if (previousLine !== -1 /* Unknown */ && line !== previousLine) { break; } - if (formatting.SmartIndenter.shouldIndentChildNode(n.kind, childKind)) { + if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { return options.IndentSize; } previousLine = line; - childKind = n.kind; + child = n; n = n.parent; } return 0; @@ -42555,6 +45922,13 @@ var ts; var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined); + trimTrailingWhitespacesForRemainingRange(); + } + } formattingScanner.close(); return edits; // local functions @@ -42566,7 +45940,8 @@ var ts; * to inherited indentation from its predecessors. */ function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { - if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { if (inheritedIndentation !== -1 /* Unknown */) { return inheritedIndentation; } @@ -42583,32 +45958,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - if (indentation === -1 /* Unknown */) { - if (isSomeBlock(node.kind)) { - // blocks should be indented in - // - other blocks - // - source file - // - switch\default clauses - if (isSomeBlock(parent.kind) || - parent.kind === 248 /* SourceFile */ || - parent.kind === 241 /* CaseClause */ || - parent.kind === 242 /* DefaultClause */) { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - else { - indentation = parentDynamicIndentation.getIndentation(); - } - } - else { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); - } - else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); - } - } - } - var delta = formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -42616,7 +45966,15 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + } + else if (indentation === -1 /* Unknown */) { + if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + indentation = parentDynamicIndentation.getIndentation(); + } + else { + indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + } } return { indentation: indentation, @@ -42628,25 +45986,25 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 214 /* ClassDeclaration */: return 73 /* ClassKeyword */; - case 215 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; - case 213 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; - case 217 /* EnumDeclaration */: return 217 /* EnumDeclaration */; - case 145 /* GetAccessor */: return 123 /* GetKeyword */; - case 146 /* SetAccessor */: return 129 /* SetKeyword */; - case 143 /* MethodDeclaration */: + case 218 /* ClassDeclaration */: return 73 /* ClassKeyword */; + case 219 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; + case 217 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; + case 221 /* EnumDeclaration */: return 221 /* EnumDeclaration */; + case 147 /* GetAccessor */: return 123 /* GetKeyword */; + case 148 /* SetAccessor */: return 130 /* SetKeyword */; + case 145 /* MethodDeclaration */: if (node.asteriskToken) { return 37 /* AsteriskToken */; } // fall-through - case 141 /* PropertyDeclaration */: - case 138 /* Parameter */: + case 143 /* PropertyDeclaration */: + case 140 /* Parameter */: return node.name.kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { return { - getIndentationForComment: function (kind, tokenIndentation) { + getIndentationForComment: function (kind, tokenIndentation, container) { switch (kind) { // preceding comment to the token that closes the indentation scope inherits the indentation from the scope // .. { @@ -42655,11 +46013,11 @@ var ts; case 16 /* CloseBraceToken */: case 20 /* CloseBracketToken */: case 18 /* CloseParenToken */: - return indentation + delta; + return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind) { + getIndentationForToken: function (line, kind, container) { if (nodeStartLine !== line && node.decorators) { if (kind === getFirstNonDecoratorTokenOfNode(node)) { // if this token is the first token following the list of decorators, we do not need to indent @@ -42680,20 +46038,20 @@ var ts; return indentation; default: // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + delta : indentation; + return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; } }, getIndentation: function () { return indentation; }, - getDelta: function () { return delta; }, + getDelta: function (child) { return getEffectiveDelta(delta, child); }, recomputeIndentation: function (lineAdded) { - if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { indentation += options.IndentSize; } else { indentation -= options.IndentSize; } - if (formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */)) { + if (formatting.SmartIndenter.shouldIndentChildNode(node)) { delta = options.IndentSize; } else { @@ -42702,6 +46060,10 @@ var ts; } } }; + function getEffectiveDelta(delta, child) { + // Delta value should be zero when the node explicitly prevents indentation of the child node + return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0; + } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { @@ -42773,10 +46135,10 @@ var ts; // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules var tokenInfo = formattingScanner.readTokenInfo(child); ts.Debug.assert(tokenInfo.token.end === child.end); - consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 139 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 141 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; @@ -42827,7 +46189,7 @@ var ts; } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -42862,10 +46224,10 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : -1 /* Unknown */; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); + var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); var indentNextTokenOrTrivia = true; for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { var triviaItem = _a[_i]; @@ -42954,9 +46316,7 @@ var ts; } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line - trimTrailingWhitespaces = - (rule.Operation.Action & (4 /* NewLine */ | 2 /* Space */)) && - rule.Flag !== 1 /* CanDeleteNewLines */; + trimTrailingWhitespaces = !(rule.Operation.Action & 8 /* Delete */) && rule.Flag !== 1 /* CanDeleteNewLines */; } else { trimTrailingWhitespaces = true; @@ -43039,16 +46399,36 @@ var ts; if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { continue; } - var pos = lineEndPosition; - while (pos >= lineStartPosition && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { - pos--; - } - if (pos !== lineEndPosition) { - ts.Debug.assert(pos === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))); - recordDelete(pos + 1, lineEndPosition - pos); + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); } } } + /** + * @param start The position of the first character in range + * @param end The position of the last character in range + */ + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + /** + * Trimming will be done for lines after the previous range + */ + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } function newTextChange(start, len, newText) { return { span: ts.createTextSpan(start, len), newText: newText }; } @@ -43102,20 +46482,20 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 196 /* Block */: + case 223 /* ModuleBlock */: return true; } return false; } function getOpenTokenForList(node, list) { switch (node.kind) { - case 144 /* Constructor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 174 /* ArrowFunction */: + case 146 /* Constructor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 178 /* ArrowFunction */: if (node.typeParameters === list) { return 25 /* LessThanToken */; } @@ -43123,8 +46503,8 @@ var ts; return 17 /* OpenParenToken */; } break; - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: if (node.typeArguments === list) { return 25 /* LessThanToken */; } @@ -43132,7 +46512,7 @@ var ts; return 17 /* OpenParenToken */; } break; - case 151 /* TypeReference */: + case 153 /* TypeReference */: if (node.typeArguments === list) { return 25 /* LessThanToken */; } @@ -43161,7 +46541,7 @@ var ts; if (!options.ConvertTabsToSpaces) { var tabs = Math.floor(indentation / options.TabSize); var spaces = indentation - tabs * options.TabSize; - var tabString; + var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; } @@ -43174,7 +46554,7 @@ var ts; return spaces ? tabString + repeat(" ", spaces) : tabString; } else { - var spacesString; + var spacesString = void 0; var quotient = Math.floor(indentation / options.IndentSize); var remainder = indentation % options.IndentSize; if (!internedSpacesIndentation) { @@ -43248,7 +46628,7 @@ var ts; var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); } - if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 181 /* BinaryExpression */) { + if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 185 /* 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 */) { @@ -43262,7 +46642,7 @@ var ts; var currentStart; var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : 0 /* Unknown */)) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { currentStart = getStartLineAndCharacterForNode(current, sourceFile); if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) { indentationDelta = 0; @@ -43329,7 +46709,7 @@ var ts; } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line - if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { + if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { indentationDelta += options.IndentSize; } current = parent; @@ -43367,7 +46747,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 === 248 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 252 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -43400,7 +46780,7 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 196 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 200 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 80 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -43412,23 +46792,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 151 /* TypeReference */: + case 153 /* TypeReference */: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 165 /* ObjectLiteralExpression */: + case 169 /* ObjectLiteralExpression */: return node.parent.properties; - case 164 /* ArrayLiteralExpression */: + case 168 /* ArrayLiteralExpression */: return node.parent.elements; - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: { + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -43439,8 +46819,8 @@ var ts; } break; } - case 169 /* NewExpression */: - case 168 /* CallExpression */: { + case 173 /* NewExpression */: + case 172 /* CallExpression */: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -43470,8 +46850,8 @@ var ts; if (node.kind === 18 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 168 /* CallExpression */ || - node.parent.kind === 169 /* NewExpression */) && + if (node.parent && (node.parent.kind === 172 /* CallExpression */ || + node.parent.kind === 173 /* NewExpression */) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -43489,10 +46869,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 170 /* PropertyAccessExpression */: + case 171 /* ElementAccessExpression */: node = node.expression; break; default: @@ -43556,80 +46936,85 @@ var ts; SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; function nodeContentIsAlwaysIndented(kind) { switch (kind) { - case 195 /* ExpressionStatement */: - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 164 /* ArrayLiteralExpression */: - case 192 /* Block */: - case 219 /* ModuleBlock */: - case 165 /* ObjectLiteralExpression */: - case 155 /* TypeLiteral */: - case 157 /* TupleType */: - case 220 /* CaseBlock */: - case 242 /* DefaultClause */: - case 241 /* CaseClause */: - case 172 /* ParenthesizedExpression */: - case 166 /* PropertyAccessExpression */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 193 /* VariableStatement */: - case 211 /* VariableDeclaration */: - case 227 /* ExportAssignment */: - case 204 /* ReturnStatement */: - case 182 /* ConditionalExpression */: - case 162 /* ArrayBindingPattern */: - case 161 /* ObjectBindingPattern */: - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: - case 142 /* MethodSignature */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 138 /* Parameter */: - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 160 /* ParenthesizedType */: - case 170 /* TaggedTemplateExpression */: - case 178 /* AwaitExpression */: + case 199 /* ExpressionStatement */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 168 /* ArrayLiteralExpression */: + case 196 /* Block */: + case 223 /* ModuleBlock */: + case 169 /* ObjectLiteralExpression */: + case 157 /* TypeLiteral */: + case 159 /* TupleType */: + case 224 /* CaseBlock */: + case 246 /* DefaultClause */: + case 245 /* CaseClause */: + case 176 /* ParenthesizedExpression */: + case 170 /* PropertyAccessExpression */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 197 /* VariableStatement */: + case 215 /* VariableDeclaration */: + case 231 /* ExportAssignment */: + case 208 /* ReturnStatement */: + case 186 /* ConditionalExpression */: + case 166 /* ArrayBindingPattern */: + case 165 /* ObjectBindingPattern */: + case 239 /* JsxOpeningElement */: + case 238 /* JsxSelfClosingElement */: + case 244 /* JsxExpression */: + case 144 /* MethodSignature */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 140 /* Parameter */: + case 154 /* FunctionType */: + case 155 /* ConstructorType */: + case 162 /* ParenthesizedType */: + case 174 /* TaggedTemplateExpression */: + case 182 /* AwaitExpression */: + case 229 /* NamedImports */: return true; } return false; } + /* @internal */ + function nodeWillIndentChild(parent, child, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { + case 201 /* DoStatement */: + case 202 /* WhileStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 203 /* ForStatement */: + case 200 /* IfStatement */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 145 /* MethodDeclaration */: + case 178 /* ArrowFunction */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + return childKind !== 196 /* Block */; + case 237 /* JsxElement */: + return childKind !== 241 /* JsxClosingElement */; + } + // No explicit rule for given nodes so the result will follow the default value argument + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + /* + Function returns true when the parent node should indent the given child by an explicit rule + */ function shouldIndentChildNode(parent, child) { - if (nodeContentIsAlwaysIndented(parent)) { - return true; - } - switch (parent) { - case 197 /* DoStatement */: - case 198 /* WhileStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 199 /* ForStatement */: - case 196 /* IfStatement */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 143 /* MethodDeclaration */: - case 174 /* ArrowFunction */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - return child !== 192 /* Block */; - default: - return false; - } + return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (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; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; /// /// /// @@ -43661,7 +47046,7 @@ var ts; return undefined; }; return StringScriptSnapshot; - })(); + }()); function fromString(text) { return new StringScriptSnapshot(text); } @@ -43709,13 +47094,18 @@ var ts; ]; var jsDocCompletionEntries; function createNode(kind, pos, end, flags, parent) { - var node = new (ts.getNodeConstructor(kind))(pos, end); + var node = new NodeObject(kind, pos, end); node.flags = flags; node.parent = parent; return node; } var NodeObject = (function () { - function NodeObject() { + function NodeObject(kind, pos, end) { + this.kind = kind; + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -43749,13 +47139,13 @@ var ts; while (pos < end) { var token = scanner.scan(); var textPos = scanner.getTextPos(); - nodes.push(createNode(token, pos, textPos, 2048 /* Synthetic */, this)); + nodes.push(createNode(token, pos, textPos, 0, this)); pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(271 /* SyntaxList */, nodes.pos, nodes.end, 2048 /* Synthetic */, this); + var list = createNode(275 /* SyntaxList */, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { @@ -43774,27 +47164,27 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 135 /* FirstNode */) { + if (this.kind >= 137 /* FirstNode */) { scanner.setText((sourceFile || this.getSourceFile()).text); children = []; - var pos = this.pos; + var pos_3 = this.pos; var processNode = function (node) { - if (pos < node.pos) { - pos = _this.addSyntheticNodes(children, pos, node.pos); + if (pos_3 < node.pos) { + pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos); } children.push(node); - pos = node.end; + pos_3 = node.end; }; var processNodes = function (nodes) { - if (pos < nodes.pos) { - pos = _this.addSyntheticNodes(children, pos, nodes.pos); + if (pos_3 < nodes.pos) { + pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos); } children.push(_this.createSyntaxList(nodes)); - pos = nodes.end; + pos_3 = nodes.end; }; ts.forEachChild(this, processNode, processNodes); - if (pos < this.end) { - this.addSyntheticNodes(children, pos, this.end); + if (pos_3 < this.end) { + this.addSyntheticNodes(children, pos_3, this.end); } scanner.setText(undefined); } @@ -43821,7 +47211,7 @@ var ts; return undefined; } var child = children[0]; - return child.kind < 135 /* FirstNode */ ? child : child.getFirstToken(sourceFile); + return child.kind < 137 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { var children = this.getChildren(sourceFile); @@ -43829,10 +47219,10 @@ var ts; if (!child) { return undefined; } - return child.kind < 135 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 137 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; return NodeObject; - })(); + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -43854,7 +47244,7 @@ var ts; return this.documentationComment; }; return SymbolObject; - })(); + }()); function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { var documentationComment = []; var docComments = getJsDocCommentsSeparatedByNewLines(); @@ -43872,31 +47262,31 @@ var ts; // Make sure we are collecting doc comment from declaration once, // In case of union property there might be same declaration multiple times // which only varies in type parameter - // Eg. let a: Array | Array; a.length + // Eg. const a: Array | Array; a.length // The property length will have two declarations of property length coming // from Array - Array and Array if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { - var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); + var sourceFileOfDeclaration_1 = 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 === 138 /* Parameter */) { - ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { - var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + if (canUseParsedParamTagComments && declaration.kind === 140 /* Parameter */) { + ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration_1), function (jsDocCommentTextRange) { + var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration_1); if (cleanedParamJsDocComment) { ts.addRange(jsDocCommentParts, cleanedParamJsDocComment); } }); } // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 218 /* ModuleDeclaration */ && declaration.body.kind === 218 /* ModuleDeclaration */) { + if (declaration.kind === 222 /* ModuleDeclaration */ && declaration.body.kind === 222 /* ModuleDeclaration */) { return; } // If this is dotted module name, get the doc comments from the parent - while (declaration.kind === 218 /* ModuleDeclaration */ && declaration.parent.kind === 218 /* ModuleDeclaration */) { + while (declaration.kind === 222 /* ModuleDeclaration */ && declaration.parent.kind === 222 /* ModuleDeclaration */) { declaration = declaration.parent; } // Get the cleaned js doc comment text from the declaration - ts.forEach(getJsDocCommentTextRange(declaration.kind === 211 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { - var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + ts.forEach(getJsDocCommentTextRange(declaration.kind === 215 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration_1), function (jsDocCommentTextRange) { + var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration_1); if (cleanedJsDocComment) { ts.addRange(jsDocCommentParts, cleanedJsDocComment); } @@ -43943,7 +47333,8 @@ var ts; } function pushDocCommentLineText(docComments, text, blankLineCount) { // Add the empty lines in between texts - while (blankLineCount--) { + while (blankLineCount) { + blankLineCount--; docComments.push(ts.textPart("")); } docComments.push(ts.textPart(text)); @@ -43969,7 +47360,7 @@ var ts; else if (spacesToRemoveAfterAsterisk === undefined) { spacesToRemoveAfterAsterisk = 0; } - // Analyse text on this line + // Analyze text on this line while (pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { var ch = sourceFile.text.charAt(pos); if (ch === "@") { @@ -44089,7 +47480,7 @@ var ts; } paramHelpStringMargin = undefined; } - // If this is the start of another tag, continue with the loop in seach of param tag with symbol name + // If this is the start of another tag, continue with the loop in search of param tag with symbol name if (sourceFile.text.charCodeAt(pos) === 64 /* at */) { continue; } @@ -44169,7 +47560,7 @@ var ts; : undefined; }; return TypeObject; - })(); + }()); var SignatureObject = (function () { function SignatureObject(checker) { this.checker = checker; @@ -44195,11 +47586,11 @@ var ts; return this.documentationComment; }; return SignatureObject; - })(); + }()); var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); - function SourceFileObject() { - _super.apply(this, arguments); + function SourceFileObject(kind, pos, end) { + _super.call(this, kind, pos, end); } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -44239,9 +47630,9 @@ var ts; if (result_2 !== undefined) { return result_2; } - if (declaration.name.kind === 136 /* ComputedPropertyName */) { + if (declaration.name.kind === 138 /* ComputedPropertyName */) { var expr = declaration.name.expression; - if (expr.kind === 166 /* PropertyAccessExpression */) { + if (expr.kind === 170 /* PropertyAccessExpression */) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -44261,9 +47652,9 @@ var ts; } function visit(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -44283,60 +47674,60 @@ var ts; ts.forEachChild(node, visit); } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: - case 218 /* ModuleDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 230 /* ExportSpecifier */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 155 /* TypeLiteral */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 221 /* EnumDeclaration */: + case 222 /* ModuleDeclaration */: + case 225 /* ImportEqualsDeclaration */: + case 234 /* ExportSpecifier */: + case 230 /* ImportSpecifier */: + case 225 /* ImportEqualsDeclaration */: + case 227 /* ImportClause */: + case 228 /* NamespaceImport */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 157 /* TypeLiteral */: addDeclaration(node); // fall through - case 144 /* Constructor */: - case 193 /* VariableStatement */: - case 212 /* VariableDeclarationList */: - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 219 /* ModuleBlock */: + case 146 /* Constructor */: + case 197 /* VariableStatement */: + case 216 /* VariableDeclarationList */: + case 165 /* ObjectBindingPattern */: + case 166 /* ArrayBindingPattern */: + case 223 /* ModuleBlock */: ts.forEachChild(node, visit); break; - case 192 /* Block */: + case 196 /* Block */: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } break; - case 138 /* Parameter */: + case 140 /* Parameter */: // Only consider properties defined as constructor parameters - if (!(node.flags & 56 /* AccessibilityModifier */)) { + if (!(node.flags & 28 /* AccessibilityModifier */)) { break; } // fall through - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } - case 247 /* EnumMember */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 251 /* EnumMember */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: addDeclaration(node); break; - case 228 /* ExportDeclaration */: + case 232 /* 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 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -44348,7 +47739,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 228 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -44361,12 +47752,12 @@ var ts; } }; return SourceFileObject; - })(NodeObject); + }(NodeObject)); var TextChange = (function () { function TextChange() { } return TextChange; - })(); + }()); ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { @@ -44456,7 +47847,7 @@ var ts; // enum E ScriptElementKind.enumElement = "enum"; // Inside module and script only - // let v = .. + // const v = .. ScriptElementKind.variableElement = "var"; // Inside function ScriptElementKind.localVariableElement = "local var"; @@ -44521,8 +47912,14 @@ var ts; ClassificationTypeNames.typeAliasName = "type alias name"; ClassificationTypeNames.parameterName = "parameter name"; ClassificationTypeNames.docCommentTagName = "doc comment tag name"; + ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; + ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; + ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; + ClassificationTypeNames.jsxAttribute = "jsx attribute"; + ClassificationTypeNames.jsxText = "jsx text"; + ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; return ClassificationTypeNames; - })(); + }()); ts.ClassificationTypeNames = ClassificationTypeNames; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; @@ -44543,6 +47940,12 @@ var ts; ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; })(ts.ClassificationType || (ts.ClassificationType = {})); var ClassificationType = ts.ClassificationType; function displayPartsToString(displayParts) { @@ -44558,16 +47961,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 173 /* FunctionExpression */) { + if (declaration.kind === 177 /* FunctionExpression */) { return true; } - if (declaration.kind !== 211 /* VariableDeclaration */ && declaration.kind !== 213 /* FunctionDeclaration */) { + if (declaration.kind !== 215 /* VariableDeclaration */ && declaration.kind !== 217 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable - for (var parent_8 = declaration.parent; !ts.isFunctionBlock(parent_8); parent_8 = parent_8.parent) { + for (var parent_10 = declaration.parent; !ts.isFunctionBlock(parent_10); parent_10 = parent_10.parent) { // Reached source file or module block - if (parent_8.kind === 248 /* SourceFile */ || parent_8.kind === 219 /* ModuleBlock */) { + if (parent_10.kind === 252 /* SourceFile */ || parent_10.kind === 223 /* ModuleBlock */) { return false; } } @@ -44579,7 +47982,6 @@ var ts; // Always default to "ScriptTarget.ES5" for the language service return { target: 1 /* ES5 */, - module: 0 /* None */, jsx: 1 /* Preserve */ }; } @@ -44608,12 +48010,14 @@ var ts; }; HostCache.prototype.createEntry = function (fileName, path) { var entry; + var scriptKind = this.host.getScriptKind ? this.host.getScriptKind(fileName) : 0 /* Unknown */; var scriptSnapshot = this.host.getScriptSnapshot(fileName); if (scriptSnapshot) { entry = { hostFileName: fileName, version: this.host.getScriptVersion(fileName), - scriptSnapshot: scriptSnapshot + scriptSnapshot: scriptSnapshot, + scriptKind: scriptKind ? scriptKind : ts.getScriptKindFromFileName(fileName) }; } this.fileNameToEntry.set(path, entry); @@ -44650,7 +48054,7 @@ var ts; return file && file.scriptSnapshot; }; return HostCache; - })(); + }()); var SyntaxTreeCache = (function () { function SyntaxTreeCache(host) { this.host = host; @@ -44661,11 +48065,12 @@ var ts; // The host does not know about this file. throw new Error("Could not find file: '" + fileName + "'."); } + var scriptKind = this.host.getScriptKind ? this.host.getScriptKind(fileName) : 0 /* Unknown */; var version = this.host.getScriptVersion(fileName); var sourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents:*/ true); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents*/ true, scriptKind); } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. @@ -44682,7 +48087,7 @@ var ts; return this.currentSourceFile; }; return SyntaxTreeCache; - })(); + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; @@ -44699,6 +48104,8 @@ var ts; function transpileModule(input, transpileOptions) { var options = transpileOptions.compilerOptions ? ts.clone(transpileOptions.compilerOptions) : getDefaultCompilerOptions(); options.isolatedModules = true; + // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. + options.suppressOutputPathCheck = true; // Filename can be non-ts file. options.allowNonTsExtensions = true; // We are not returning a sourceFile for lib file when asked by the program, @@ -44727,7 +48134,7 @@ var ts; sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); outputText = text; } }, @@ -44737,7 +48144,8 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; } + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; } }; var program = ts.createProgram([inputFileName], options, compilerHost); var diagnostics; @@ -44762,12 +48170,10 @@ var ts; return output.outputText; } ts.transpile = transpile; - function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents) { + function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents); + var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); - // after full parsing we can use table with interned strings as name table - sourceFile.nameTable = sourceFile.identifiers; return sourceFile; } ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; @@ -44779,7 +48185,7 @@ var ts; if (version !== sourceFile.version) { // Once incremental parsing is ready, then just call into this function. if (!ts.disableIncrementalParsing) { - var newText; + var newText = void 0; // 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) @@ -44819,23 +48225,17 @@ var ts; } } // Otherwise, just create a new source file. - return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents:*/ true); + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents*/ true, sourceFile.scriptKind); } ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; - function createGetCanonicalFileName(useCaseSensitivefileNames) { - return useCaseSensitivefileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); - } - ts.createGetCanonicalFileName = createGetCanonicalFileName; function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. var buckets = {}; - var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx; + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + +"|" + settings.allowJs; } function getBucketForCompilationSettings(settings, createIfMissing) { var key = getKeyFromCompilationSettings(settings); @@ -44846,7 +48246,7 @@ var ts; return bucket; } function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = ts.lookUp(buckets, name); var sourceFiles = []; entries.forEachValue(function (key, entry) { @@ -44862,22 +48262,22 @@ var ts; sourceFiles: sourceFiles }; }); - return JSON.stringify(bucketInfoArray, null, 2); + return JSON.stringify(bucketInfoArray, undefined, 2); } - function acquireDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ true); + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ true, scriptKind); } - function updateDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ false); + function updateDocument(fileName, compilationSettings, scriptSnapshot, version, scriptKind) { + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } - function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { + function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = bucket.get(path); 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, /*setNodeParents:*/ false); + var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); entry = { sourceFile: sourceFile, languageServiceRefCount: 0, @@ -44904,7 +48304,7 @@ var ts; return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { - var bucket = getBucketForCompilationSettings(compilationSettings, false); + var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ false); ts.Debug.assert(bucket !== undefined); var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = bucket.get(path); @@ -44922,8 +48322,9 @@ var ts; }; } ts.createDocumentRegistry = createDocumentRegistry; - function preProcessFile(sourceText, readImportFiles) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } var referencedFiles = []; var importedFiles = []; var ambientExternalModules; @@ -44957,9 +48358,207 @@ var ts; end: pos + importPath.length }); } - function processImport() { + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeDeclare() { + var token = scanner.getToken(); + if (token === 122 /* DeclareKeyword */) { + // declare module "mod" + token = scanner.scan(); + if (token === 125 /* ModuleKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + recordAmbientExternalModule(); + } + } + return true; + } + return false; + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeImport() { + var token = scanner.getToken(); + if (token === 89 /* ImportKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import "mod"; + recordModuleName(); + return true; + } + else { + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 134 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import d from "mod"; + recordModuleName(); + return true; + } + } + else if (token === 56 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + else if (token === 24 /* CommaToken */) { + // consume comma and keep going + token = scanner.scan(); + } + else { + // unknown syntax + return true; + } + } + if (token === 15 /* OpenBraceToken */) { + token = scanner.scan(); + // consume "{ a as B, c, d as D}" clauses + // make sure that it stops on EOF + while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = scanner.scan(); + } + if (token === 16 /* CloseBraceToken */) { + token = scanner.scan(); + if (token === 134 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import {a as A} from "mod"; + // import d, {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 37 /* AsteriskToken */) { + token = scanner.scan(); + if (token === 116 /* AsKeyword */) { + token = scanner.scan(); + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 134 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import * as NS from "mod" + // import d, * as NS from "mod" + recordModuleName(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = scanner.getToken(); + if (token === 82 /* ExportKeyword */) { + token = scanner.scan(); + if (token === 15 /* OpenBraceToken */) { + token = scanner.scan(); + // consume "{ a as B, c, d as D}" clauses + // make sure it stops on EOF + while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = scanner.scan(); + } + if (token === 16 /* CloseBraceToken */) { + token = scanner.scan(); + if (token === 134 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // export {a as A} from "mod"; + // export {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 37 /* AsteriskToken */) { + token = scanner.scan(); + if (token === 134 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // export * from "mod" + recordModuleName(); + } + } + } + else if (token === 89 /* ImportKeyword */) { + token = scanner.scan(); + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 56 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; + } + } + } + } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? scanner.scan() : scanner.getToken(); + if (token === 128 /* RequireKeyword */) { + token = scanner.scan(); + if (token === 17 /* OpenParenToken */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // require("mod"); + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = scanner.getToken(); + if (token === 69 /* Identifier */ && scanner.getTokenValue() === "define") { + token = scanner.scan(); + if (token !== 17 /* OpenParenToken */) { + return true; + } + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // looks like define ("modname", ... - skip string literal and comma + token = scanner.scan(); + if (token === 24 /* CommaToken */) { + token = scanner.scan(); + } + else { + // unexpected token + return true; + } + } + // should be start of dependency list + if (token !== 19 /* OpenBracketToken */) { + return true; + } + // skip open bracket + token = scanner.scan(); + var i = 0; + // scan until ']' or EOF + while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + // record string literals as module names + if (token === 9 /* StringLiteral */) { + recordModuleName(); + i++; + } + token = scanner.scan(); + } + return true; + } + return false; + } + function processImports() { scanner.setText(sourceText); - var token = scanner.scan(); + scanner.scan(); // Look for: // import "mod"; // import d from "mod" @@ -44971,152 +48570,26 @@ var ts; // export * from "mod" // export {a as b} from "mod" // export import i = require("mod") - while (token !== 1 /* EndOfFileToken */) { - if (token === 122 /* DeclareKeyword */) { - // declare module "mod" - token = scanner.scan(); - if (token === 125 /* ModuleKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - recordAmbientExternalModule(); - continue; - } - } + // (for JavaScript files) require("mod") + while (true) { + if (scanner.getToken() === 1 /* EndOfFileToken */) { + break; } - else if (token === 89 /* ImportKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // import "mod"; - recordModuleName(); - continue; - } - else { - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = scanner.scan(); - if (token === 133 /* FromKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // import d from "mod"; - recordModuleName(); - continue; - } - } - else if (token === 56 /* EqualsToken */) { - token = scanner.scan(); - if (token === 127 /* RequireKeyword */) { - token = scanner.scan(); - if (token === 17 /* OpenParenToken */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // import i = require("mod"); - recordModuleName(); - continue; - } - } - } - } - else if (token === 24 /* CommaToken */) { - // consume comma and keep going - token = scanner.scan(); - } - else { - // unknown syntax - continue; - } - } - if (token === 15 /* OpenBraceToken */) { - token = scanner.scan(); - // consume "{ a as B, c, d as D}" clauses - while (token !== 16 /* CloseBraceToken */) { - token = scanner.scan(); - } - if (token === 16 /* CloseBraceToken */) { - token = scanner.scan(); - if (token === 133 /* FromKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // import {a as A} from "mod"; - // import d, {a, b as B} from "mod" - recordModuleName(); - } - } - } - } - else if (token === 37 /* AsteriskToken */) { - token = scanner.scan(); - if (token === 116 /* AsKeyword */) { - token = scanner.scan(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = scanner.scan(); - if (token === 133 /* FromKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // import * as NS from "mod" - // import d, * as NS from "mod" - recordModuleName(); - } - } - } - } - } - } + // check if at least one of alternative have moved scanner forward + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { + continue; } - else if (token === 82 /* ExportKeyword */) { - token = scanner.scan(); - if (token === 15 /* OpenBraceToken */) { - token = scanner.scan(); - // consume "{ a as B, c, d as D}" clauses - while (token !== 16 /* CloseBraceToken */) { - token = scanner.scan(); - } - if (token === 16 /* CloseBraceToken */) { - token = scanner.scan(); - if (token === 133 /* FromKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // export {a as A} from "mod"; - // export {a, b as B} from "mod" - recordModuleName(); - } - } - } - } - else if (token === 37 /* AsteriskToken */) { - token = scanner.scan(); - if (token === 133 /* FromKeyword */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // export * from "mod" - recordModuleName(); - } - } - } - else if (token === 89 /* ImportKeyword */) { - token = scanner.scan(); - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { - token = scanner.scan(); - if (token === 56 /* EqualsToken */) { - token = scanner.scan(); - if (token === 127 /* RequireKeyword */) { - token = scanner.scan(); - if (token === 17 /* OpenParenToken */) { - token = scanner.scan(); - if (token === 9 /* StringLiteral */) { - // export import i = require("mod"); - recordModuleName(); - } - } - } - } - } - } + else { + scanner.scan(); } - token = scanner.scan(); } scanner.setText(undefined); } if (readImportFiles) { - processImport(); + processImports(); } processTripleSlashDirectives(); return { referencedFiles: referencedFiles, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientExternalModules }; @@ -45125,7 +48598,7 @@ var ts; /// Helpers function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 207 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 211 /* LabeledStatement */ && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -45134,12 +48607,12 @@ var ts; } function isJumpStatementTarget(node) { return node.kind === 69 /* Identifier */ && - (node.parent.kind === 203 /* BreakStatement */ || node.parent.kind === 202 /* ContinueStatement */) && + (node.parent.kind === 207 /* BreakStatement */ || node.parent.kind === 206 /* ContinueStatement */) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { return node.kind === 69 /* Identifier */ && - node.parent.kind === 207 /* LabeledStatement */ && + node.parent.kind === 211 /* LabeledStatement */ && node.parent.label === node; } /** @@ -45147,7 +48620,7 @@ var ts; * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 207 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 211 /* LabeledStatement */; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -45158,25 +48631,25 @@ var ts; return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } function isRightSideOfQualifiedName(node) { - return node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 137 /* QualifiedName */ && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 170 /* PropertyAccessExpression */ && node.parent.name === node; } function isCallExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 168 /* CallExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 172 /* CallExpression */ && node.parent.expression === node; } function isNewExpressionTarget(node) { if (isRightSideOfPropertyAccess(node)) { node = node.parent; } - return node && node.parent && node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node; + return node && node.parent && node.parent.kind === 173 /* NewExpression */ && node.parent.expression === node; } function isNameOfModuleDeclaration(node) { - return node.parent.kind === 218 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 222 /* ModuleDeclaration */ && node.parent.name === node; } function isNameOfFunctionDeclaration(node) { return node.kind === 69 /* Identifier */ && @@ -45185,22 +48658,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 === 69 /* Identifier */ || node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - (node.parent.kind === 245 /* PropertyAssignment */ || node.parent.kind === 246 /* ShorthandPropertyAssignment */) && node.parent.name === node; + (node.parent.kind === 249 /* PropertyAssignment */ || node.parent.kind === 250 /* ShorthandPropertyAssignment */) && node.parent.name === node; } function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { switch (node.parent.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 247 /* EnumMember */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 218 /* ModuleDeclaration */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 249 /* PropertyAssignment */: + case 251 /* EnumMember */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 222 /* ModuleDeclaration */: return node.parent.name === node; - case 167 /* ElementAccessExpression */: + case 171 /* ElementAccessExpression */: return node.parent.argumentExpression === node; } } @@ -45259,7 +48732,7 @@ var ts; })(BreakContinueSearchType || (BreakContinueSearchType = {})); // A cache of completion entries for keywords, these do not change between sessions var keywordCompletions = []; - for (var i = 70 /* FirstKeyword */; i <= 134 /* LastKeyword */; i++) { + for (var i = 70 /* FirstKeyword */; i <= 136 /* LastKeyword */; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ScriptElementKind.keyword, @@ -45274,17 +48747,17 @@ var ts; return undefined; } switch (node.kind) { - case 248 /* SourceFile */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: - case 218 /* ModuleDeclaration */: + case 252 /* SourceFile */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 221 /* EnumDeclaration */: + case 222 /* ModuleDeclaration */: return node; } } @@ -45292,38 +48765,38 @@ var ts; ts.getContainerNode = getContainerNode; /* @internal */ function getNodeKind(node) { switch (node.kind) { - case 218 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; - case 214 /* ClassDeclaration */: return ScriptElementKind.classElement; - case 215 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; - case 216 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; - case 217 /* EnumDeclaration */: return ScriptElementKind.enumElement; - case 211 /* VariableDeclaration */: + case 222 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; + case 218 /* ClassDeclaration */: return ScriptElementKind.classElement; + case 219 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; + case 220 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; + case 221 /* EnumDeclaration */: return ScriptElementKind.enumElement; + case 215 /* VariableDeclaration */: return ts.isConst(node) ? ScriptElementKind.constElement : ts.isLet(node) ? ScriptElementKind.letElement : ScriptElementKind.variableElement; - case 213 /* FunctionDeclaration */: return ScriptElementKind.functionElement; - case 145 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; - case 146 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 217 /* FunctionDeclaration */: return ScriptElementKind.functionElement; + case 147 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; + case 148 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: return ScriptElementKind.memberFunctionElement; - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return ScriptElementKind.memberVariableElement; - case 149 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; - case 148 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; - case 147 /* CallSignature */: return ScriptElementKind.callSignatureElement; - case 144 /* Constructor */: return ScriptElementKind.constructorImplementationElement; - case 137 /* TypeParameter */: return ScriptElementKind.typeParameterElement; - case 247 /* EnumMember */: return ScriptElementKind.variableElement; - case 138 /* Parameter */: return (node.flags & 56 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; - case 221 /* ImportEqualsDeclaration */: - case 226 /* ImportSpecifier */: - case 223 /* ImportClause */: - case 230 /* ExportSpecifier */: - case 224 /* NamespaceImport */: + case 151 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; + case 150 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; + case 149 /* CallSignature */: return ScriptElementKind.callSignatureElement; + case 146 /* Constructor */: return ScriptElementKind.constructorImplementationElement; + case 139 /* TypeParameter */: return ScriptElementKind.typeParameterElement; + case 251 /* EnumMember */: return ScriptElementKind.variableElement; + case 140 /* Parameter */: return (node.flags & 28 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case 225 /* ImportEqualsDeclaration */: + case 230 /* ImportSpecifier */: + case 227 /* ImportClause */: + case 234 /* ExportSpecifier */: + case 228 /* NamespaceImport */: return ScriptElementKind.alias; } return ScriptElementKind.unknown; @@ -45342,7 +48815,7 @@ var ts; } }; return CancellationTokenObject; - })(); + }()); function createLanguageService(host, documentRegistry) { if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); @@ -45361,7 +48834,7 @@ var ts; host.log(message); } } - var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -45405,7 +48878,8 @@ var ts; (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx); + oldSettings.jsx !== newSettings.jsx || + oldSettings.allowJs !== newSettings.allowJs); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -45425,8 +48899,15 @@ var ts; // stub missing host functionality var entry = hostCache.getOrCreateEntry(fileName); return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + }, + directoryExists: function (directoryName) { + ts.Debug.assert(!host.resolveModuleNames); + return ts.directoryProbablyExists(directoryName, host); } }; + if (host.trace) { + compilerHost.trace = function (message) { return host.trace(message); }; + } if (host.resolveModuleNames) { compilerHost.resolveModuleNames = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } @@ -45460,7 +48941,7 @@ var ts; return undefined; } // Check if the language version has changed since we last created a program; if they are the same, - // it is safe to reuse the souceFiles; if not, then the shape of the AST can change, and the oldSourceFile + // it is safe to reuse the sourceFiles; if not, then the shape of the AST can change, and the oldSourceFile // can not be reused. we have to dump all syntax trees and create new ones. if (!changesInCompilationSettingsAffectSyntax) { // Check if the old program had this file already @@ -45468,7 +48949,7 @@ var ts; if (oldSourceFile) { // We already had a source file for this file name. Go to the registry to // ensure that we get the right up to date version of it. We need this to - // address the following 'race'. Specifically, say we have the following: + // address the following race-condition. Specifically, say we have the following: // // LS1 // \ @@ -45487,15 +48968,22 @@ var ts; // it's source file any more, and instead defers to DocumentRegistry to get // either version 1, version 2 (or some other version) depending on what the // host says should be used. - return documentRegistry.updateDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); + // We do not support the scenario where a host can modify a registered + // file's script kind, i.e. in one project some file is treated as ".ts" + // and in another as ".js" + ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + fileName); + return documentRegistry.updateDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } } // Could not find this file in the old program, create a new SourceFile for it. - return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); + return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } function sourceFileUpToDate(sourceFile) { + if (!sourceFile) { + return false; + } var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); - return sourceFile && sourceFile.version === hostCache.getVersion(path); + return sourceFile.version === hostCache.getVersion(path); } function programUpToDate() { // If we haven't create a program yet, then it is not up-to-date @@ -45538,18 +49026,12 @@ var ts; return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken); } /** - * getSemanticDiagnostiscs return array of Diagnostics. If '-d' is not enabled, only report semantic errors + * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors * If '-d' enabled, report both semantic and emitter errors */ function getSemanticDiagnostics(fileName) { synchronizeHostData(); var targetSourceFile = getValidSourceFile(fileName); - // For JavaScript files, we don't want to report the normal typescript semantic errors. - // Instead, we just report errors for using TypeScript-only constructs from within a - // JavaScript file. - if (ts.isJavaScript(fileName)) { - return getJavaScriptSemanticDiagnostics(targetSourceFile); - } // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); @@ -45560,151 +49042,6 @@ var ts; var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return ts.concatenate(semanticDiagnostics, declarationDiagnostics); } - function getJavaScriptSemanticDiagnostics(sourceFile) { - var diagnostics = []; - walk(sourceFile); - return diagnostics; - function walk(node) { - if (!node) { - return false; - } - switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return true; - case 227 /* ExportAssignment */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return true; - case 214 /* ClassDeclaration */: - var classDeclaration = node; - if (checkModifiers(classDeclaration.modifiers) || - checkTypeParameters(classDeclaration.typeParameters)) { - return true; - } - break; - case 243 /* HeritageClause */: - var heritageClause = node; - if (heritageClause.token === 106 /* ImplementsKeyword */) { - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 215 /* InterfaceDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 218 /* ModuleDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 216 /* TypeAliasDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return true; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: - case 213 /* FunctionDeclaration */: - var functionDeclaration = node; - if (checkModifiers(functionDeclaration.modifiers) || - checkTypeParameters(functionDeclaration.typeParameters) || - checkTypeAnnotation(functionDeclaration.type)) { - return true; - } - break; - case 193 /* VariableStatement */: - var variableStatement = node; - if (checkModifiers(variableStatement.modifiers)) { - return true; - } - break; - case 211 /* VariableDeclaration */: - var variableDeclaration = node; - if (checkTypeAnnotation(variableDeclaration.type)) { - return true; - } - break; - case 168 /* CallExpression */: - case 169 /* NewExpression */: - var expression = node; - if (expression.typeArguments && expression.typeArguments.length > 0) { - var start = expression.typeArguments.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 138 /* Parameter */: - var parameter = node; - if (parameter.modifiers) { - var start = parameter.modifiers.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return true; - } - if (parameter.questionToken) { - diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, '?')); - return true; - } - if (parameter.type) { - diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - break; - case 141 /* PropertyDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 217 /* EnumDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return true; - case 171 /* 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 139 /* Decorator */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); - return true; - } - return ts.forEachChild(node, walk); - } - function checkTypeParameters(typeParameters) { - if (typeParameters) { - var start = typeParameters.pos; - diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkTypeAnnotation(type) { - if (type) { - diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return true; - } - return false; - } - function checkModifiers(modifiers) { - if (modifiers) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 112 /* PublicKeyword */: - case 110 /* PrivateKeyword */: - case 111 /* ProtectedKeyword */: - case 122 /* DeclareKeyword */: - diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - return true; - // These are all legal modifiers. - case 113 /* StaticKeyword */: - case 82 /* ExportKeyword */: - case 74 /* ConstKeyword */: - case 77 /* DefaultKeyword */: - case 115 /* AbstractKeyword */: - } - } - } - return false; - } - } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); @@ -45721,7 +49058,7 @@ var ts; // First check of the displayName is not external module; if it is an external module, it is not valid entry if ((symbol.flags & 1536 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { let x; } | // <= request completion here, "http" should not be there) + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } @@ -45744,22 +49081,16 @@ var ts; // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks) { - if (!ts.isIdentifierStart(name.charCodeAt(0), target)) { + if (!ts.isIdentifier(name, target)) { return undefined; } - for (var i = 1, n = name.length; i < n; i++) { - if (!ts.isIdentifierPart(name.charCodeAt(i), target)) { - return undefined; - } - } } return name; } function getCompletionData(fileName, position) { var typeChecker = program.getTypeChecker(); - var syntacticStart = new Date().getTime(); var sourceFile = getValidSourceFile(fileName); - var isJavaScriptFile = ts.isJavaScript(fileName); + var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; var start = new Date().getTime(); var currentToken = ts.getTokenAtPosition(sourceFile, position); @@ -45769,7 +49100,7 @@ var ts; var insideComment = isInsideComment(sourceFile, currentToken, position); log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); if (insideComment) { - // The current position is next to the '@' sign, when no tag name being provided yet. + // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { isJsDocTagName = true; @@ -45784,9 +49115,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { - case 269 /* JSDocTypeTag */: - case 267 /* JSDocParameterTag */: - case 268 /* JSDocReturnTag */: + case 273 /* JSDocTypeTag */: + case 271 /* JSDocParameterTag */: + case 272 /* JSDocReturnTag */: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -45798,7 +49129,7 @@ var ts; return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { - // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; @@ -45813,9 +49144,9 @@ var ts; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_3 = new Date().getTime(); + var start_6 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_3)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -45831,13 +49162,13 @@ var ts; log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent_9 = contextToken.parent, kind = contextToken.kind; + var parent_11 = contextToken.parent, kind = contextToken.kind; if (kind === 21 /* DotToken */) { - if (parent_9.kind === 166 /* PropertyAccessExpression */) { + if (parent_11.kind === 170 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent_9.kind === 135 /* QualifiedName */) { + else if (parent_11.kind === 137 /* QualifiedName */) { node = contextToken.parent.left; isRightOfDot = true; } @@ -45852,8 +49183,9 @@ var ts; isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 237 /* JsxClosingElement */) { + else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 241 /* JsxClosingElement */) { isStartingCloseTag = true; + location = contextToken; } } } @@ -45877,7 +49209,10 @@ var ts; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; - symbols = [typeChecker.getSymbolAtLocation(tagName)]; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (!typeChecker.isUnknownSymbol(tagSymbol)) { + symbols = [tagSymbol]; + } isMemberCompletion = true; isNewIdentifierLocation = false; } @@ -45895,7 +49230,7 @@ var ts; // Right of dot member completion list isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */) { + if (node.kind === 69 /* Identifier */ || node.kind === 137 /* QualifiedName */ || node.kind === 170 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases if (symbol && symbol.flags & 8388608 /* Alias */) { @@ -45950,8 +49285,8 @@ var ts; return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { - var attrsType; - if ((jsxContainer.kind === 234 /* JsxSelfClosingElement */) || (jsxContainer.kind === 235 /* JsxOpeningElement */)) { + var attrsType = void 0; + if ((jsxContainer.kind === 238 /* JsxSelfClosingElement */) || (jsxContainer.kind === 239 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { @@ -46023,15 +49358,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 236 /* JsxText */) { + if (contextToken.kind === 240 /* JsxText */) { return true; } if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 235 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 239 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 237 /* JsxClosingElement */ || contextToken.parent.kind === 234 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 233 /* JsxElement */; + if (contextToken.parent.kind === 241 /* JsxClosingElement */ || contextToken.parent.kind === 238 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 237 /* JsxElement */; } } return false; @@ -46041,40 +49376,40 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 24 /* CommaToken */: - return containingNodeKind === 168 /* CallExpression */ // func( a, | - || containingNodeKind === 144 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 169 /* NewExpression */ // new C(a, | - || containingNodeKind === 164 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 181 /* BinaryExpression */ // let x = (a, | - || containingNodeKind === 152 /* FunctionType */; // var x: (s: string, list| + return containingNodeKind === 172 /* CallExpression */ // func( a, | + || containingNodeKind === 146 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 173 /* NewExpression */ // new C(a, | + || containingNodeKind === 168 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 185 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 154 /* FunctionType */; // var x: (s: string, list| case 17 /* OpenParenToken */: - return containingNodeKind === 168 /* CallExpression */ // func( | - || containingNodeKind === 144 /* Constructor */ // constructor( | - || containingNodeKind === 169 /* NewExpression */ // new C(a| - || containingNodeKind === 172 /* ParenthesizedExpression */ // let x = (a| - || containingNodeKind === 160 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + return containingNodeKind === 172 /* CallExpression */ // func( | + || containingNodeKind === 146 /* Constructor */ // constructor( | + || containingNodeKind === 173 /* NewExpression */ // new C(a| + || containingNodeKind === 176 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 162 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 19 /* OpenBracketToken */: - return containingNodeKind === 164 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 149 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 136 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + return containingNodeKind === 168 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 151 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 138 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 125 /* ModuleKeyword */: // module | case 126 /* NamespaceKeyword */: return true; case 21 /* DotToken */: - return containingNodeKind === 218 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 222 /* ModuleDeclaration */; // module A.| case 15 /* OpenBraceToken */: - return containingNodeKind === 214 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 218 /* ClassDeclaration */; // class A{ | case 56 /* EqualsToken */: - return containingNodeKind === 211 /* VariableDeclaration */ // let x = a| - || containingNodeKind === 181 /* BinaryExpression */; // x = a| + return containingNodeKind === 215 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 185 /* BinaryExpression */; // x = a| case 12 /* TemplateHead */: - return containingNodeKind === 183 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 187 /* TemplateExpression */; // `aa ${| case 13 /* TemplateMiddle */: - return containingNodeKind === 190 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 194 /* TemplateSpan */; // `aa ${10} dd ${| case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: - return containingNodeKind === 141 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 143 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. switch (previousToken.getText()) { @@ -46088,15 +49423,16 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 /* StringLiteral */ + || contextToken.kind === 164 /* StringLiteralType */ || contextToken.kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_4 = contextToken.getStart(); + var start_7 = contextToken.getStart(); var end = contextToken.getEnd(); // To be "in" one of these literals, the position has to be: // 1. entirely within the token text. // 2. at the end position of an unterminated token. // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). - if (start_4 < position && position < end) { + if (start_7 < position && position < end) { return true; } if (position === end) { @@ -46117,14 +49453,14 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 165 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 169 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; typeForObject = typeChecker.getContextualType(objectLikeContainer); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 161 /* ObjectBindingPattern */) { + else if (objectLikeContainer.kind === 165 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -46170,9 +49506,9 @@ var ts; * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 225 /* NamedImports */ ? - 222 /* ImportDeclaration */ : - 228 /* ExportDeclaration */; + var declarationKind = namedImportsOrExports.kind === 229 /* NamedImports */ ? + 226 /* ImportDeclaration */ : + 232 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -46195,11 +49531,11 @@ var ts; function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // let x = { | + case 15 /* OpenBraceToken */: // const x = { | case 24 /* CommaToken */: - var parent_10 = contextToken.parent; - if (parent_10 && (parent_10.kind === 165 /* ObjectLiteralExpression */ || parent_10.kind === 161 /* ObjectBindingPattern */)) { - return parent_10; + var parent_12 = contextToken.parent; + if (parent_12 && (parent_12.kind === 169 /* ObjectLiteralExpression */ || parent_12.kind === 165 /* ObjectBindingPattern */)) { + return parent_12; } break; } @@ -46216,8 +49552,8 @@ var ts; case 15 /* OpenBraceToken */: // import { | case 24 /* CommaToken */: switch (contextToken.parent.kind) { - case 225 /* NamedImports */: - case 229 /* NamedExports */: + case 229 /* NamedImports */: + case 233 /* NamedExports */: return contextToken.parent; } } @@ -46226,37 +49562,37 @@ var ts; } function tryGetContainingJsxElement(contextToken) { if (contextToken) { - var parent_11 = contextToken.parent; + var parent_13 = contextToken.parent; switch (contextToken.kind) { case 26 /* LessThanSlashToken */: case 39 /* SlashToken */: case 69 /* Identifier */: - case 238 /* JsxAttribute */: - case 239 /* JsxSpreadAttribute */: - if (parent_11 && (parent_11.kind === 234 /* JsxSelfClosingElement */ || parent_11.kind === 235 /* JsxOpeningElement */)) { - return parent_11; + case 242 /* JsxAttribute */: + case 243 /* JsxSpreadAttribute */: + if (parent_13 && (parent_13.kind === 238 /* JsxSelfClosingElement */ || parent_13.kind === 239 /* JsxOpeningElement */)) { + return parent_13; } - else if (parent_11.kind === 238 /* JsxAttribute */) { - return parent_11.parent; + else if (parent_13.kind === 242 /* JsxAttribute */) { + return parent_13.parent; } break; // The context token is the closing } or " of an attribute, which means // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 9 /* StringLiteral */: - if (parent_11 && ((parent_11.kind === 238 /* JsxAttribute */) || (parent_11.kind === 239 /* JsxSpreadAttribute */))) { - return parent_11.parent; + if (parent_13 && ((parent_13.kind === 242 /* JsxAttribute */) || (parent_13.kind === 243 /* JsxSpreadAttribute */))) { + return parent_13.parent; } break; case 16 /* CloseBraceToken */: - if (parent_11 && - parent_11.kind === 240 /* JsxExpression */ && - parent_11.parent && - (parent_11.parent.kind === 238 /* JsxAttribute */)) { - return parent_11.parent.parent; + if (parent_13 && + parent_13.kind === 244 /* JsxExpression */ && + parent_13.parent && + (parent_13.parent.kind === 242 /* JsxAttribute */)) { + return parent_13.parent.parent; } - if (parent_11 && parent_11.kind === 239 /* JsxSpreadAttribute */) { - return parent_11.parent; + if (parent_13 && parent_13.kind === 243 /* JsxSpreadAttribute */) { + return parent_13.parent; } break; } @@ -46265,16 +49601,16 @@ var ts; } function isFunction(kind) { switch (kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 149 /* CallSignature */: + case 150 /* ConstructSignature */: + case 151 /* IndexSignature */: return true; } return false; @@ -46286,66 +49622,66 @@ var ts; var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 24 /* CommaToken */: - return containingNodeKind === 211 /* VariableDeclaration */ || - containingNodeKind === 212 /* VariableDeclarationList */ || - containingNodeKind === 193 /* VariableStatement */ || - containingNodeKind === 217 /* EnumDeclaration */ || + return containingNodeKind === 215 /* VariableDeclaration */ || + containingNodeKind === 216 /* VariableDeclarationList */ || + containingNodeKind === 197 /* VariableStatement */ || + containingNodeKind === 221 /* EnumDeclaration */ || isFunction(containingNodeKind) || - containingNodeKind === 214 /* ClassDeclaration */ || - containingNodeKind === 186 /* ClassExpression */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 162 /* ArrayBindingPattern */ || - containingNodeKind === 216 /* TypeAliasDeclaration */; // type Map, K, | + containingNodeKind === 218 /* ClassDeclaration */ || + containingNodeKind === 190 /* ClassExpression */ || + containingNodeKind === 219 /* InterfaceDeclaration */ || + containingNodeKind === 166 /* ArrayBindingPattern */ || + containingNodeKind === 220 /* TypeAliasDeclaration */; // type Map, K, | case 21 /* DotToken */: - return containingNodeKind === 162 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 166 /* ArrayBindingPattern */; // var [.| case 54 /* ColonToken */: - return containingNodeKind === 163 /* BindingElement */; // var {x :html| + return containingNodeKind === 167 /* BindingElement */; // var {x :html| case 19 /* OpenBracketToken */: - return containingNodeKind === 162 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 166 /* ArrayBindingPattern */; // var [x| case 17 /* OpenParenToken */: - return containingNodeKind === 244 /* CatchClause */ || + return containingNodeKind === 248 /* CatchClause */ || isFunction(containingNodeKind); case 15 /* OpenBraceToken */: - return containingNodeKind === 217 /* EnumDeclaration */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 155 /* TypeLiteral */; // let x : { | + return containingNodeKind === 221 /* EnumDeclaration */ || + containingNodeKind === 219 /* InterfaceDeclaration */ || + containingNodeKind === 157 /* TypeLiteral */; // const x : { | case 23 /* SemicolonToken */: - return containingNodeKind === 140 /* PropertySignature */ && + return containingNodeKind === 142 /* PropertySignature */ && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 215 /* InterfaceDeclaration */ || - contextToken.parent.parent.kind === 155 /* TypeLiteral */); // let x : { a; | + (contextToken.parent.parent.kind === 219 /* InterfaceDeclaration */ || + contextToken.parent.parent.kind === 157 /* TypeLiteral */); // const x : { a; | case 25 /* LessThanToken */: - return containingNodeKind === 214 /* ClassDeclaration */ || - containingNodeKind === 186 /* ClassExpression */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 216 /* TypeAliasDeclaration */ || + return containingNodeKind === 218 /* ClassDeclaration */ || + containingNodeKind === 190 /* ClassExpression */ || + containingNodeKind === 219 /* InterfaceDeclaration */ || + containingNodeKind === 220 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 113 /* StaticKeyword */: - return containingNodeKind === 141 /* PropertyDeclaration */; + return containingNodeKind === 143 /* PropertyDeclaration */; case 22 /* DotDotDotToken */: - return containingNodeKind === 138 /* Parameter */ || + return containingNodeKind === 140 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 162 /* ArrayBindingPattern */); // var [...z| + contextToken.parent.parent.kind === 166 /* ArrayBindingPattern */); // var [...z| case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: - return containingNodeKind === 138 /* Parameter */; + return containingNodeKind === 140 /* Parameter */; case 116 /* AsKeyword */: - return containingNodeKind === 226 /* ImportSpecifier */ || - containingNodeKind === 230 /* ExportSpecifier */ || - containingNodeKind === 224 /* NamespaceImport */; + return containingNodeKind === 230 /* ImportSpecifier */ || + containingNodeKind === 234 /* ExportSpecifier */ || + containingNodeKind === 228 /* NamespaceImport */; case 73 /* ClassKeyword */: case 81 /* EnumKeyword */: case 107 /* InterfaceKeyword */: case 87 /* FunctionKeyword */: case 102 /* VarKeyword */: case 123 /* GetKeyword */: - case 129 /* SetKeyword */: + case 130 /* SetKeyword */: case 89 /* ImportKeyword */: case 108 /* LetKeyword */: case 74 /* ConstKeyword */: case 114 /* YieldKeyword */: - case 132 /* TypeKeyword */: + case 133 /* TypeKeyword */: return true; } // Previous token may have been a keyword that was converted to an identifier. @@ -46386,20 +49722,20 @@ var ts; * do not occur at the current position and have not otherwise been typed. */ function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var exisingImportsOrExports = {}; + var existingImportsOrExports = {}; for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_33 = element.propertyName || element.name; - exisingImportsOrExports[name_33.text] = true; + var name_34 = element.propertyName || element.name; + existingImportsOrExports[name_34.text] = true; } - if (ts.isEmpty(exisingImportsOrExports)) { + if (ts.isEmpty(existingImportsOrExports)) { return exportsOfModule; } - return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(exisingImportsOrExports, e.name); }); + return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(existingImportsOrExports, e.name); }); } /** * Filters out completion suggestions for named imports or exports. @@ -46415,9 +49751,10 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 245 /* PropertyAssignment */ && - m.kind !== 246 /* ShorthandPropertyAssignment */ && - m.kind !== 163 /* BindingElement */) { + if (m.kind !== 249 /* PropertyAssignment */ && + m.kind !== 250 /* ShorthandPropertyAssignment */ && + m.kind !== 167 /* BindingElement */ && + m.kind !== 145 /* MethodDeclaration */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -46425,8 +49762,11 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 163 /* BindingElement */ && m.propertyName) { - existingName = m.propertyName.text; + if (m.kind === 167 /* BindingElement */ && m.propertyName) { + // include only identifiers in completion list + if (m.propertyName.kind === 69 /* Identifier */) { + existingName = m.propertyName.text; + } } else { // TODO(jfreeman): Account for computed property name @@ -46452,7 +49792,7 @@ var ts; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } - if (attr.kind === 238 /* JsxAttribute */) { + if (attr.kind === 242 /* JsxAttribute */) { seenNames[attr.name.text] = true; } } @@ -46465,47 +49805,64 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isRightOfDot = completionData.isRightOfDot, isJsDocTagName = completionData.isJsDocTagName; - var entries; + var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() }; } - if (isRightOfDot && ts.isJavaScript(fileName)) { - entries = getCompletionEntriesFromSymbols(symbols); - ts.addRange(entries, getJavaScriptCompletionEntries()); + var sourceFile = getValidSourceFile(fileName); + var entries = []; + if (ts.isSourceFileJavaScript(sourceFile)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries); + ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { if (!symbols || symbols.length === 0) { - return undefined; + if (sourceFile.languageVariant === 1 /* JSX */ && + location.parent && location.parent.kind === 241 /* JsxClosingElement */) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
completion list at "1" will contain "div" with type any + var tagName = location.parent.parent.openingElement.tagName; + entries.push({ + name: tagName.text, + kind: undefined, + kindModifiers: undefined, + sortText: "0" + }); + } + else { + return undefined; + } } - entries = getCompletionEntriesFromSymbols(symbols); + getCompletionEntriesFromSymbols(symbols, entries); } // Add keywords if this is not a member completion list if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; - function getJavaScriptCompletionEntries() { + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; - var allNames = {}; var target = program.getCompilerOptions().target; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - var nameTable = getNameTable(sourceFile); - for (var name_34 in nameTable) { - if (!allNames[name_34]) { - allNames[name_34] = name_34; - var displayName = getCompletionEntryDisplayName(name_34, target, /*performCharacterChecks:*/ true); - if (displayName) { - var entry = { - name: displayName, - kind: ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } + var nameTable = getNameTable(sourceFile); + for (var name_35 in nameTable) { + // Skip identifiers produced only from the current location + if (nameTable[name_35] === position) { + continue; + } + if (!uniqueNames[name_35]) { + uniqueNames[name_35] = name_35; + var displayName = getCompletionEntryDisplayName(name_35, target, /*performCharacterChecks*/ true); + if (displayName) { + var entry = { + name: displayName, + kind: ScriptElementKind.warning, + kindModifiers: "", + sortText: "1" + }; + entries.push(entry); } } } @@ -46525,7 +49882,7 @@ var ts; // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks:*/ true, location); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks*/ true, location); if (!displayName) { return undefined; } @@ -46543,25 +49900,24 @@ var ts; sortText: "0" }; } - function getCompletionEntriesFromSymbols(symbols) { + function getCompletionEntriesFromSymbols(symbols, entries) { var start = new Date().getTime(); - var entries = []; + var uniqueNames = {}; if (symbols) { - var nameToSymbol = {}; - for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { - var symbol = symbols_3[_i]; + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; var entry = createCompletionEntry(symbol, location); if (entry) { var id = ts.escapeIdentifier(entry.name); - if (!ts.lookUp(nameToSymbol, id)) { + if (!ts.lookUp(uniqueNames, id)) { entries.push(entry); - nameToSymbol[id] = symbol; + uniqueNames[id] = id; } } } } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); - return entries; + return uniqueNames; } } function getCompletionEntryDetails(fileName, position, entryName) { @@ -46571,11 +49927,11 @@ var ts; if (completionData) { var symbols = completionData.symbols, location_2 = completionData.location; // Find the symbol with the matching entry name. - var target = program.getCompilerOptions().target; + var target_2 = program.getCompilerOptions().target; // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false, location_2) === entryName ? s : undefined; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target_2, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); if (symbol) { var _a = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; return { @@ -46604,7 +49960,7 @@ var ts; function getSymbolKind(symbol, location) { var flags = symbol.getFlags(); if (flags & 32 /* Class */) - return ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 190 /* ClassExpression */) ? ScriptElementKind.localClassElement : ScriptElementKind.classElement; if (flags & 384 /* Enum */) return ScriptElementKind.enumElement; @@ -46669,7 +50025,7 @@ var ts; }); if (!unionPropertyKind) { // If this was union of all methods, - //make sure it has call signatures before we can label it as method + // make sure it has call signatures before we can label it as method var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { return ScriptElementKind.memberFunctionElement; @@ -46703,10 +50059,10 @@ var ts; if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { symbolKind = ScriptElementKind.memberVariableElement; } - var signature; + var signature = void 0; type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 166 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 170 /* 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)) { @@ -46714,8 +50070,8 @@ var ts; } } // try get the call/construct signature from the type if it matches - var callExpression; - if (location.kind === 168 /* CallExpression */ || location.kind === 169 /* NewExpression */) { + var callExpression = void 0; + if (location.kind === 172 /* CallExpression */ || location.kind === 173 /* NewExpression */) { callExpression = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -46728,7 +50084,7 @@ var ts; // Use the first candidate: signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 169 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; + var useConstructSignatures = callExpression.kind === 173 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain @@ -46781,24 +50137,24 @@ var ts; } } else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || - (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 144 /* Constructor */)) { + (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 146 /* Constructor */)) { // get the signature from the declaration and write it var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 144 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); + var allSignatures = functionDeclaration.kind === 146 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 144 /* Constructor */) { + if (functionDeclaration.kind === 146 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 147 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 149 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -46807,7 +50163,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo) { - if (ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 190 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -46830,7 +50186,7 @@ var ts; } if (symbolFlags & 524288 /* TypeAlias */) { addNewLineIfDisplayPartsExist(); - displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); + displayParts.push(ts.keywordPart(133 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); @@ -46851,7 +50207,7 @@ var ts; } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 218 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 222 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -46874,35 +50230,37 @@ var ts; } else { // Method/function type parameter - var container = ts.getContainingFunction(location); - if (container) { - var signatureDeclaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).parent; - var signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration); - if (signatureDeclaration.kind === 148 /* ConstructSignature */) { - displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + var declaration = ts.getDeclarationOfKind(symbol, 139 /* TypeParameter */); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 150 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 149 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + displayParts.push(ts.keywordPart(133 /* TypeKeyword */)); displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } - else if (signatureDeclaration.kind !== 147 /* CallSignature */ && signatureDeclaration.name) { - addFullSymbolName(signatureDeclaration.symbol); - } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); - } - else { - // Type aliash type parameter - // For example - // type list = T[]; // Both T will go through same code path - var declaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).parent; - displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); - displayParts.push(ts.spacePart()); - addFullSymbolName(declaration.symbol); - writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } } } if (symbolFlags & 8 /* EnumMember */) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 247 /* EnumMember */) { + if (declaration.kind === 251 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -46918,13 +50276,13 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 221 /* ImportEqualsDeclaration */) { + if (declaration.kind === 225 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(56 /* EqualsToken */)); displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(127 /* RequireKeyword */)); + displayParts.push(ts.keywordPart(128 /* RequireKeyword */)); displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); @@ -47047,13 +50405,14 @@ var ts; } var typeChecker = program.getTypeChecker(); var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { + if (!symbol || typeChecker.isUnknownSymbol(symbol)) { // Try getting just type at this position and show switch (node.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: - case 135 /* QualifiedName */: + case 170 /* PropertyAccessExpression */: + case 137 /* QualifiedName */: case 97 /* ThisKeyword */: + case 163 /* ThisType */: case 95 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); @@ -47132,8 +50491,8 @@ var ts; var declarations = []; var definition; ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 144 /* Constructor */) || - (!selectConstructors && (d.kind === 213 /* FunctionDeclaration */ || d.kind === 143 /* MethodDeclaration */ || d.kind === 142 /* MethodSignature */))) { + if ((selectConstructors && d.kind === 146 /* Constructor */) || + (!selectConstructors && (d.kind === 217 /* FunctionDeclaration */ || d.kind === 145 /* MethodDeclaration */ || d.kind === 144 /* MethodSignature */))) { declarations.push(d); if (d.body) definition = d; @@ -47193,7 +50552,14 @@ var ts; // to jump to the implementation directly. if (symbol.flags & 8388608 /* Alias */) { var declaration = symbol.declarations[0]; - if (node.kind === 69 /* Identifier */ && node.parent === declaration) { + // Go to the original declaration for cases: + // + // (1) when the aliased symbol was declared in the location(parent). + // (2) when the aliased symbol is originating from a named import. + // + if (node.kind === 69 /* Identifier */ && + (node.parent === declaration || + (declaration.kind === 230 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 229 /* NamedImports */))) { symbol = typeChecker.getAliasedSymbol(symbol); } } @@ -47202,16 +50568,16 @@ 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 === 246 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 250 /* ShorthandPropertyAssignment */) { var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; } var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind = getSymbolKind(shorthandSymbol, node); - var shorthandSymbolName = typeChecker.symbolToString(shorthandSymbol); - var shorthandContainerName = typeChecker.symbolToString(symbol.parent, node); - return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName); }); + var shorthandSymbolKind_1 = getSymbolKind(shorthandSymbol, node); + var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); + var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); + return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } return getDefinitionFromSymbol(symbol, node); } @@ -47233,13 +50599,13 @@ var ts; return undefined; } if (type.flags & 16384 /* Union */) { - var result = []; + var result_3 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result, /*from*/ getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(/*to*/ result_3, /*from*/ getDefinitionFromSymbol(t.symbol, node)); } }); - return result; + return result_3; } if (!type.symbol) { return undefined; @@ -47249,10 +50615,10 @@ var ts; function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile = getCanonicalFileName(ts.normalizeSlashes(fileName)); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); // Get occurrences only supports reporting occurrences for the file queried. So // filter down to that list. - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile; }); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -47278,10 +50644,11 @@ var ts; function getSemanticDocumentHighlights(node) { if (node.kind === 69 /* Identifier */ || node.kind === 97 /* ThisKeyword */ || + node.kind === 163 /* ThisType */ || node.kind === 95 /* SuperKeyword */ || isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) { - var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings*/ false, /*findInComments*/ false); return convertReferencedSymbols(referencedSymbols); } return undefined; @@ -47331,75 +50698,75 @@ var ts; switch (node.kind) { case 88 /* IfKeyword */: case 80 /* ElseKeyword */: - if (hasKind(node.parent, 196 /* IfStatement */)) { + if (hasKind(node.parent, 200 /* IfStatement */)) { return getIfElseOccurrences(node.parent); } break; case 94 /* ReturnKeyword */: - if (hasKind(node.parent, 204 /* ReturnStatement */)) { + if (hasKind(node.parent, 208 /* ReturnStatement */)) { return getReturnOccurrences(node.parent); } break; case 98 /* ThrowKeyword */: - if (hasKind(node.parent, 208 /* ThrowStatement */)) { + if (hasKind(node.parent, 212 /* ThrowStatement */)) { return getThrowOccurrences(node.parent); } break; case 72 /* CatchKeyword */: - if (hasKind(parent(parent(node)), 209 /* TryStatement */)) { + if (hasKind(parent(parent(node)), 213 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; case 100 /* TryKeyword */: case 85 /* FinallyKeyword */: - if (hasKind(parent(node), 209 /* TryStatement */)) { + if (hasKind(parent(node), 213 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent); } break; case 96 /* SwitchKeyword */: - if (hasKind(node.parent, 206 /* SwitchStatement */)) { + if (hasKind(node.parent, 210 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 71 /* CaseKeyword */: case 77 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 206 /* SwitchStatement */)) { + if (hasKind(parent(parent(parent(node))), 210 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); } break; case 70 /* BreakKeyword */: case 75 /* ContinueKeyword */: - if (hasKind(node.parent, 203 /* BreakStatement */) || hasKind(node.parent, 202 /* ContinueStatement */)) { + if (hasKind(node.parent, 207 /* BreakStatement */) || hasKind(node.parent, 206 /* ContinueStatement */)) { return getBreakOrContinueStatementOccurrences(node.parent); } break; case 86 /* ForKeyword */: - if (hasKind(node.parent, 199 /* ForStatement */) || - hasKind(node.parent, 200 /* ForInStatement */) || - hasKind(node.parent, 201 /* ForOfStatement */)) { + if (hasKind(node.parent, 203 /* ForStatement */) || + hasKind(node.parent, 204 /* ForInStatement */) || + hasKind(node.parent, 205 /* ForOfStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 104 /* WhileKeyword */: case 79 /* DoKeyword */: - if (hasKind(node.parent, 198 /* WhileStatement */) || hasKind(node.parent, 197 /* DoStatement */)) { + if (hasKind(node.parent, 202 /* WhileStatement */) || hasKind(node.parent, 201 /* DoStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 121 /* ConstructorKeyword */: - if (hasKind(node.parent, 144 /* Constructor */)) { + if (hasKind(node.parent, 146 /* Constructor */)) { return getConstructorOccurrences(node.parent); } break; case 123 /* GetKeyword */: - case 129 /* SetKeyword */: - if (hasKind(node.parent, 145 /* GetAccessor */) || hasKind(node.parent, 146 /* SetAccessor */)) { + case 130 /* SetKeyword */: + if (hasKind(node.parent, 147 /* GetAccessor */) || hasKind(node.parent, 148 /* SetAccessor */)) { return getGetAndSetOccurrences(node.parent); } break; default: - if (ts.isModifier(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 193 /* VariableStatement */)) { + if (ts.isModifierKind(node.kind) && node.parent && + (ts.isDeclaration(node.parent) || node.parent.kind === 197 /* VariableStatement */)) { return getModifierOccurrences(node.kind, node.parent); } } @@ -47415,10 +50782,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 208 /* ThrowStatement */) { + if (node.kind === 212 /* ThrowStatement */) { statementAccumulator.push(node); } - else if (node.kind === 209 /* TryStatement */) { + else if (node.kind === 213 /* TryStatement */) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -47445,19 +50812,19 @@ var ts; function getThrowStatementOwner(throwStatement) { var child = throwStatement; while (child.parent) { - var parent_12 = child.parent; - if (ts.isFunctionBlock(parent_12) || parent_12.kind === 248 /* SourceFile */) { - return parent_12; + var parent_14 = child.parent; + if (ts.isFunctionBlock(parent_14) || parent_14.kind === 252 /* SourceFile */) { + return parent_14; } // 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_12.kind === 209 /* TryStatement */) { - var tryStatement = parent_12; + if (parent_14.kind === 213 /* TryStatement */) { + var tryStatement = parent_14; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_12; + child = parent_14; } return undefined; } @@ -47466,7 +50833,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 203 /* BreakStatement */ || node.kind === 202 /* ContinueStatement */) { + if (node.kind === 207 /* BreakStatement */ || node.kind === 206 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { @@ -47481,16 +50848,16 @@ var ts; function getBreakOrContinueOwner(statement) { for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { switch (node_2.kind) { - case 206 /* SwitchStatement */: - if (statement.kind === 202 /* ContinueStatement */) { + case 210 /* SwitchStatement */: + if (statement.kind === 206 /* ContinueStatement */) { continue; } // Fall through. - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: - case 197 /* DoStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 202 /* WhileStatement */: + case 201 /* DoStatement */: if (!statement.label || isLabeledBy(node_2, statement.label.text)) { return node_2; } @@ -47509,24 +50876,24 @@ 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 === 214 /* ClassDeclaration */ || - container.kind === 186 /* ClassExpression */ || - (declaration.kind === 138 /* Parameter */ && hasKind(container, 144 /* Constructor */)))) { + if (!(container.kind === 218 /* ClassDeclaration */ || + container.kind === 190 /* ClassExpression */ || + (declaration.kind === 140 /* Parameter */ && hasKind(container, 146 /* Constructor */)))) { return undefined; } } else if (modifier === 113 /* StaticKeyword */) { - if (!(container.kind === 214 /* ClassDeclaration */ || container.kind === 186 /* ClassExpression */)) { + if (!(container.kind === 218 /* ClassDeclaration */ || container.kind === 190 /* ClassExpression */)) { return undefined; } } else if (modifier === 82 /* ExportKeyword */ || modifier === 122 /* DeclareKeyword */) { - if (!(container.kind === 219 /* ModuleBlock */ || container.kind === 248 /* SourceFile */)) { + if (!(container.kind === 223 /* ModuleBlock */ || container.kind === 252 /* SourceFile */)) { return undefined; } } else if (modifier === 115 /* AbstractKeyword */) { - if (!(container.kind === 214 /* ClassDeclaration */ || declaration.kind === 214 /* ClassDeclaration */)) { + if (!(container.kind === 218 /* ClassDeclaration */ || declaration.kind === 218 /* ClassDeclaration */)) { return undefined; } } @@ -47538,8 +50905,8 @@ var ts; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { - case 219 /* ModuleBlock */: - case 248 /* SourceFile */: + case 223 /* ModuleBlock */: + case 252 /* SourceFile */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */) { nodes = declaration.members.concat(declaration); @@ -47548,17 +50915,17 @@ var ts; nodes = container.statements; } break; - case 144 /* Constructor */: + case 146 /* Constructor */: nodes = container.parameters.concat(container.parent.members); break; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 218 /* ClassDeclaration */: + case 190 /* ClassExpression */: 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 & 56 /* AccessibilityModifier */) { + if (modifierFlag & 28 /* AccessibilityModifier */) { var constructor = ts.forEach(container.members, function (member) { - return member.kind === 144 /* Constructor */ && member; + return member.kind === 146 /* Constructor */ && member; }); if (constructor) { nodes = nodes.concat(constructor.parameters); @@ -47580,17 +50947,17 @@ var ts; function getFlagFromModifier(modifier) { switch (modifier) { case 112 /* PublicKeyword */: - return 8 /* Public */; + return 4 /* Public */; case 110 /* PrivateKeyword */: - return 16 /* Private */; + return 8 /* Private */; case 111 /* ProtectedKeyword */: - return 32 /* Protected */; + return 16 /* Protected */; case 113 /* StaticKeyword */: - return 64 /* Static */; + return 32 /* Static */; case 82 /* ExportKeyword */: - return 2 /* Export */; + return 1 /* Export */; case 122 /* DeclareKeyword */: - return 4 /* Ambient */; + return 2 /* Ambient */; case 115 /* AbstractKeyword */: return 128 /* Abstract */; default: @@ -47611,13 +50978,13 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 145 /* GetAccessor */); - tryPushAccessorKeyword(accessorDeclaration.symbol, 146 /* SetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 147 /* GetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 148 /* 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, 123 /* GetKeyword */, 129 /* SetKeyword */); }); + ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 123 /* GetKeyword */, 130 /* SetKeyword */); }); } } } @@ -47635,7 +51002,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86 /* ForKeyword */, 104 /* WhileKeyword */, 79 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 197 /* DoStatement */) { + if (loopNode.kind === 201 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { @@ -47656,13 +51023,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: + case 203 /* ForStatement */: + case 204 /* ForInStatement */: + case 205 /* ForOfStatement */: + case 201 /* DoStatement */: + case 202 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 206 /* SwitchStatement */: + case 210 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -47716,7 +51083,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, 192 /* Block */))) { + if (!(func && hasKind(func.body, 196 /* Block */))) { return undefined; } var keywords = []; @@ -47732,7 +51099,7 @@ var ts; function getIfElseOccurrences(ifStatement) { var keywords = []; // Traverse upwards through all parent if-statements linked by their else-branches. - while (hasKind(ifStatement.parent, 196 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 200 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. @@ -47745,7 +51112,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 196 /* IfStatement */)) { + if (!hasKind(ifStatement.elseStatement, 200 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; @@ -47821,11 +51188,11 @@ var ts; return convertReferences(referencedSymbols); } function getReferencesAtPosition(fileName, position) { - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); return convertReferences(referencedSymbols); } function findReferences(fileName, position) { - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false); // Only include referenced symbols that have a valid definition. return ts.filter(referencedSymbols, function (rs) { return !!rs.definition; }); } @@ -47838,8 +51205,8 @@ var ts; } if (node.kind !== 69 /* Identifier */ && // TODO (drosen): This should be enabled in a later release - currently breaks rename. - //node.kind !== SyntaxKind.ThisKeyword && - //node.kind !== SyntaxKind.SuperKeyword && + // node.kind !== SyntaxKind.ThisKeyword && + // node.kind !== SyntaxKind.SuperKeyword && !isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && !isNameOfExternalModuleImportOrDeclaration(node)) { return undefined; @@ -47862,7 +51229,7 @@ var ts; return getLabelReferencesInNode(node.parent, node); } } - if (node.kind === 97 /* ThisKeyword */) { + if (node.kind === 97 /* ThisKeyword */ || node.kind === 163 /* ThisType */) { return getReferencesForThisKeyword(node, sourceFiles); } if (node.kind === 95 /* SuperKeyword */) { @@ -47896,11 +51263,11 @@ var ts; } else { var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var sourceFile = sourceFiles_2[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName)) { + if (ts.lookUp(nameTable, internedName) !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -47923,10 +51290,8 @@ var ts; textSpan: ts.createTextSpan(declarations[0].getStart(), 0) }; } - function isImportOrExportSpecifierImportSymbol(symbol) { - return (symbol.flags & 8388608 /* Alias */) && ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 230 /* ExportSpecifier */; - }); + function isImportSpecifierSymbol(symbol) { + return (symbol.flags & 8388608 /* Alias */) && !!ts.getDeclarationOfKind(symbol, 230 /* ImportSpecifier */); } function getInternedName(symbol, location, declarations) { // If this is an export or import specifier it could have been renamed using the 'as' syntax. @@ -47952,18 +51317,18 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 173 /* FunctionExpression */ || valueDeclaration.kind === 186 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 177 /* FunctionExpression */ || valueDeclaration.kind === 190 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16 /* Private */) ? d : undefined; }); + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8 /* Private */) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 218 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. - // So consider it visibile outside its declaration scope. + // So consider it visible outside its declaration scope. if (symbol.flags & 8388608 /* Alias */) { return undefined; } @@ -47972,11 +51337,11 @@ var ts; if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } - var scope = undefined; + var scope; var declarations = symbol.getDeclarations(); if (declarations) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; @@ -47985,7 +51350,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + if (container.kind === 252 /* 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; @@ -48084,7 +51449,7 @@ var ts; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, container.getStart(), container.getEnd()); if (possiblePositions.length) { // Build the set of symbols to search for, initially it has only the current symbol - var searchSymbols = populateSearchSymbolSet(searchSymbol, searchLocation); + var searchSymbols_1 = populateSearchSymbolSet(searchSymbol, searchLocation); ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -48116,12 +51481,12 @@ var ts; if (referenceSymbol) { var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); - var relatedSymbol = getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation); + var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation); if (relatedSymbol) { var referencedSymbol = getReferencedSymbol(relatedSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceLocation)); } - else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols.indexOf(shorthandValueSymbol) >= 0) { + else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); } @@ -48151,20 +51516,20 @@ var ts; } } function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword, /*includeFunctions*/ false); + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); if (!searchSpaceNode) { return undefined; } // Whether 'super' occurs in a static context within a class. - var staticFlag = 64 /* Static */; + var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -48180,11 +51545,11 @@ var ts; if (!node || node.kind !== 95 /* SuperKeyword */) { return; } - var container = ts.getSuperContainer(node, /*includeFunctions*/ false); + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); // If we have a 'super' container, we must have an enclosing class. // Now make sure the owning class is the same as the search-space // and has the same static qualifier as the original 'super's owner. - if (container && (64 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + if (container && (32 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { references.push(getReferenceEntryFromNode(node)); } }); @@ -48194,29 +51559,29 @@ var ts; function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. - var staticFlag = 64 /* Static */; + var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // fall through - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 248 /* SourceFile */: + case 252 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: + case 177 /* 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. @@ -48225,7 +51590,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 248 /* SourceFile */) { + if (searchSpaceNode.kind === 252 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -48251,33 +51616,33 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 97 /* ThisKeyword */) { + if (!node || (node.kind !== 97 /* ThisKeyword */ && node.kind !== 163 /* ThisType */)) { return; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: + case 190 /* ClassExpression */: + case 218 /* 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 & 64 /* Static */) === staticFlag) { + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 32 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 248 /* SourceFile */: - if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + case 252 /* SourceFile */: + if (container.kind === 252 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -48288,10 +51653,18 @@ var ts; function populateSearchSymbolSet(symbol, location) { // The search set contains at least the current symbol var result = [symbol]; - // If the symbol is an alias, add what it alaises to the list - if (isImportOrExportSpecifierImportSymbol(symbol)) { + // If the symbol is an alias, add what it aliases to the list + if (isImportSpecifierSymbol(symbol)) { result.push(typeChecker.getAliasedSymbol(symbol)); } + // For export specifiers, the exported name can be referring to a local symbol, e.g.: + // import {a} from "mod"; + // export {a as somethingElse} + // We want the *local* declaration of 'a' as declared in the import, + // *not* as declared within "mod" (or farther) + if (location.parent.kind === 234 /* ExportSpecifier */) { + result.push(typeChecker.getExportSpecifierLocalTargetSymbol(location.parent)); + } // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set @@ -48304,8 +51677,8 @@ var ts; * property name and variable declaration of the identifier. * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service * should show both 'name' in 'obj' and 'name' in variable declaration - * let name = "Foo"; - * let obj = { name }; + * const name = "Foo"; + * const obj = { name }; * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. @@ -48315,6 +51688,14 @@ var ts; result.push(shorthandValueSymbol); } } + // If the symbol.valueDeclaration is a property parameter declaration, + // we should include both parameter declaration symbol and property declaration symbol + // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. + // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 140 /* Parameter */ && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } // If this is a union property, add all the symbols from all its source symbols in all unioned types. // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { @@ -48323,19 +51704,44 @@ var ts; } // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ {}); } }); return result; } - function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { - if (symbol && symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { + if (!symbol) { + return; + } + // If the current symbol is the same as the previous-iteration symbol, we can just return the symbol that has already been visited + // This is particularly important for the following cases, so that we do not infinitely visit the same symbol. + // For example: + // interface C extends C { + // /*findRef*/propName: string; + // } + // The first time getPropertySymbolsFromBaseTypes is called when finding-all-references at propName, + // the symbol argument will be the symbol of an interface "C" and previousIterationSymbol is undefined, + // the function will add any found symbol of the property-name, then its sub-routine will call + // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already + // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. + if (ts.hasProperty(previousIterationSymbolsCache, symbol.name)) { + return; + } + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { ts.forEach(symbol.getDeclarations(), function (declaration) { - if (declaration.kind === 214 /* ClassDeclaration */) { + if (declaration.kind === 218 /* ClassDeclaration */) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 215 /* InterfaceDeclaration */) { + else if (declaration.kind === 219 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -48350,7 +51756,8 @@ var ts; result.push(propertySymbol); } // Visit the typeReference as well to see if it directly or indirectly use that property - getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result); + previousIterationSymbolsCache[symbol.name] = symbol; + getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); } } } @@ -48361,12 +51768,22 @@ var ts; } // If the reference symbol is an alias, check if what it is aliasing is one of the search // symbols. - if (isImportOrExportSpecifierImportSymbol(referenceSymbol)) { + if (isImportSpecifierSymbol(referenceSymbol)) { var aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol); if (searchSymbols.indexOf(aliasedSymbol) >= 0) { return aliasedSymbol; } } + // For export specifiers, it can be a local symbol, e.g. + // import {a} from "mod"; + // export {a as somethingElse} + // We want the local target of the export (i.e. the import symbol) and not the final target (i.e. "mod".a) + if (referenceLocation.parent.kind === 234 /* ExportSpecifier */) { + var aliasedSymbol = typeChecker.getExportSpecifierLocalTargetSymbol(referenceLocation.parent); + if (searchSymbols.indexOf(aliasedSymbol) >= 0) { + return aliasedSymbol; + } + } // If the reference location is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this symbol to // compare to our searchSymbol @@ -48385,9 +51802,9 @@ var ts; // Finally, try all properties with the same name in any type the containing type extended or implemented, and // see if any is in the list if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - var result_3 = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3); - return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + var result_4 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, /*previousIterationSymbolsCache*/ {}); + return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -48396,28 +51813,28 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_35 = node.text; + var name_36 = 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_35); + var unionProperty = contextualType.getProperty(name_36); if (unionProperty) { return [unionProperty]; } else { - var result_4 = []; + var result_5 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_35); + var symbol = t.getProperty(name_36); if (symbol) { - result_4.push(symbol); + result_5.push(symbol); } }); - return result_4; + return result_5; } } else { - var symbol_1 = contextualType.getProperty(name_35); + var symbol_1 = contextualType.getProperty(name_36); if (symbol_1) { return [symbol_1]; } @@ -48435,7 +51852,7 @@ var ts; */ function getIntersectingMeaningFromDeclarations(meaning, declarations) { if (declarations) { - var lastIterationMeaning; + var lastIterationMeaning = void 0; do { // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module @@ -48443,8 +51860,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var declarationMeaning = getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -48475,10 +51892,10 @@ var ts; } var parent = node.parent; if (parent) { - if (parent.kind === 180 /* PostfixUnaryExpression */ || parent.kind === 179 /* PrefixUnaryExpression */) { + if (parent.kind === 184 /* PostfixUnaryExpression */ || parent.kind === 183 /* PrefixUnaryExpression */) { return true; } - else if (parent.kind === 181 /* BinaryExpression */ && parent.left === node) { + else if (parent.kind === 185 /* BinaryExpression */ && parent.left === node) { var operator = parent.operatorToken.kind; return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; } @@ -48490,9 +51907,6 @@ var ts; synchronizeHostData(); return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); } - function containErrors(diagnostics) { - return ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); - } function getEmitOutput(fileName) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -48512,34 +51926,34 @@ var ts; } function getMeaningFromDeclaration(node) { switch (node.kind) { - case 138 /* Parameter */: - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 245 /* PropertyAssignment */: - case 246 /* ShorthandPropertyAssignment */: - case 247 /* EnumMember */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: - case 244 /* CatchClause */: + case 140 /* Parameter */: + case 215 /* VariableDeclaration */: + case 167 /* BindingElement */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: + case 249 /* PropertyAssignment */: + case 250 /* ShorthandPropertyAssignment */: + case 251 /* EnumMember */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 146 /* Constructor */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 217 /* FunctionDeclaration */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: + case 248 /* CatchClause */: return 1 /* Value */; - case 137 /* TypeParameter */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 155 /* TypeLiteral */: + case 139 /* TypeParameter */: + case 219 /* InterfaceDeclaration */: + case 220 /* TypeAliasDeclaration */: + case 157 /* TypeLiteral */: return 2 /* Type */; - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 218 /* ModuleDeclaration */: - if (node.name.kind === 9 /* StringLiteral */) { + case 222 /* ModuleDeclaration */: + if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { @@ -48548,15 +51962,15 @@ var ts; else { return 4 /* Namespace */; } - case 225 /* NamedImports */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 222 /* ImportDeclaration */: - case 227 /* ExportAssignment */: - case 228 /* ExportDeclaration */: + case 229 /* NamedImports */: + case 230 /* ImportSpecifier */: + case 225 /* ImportEqualsDeclaration */: + case 226 /* ImportDeclaration */: + case 231 /* ExportAssignment */: + case 232 /* ExportDeclaration */: return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; // An external module can be a Value - case 248 /* SourceFile */: + case 252 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; @@ -48565,9 +51979,10 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 151 /* TypeReference */ || - (node.parent.kind === 188 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node); + return node.parent.kind === 153 /* TypeReference */ || + (node.parent.kind === 192 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node)) || + node.kind === 163 /* ThisType */; } function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); @@ -48575,32 +51990,32 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 166 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 166 /* PropertyAccessExpression */) { + if (root.parent.kind === 170 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 170 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 188 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 243 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 192 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 247 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 214 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || - (decl.kind === 215 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); + return (decl.kind === 218 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || + (decl.kind === 219 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); } return false; } function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 135 /* QualifiedName */) { - while (root.parent && root.parent.kind === 135 /* QualifiedName */) { + if (root.parent.kind === 137 /* QualifiedName */) { + while (root.parent && root.parent.kind === 137 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 151 /* TypeReference */ && !isLastClause; + return root.parent.kind === 153 /* TypeReference */ && !isLastClause; } function isInRightSideOfImport(node) { - while (node.parent.kind === 135 /* QualifiedName */) { + while (node.parent.kind === 137 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -48610,15 +52025,15 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (node.parent.kind === 135 /* QualifiedName */ && + if (node.parent.kind === 137 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 221 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 225 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function getMeaningFromLocation(node) { - if (node.parent.kind === 227 /* ExportAssignment */) { + if (node.parent.kind === 231 /* ExportAssignment */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } else if (isInRightSideOfImport(node)) { @@ -48658,14 +52073,16 @@ var ts; return; } switch (node.kind) { - case 166 /* PropertyAccessExpression */: - case 135 /* QualifiedName */: + case 170 /* PropertyAccessExpression */: + case 137 /* QualifiedName */: case 9 /* StringLiteral */: + case 164 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: case 95 /* SuperKeyword */: case 97 /* ThisKeyword */: + case 163 /* ThisType */: case 69 /* Identifier */: break; // Cant create the text span @@ -48682,7 +52099,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 === 218 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 222 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -48706,7 +52123,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -48723,10 +52140,10 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 218 /* ModuleDeclaration */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 222 /* ModuleDeclaration */: + case 218 /* ClassDeclaration */: + case 219 /* InterfaceDeclaration */: + case 217 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -48780,7 +52197,7 @@ var ts; */ function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 218 /* ModuleDeclaration */ && + return declaration.kind === 222 /* ModuleDeclaration */ && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; }); } @@ -48828,6 +52245,12 @@ var ts; case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName; case 17 /* parameterName */: return ClassificationTypeNames.parameterName; case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName; + case 19 /* jsxOpenTagName */: return ClassificationTypeNames.jsxOpenTagName; + case 20 /* jsxCloseTagName */: return ClassificationTypeNames.jsxCloseTagName; + case 21 /* jsxSelfClosingTagName */: return ClassificationTypeNames.jsxSelfClosingTagName; + case 22 /* jsxAttribute */: return ClassificationTypeNames.jsxAttribute; + case 23 /* jsxText */: return ClassificationTypeNames.jsxText; + case 24 /* jsxAttributeStringLiteralValue */: return ClassificationTypeNames.jsxAttributeStringLiteralValue; } } function convertClassifications(classifications) { @@ -48851,8 +52274,8 @@ var ts; var spanStart = span.start; var spanLength = span.length; // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; @@ -48935,16 +52358,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); pos = tag.tagName.end; switch (tag.kind) { - case 267 /* JSDocParameterTag */: + case 271 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 270 /* JSDocTemplateTag */: + case 274 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 269 /* JSDocTypeTag */: + case 273 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 268 /* JSDocReturnTag */: + case 272 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -48981,7 +52404,8 @@ var ts; function classifyDisabledMergeCode(text, start, end) { // Classify the line that the ======= marker is on as a comment. Then just lex // all further tokens and add them to the result. - for (var i = start; i < end; i++) { + var i; + for (i = start; i < end; i++) { if (ts.isLineBreak(text.charCodeAt(i))) { break; } @@ -49001,19 +52425,53 @@ var ts; pushClassification(start, end - start, type); } } - function classifyToken(token) { - if (ts.nodeIsMissing(token)) { - return; + /** + * Returns true if node should be treated as classified and no further processing is required. + * False will mean that node is not classified and traverse routine should recurse into node contents. + */ + function tryClassifyNode(node) { + if (ts.nodeIsMissing(node)) { + return true; } - var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); - var tokenWidth = token.end - tokenStart; + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 240 /* JsxText */ && classifiedElementName === undefined) { + return false; + } + var tokenStart = node.kind === 240 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { - var type = classifyTokenType(token.kind, token); + var type = classifiedElementName || classifyTokenType(node.kind, node); if (type) { pushClassification(tokenStart, tokenWidth, type); } } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 239 /* JsxOpeningElement */: + if (token.parent.tagName === token) { + return 19 /* jsxOpenTagName */; + } + break; + case 241 /* JsxClosingElement */: + if (token.parent.tagName === token) { + return 20 /* jsxCloseTagName */; + } + break; + case 238 /* JsxSelfClosingElement */: + if (token.parent.tagName === token) { + return 21 /* jsxSelfClosingTagName */; + } + break; + case 242 /* JsxAttribute */: + if (token.parent.name === token) { + return 22 /* jsxAttribute */; + } + break; + } + return undefined; } // for accurate classification, the actual token should be passed in. however, for // cases like 'disabled merge code' classification, we just get the token kind and @@ -49035,16 +52493,17 @@ var ts; if (token) { if (tokenKind === 56 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 211 /* VariableDeclaration */ || - token.parent.kind === 141 /* PropertyDeclaration */ || - token.parent.kind === 138 /* Parameter */) { + if (token.parent.kind === 215 /* VariableDeclaration */ || + token.parent.kind === 143 /* PropertyDeclaration */ || + token.parent.kind === 140 /* Parameter */ || + token.parent.kind === 242 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 181 /* BinaryExpression */ || - token.parent.kind === 179 /* PrefixUnaryExpression */ || - token.parent.kind === 180 /* PostfixUnaryExpression */ || - token.parent.kind === 182 /* ConditionalExpression */) { + if (token.parent.kind === 185 /* BinaryExpression */ || + token.parent.kind === 183 /* PrefixUnaryExpression */ || + token.parent.kind === 184 /* PostfixUnaryExpression */ || + token.parent.kind === 186 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -49053,8 +52512,8 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { - return 6 /* stringLiteral */; + else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 164 /* StringLiteralType */) { + return token.parent.kind === 242 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -49064,35 +52523,38 @@ var ts; // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } + else if (tokenKind === 240 /* JsxText */) { + return 23 /* jsxText */; + } else if (tokenKind === 69 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 137 /* TypeParameter */: + case 139 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 215 /* InterfaceDeclaration */: + case 219 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 138 /* Parameter */: + case 140 /* Parameter */: if (token.parent.name === token) { return 17 /* parameterName */; } @@ -49112,10 +52574,7 @@ var ts; 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); - } - else { + if (!tryClassifyNode(child)) { // Recurse into our child nodes. processElement(child); } @@ -49221,7 +52680,6 @@ var ts; * be performed. */ function getDocCommentTemplateAtPosition(fileName, position) { - var start = new Date().getTime(); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Check if in a context where we don't want to perform any insertion if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { @@ -49240,19 +52698,19 @@ var ts; var commentOwner; findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 144 /* Constructor */: - case 214 /* ClassDeclaration */: - case 193 /* VariableStatement */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 146 /* Constructor */: + case 218 /* ClassDeclaration */: + case 197 /* VariableStatement */: break findOwner; - case 248 /* SourceFile */: + case 252 /* SourceFile */: return undefined; - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - if (commentOwner.parent.kind === 218 /* ModuleDeclaration */) { + if (commentOwner.parent.kind === 222 /* ModuleDeclaration */) { return undefined; } break findOwner; @@ -49265,8 +52723,7 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); - // TODO: call a helper method instead once PR #4133 gets merged in. - var newLine = host.getNewLine ? host.getNewLine() : "\r\n"; + var newLine = ts.getNewLineOrDefaultFromHost(host); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; @@ -49294,7 +52751,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 193 /* VariableStatement */) { + if (commentOwner.kind === 197 /* VariableStatement */) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -49312,17 +52769,17 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 172 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 176 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return rightHandSide.parameters; - case 186 /* ClassExpression */: + case 190 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 144 /* Constructor */) { + if (member.kind === 146 /* Constructor */) { return member.parameters; } } @@ -49344,7 +52801,7 @@ var ts; var result = []; if (descriptors.length > 0) { var regExp = getTodoCommentsRegExp(); - var matchArray; + var matchArray = void 0; while (matchArray = regExp.exec(fileContents)) { cancellationToken.throwIfCancellationRequested(); // If we got a match, here is what the match array will look like. Say the source text is: @@ -49415,11 +52872,11 @@ var ts; // comment portion. var singleLineCommentStart = /(?:\/\/+\s*)/.source; var multiLineCommentStart = /(?:\/\*+\s*)/.source; - var anyNumberOfSpacesAndAsterixesAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + var anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; // Match any of the above three TODO comment start regexps. // Note that the outermost group *is* a capture group. We want to capture the preamble // so that we can determine the starting position of the TODO comment match. - var preamble = "(" + anyNumberOfSpacesAndAsterixesAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + var preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; // Takes the descriptors and forms a regexp that matches them as if they were literals. // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: // @@ -49468,12 +52925,17 @@ var ts; if (declarations && declarations.length > 0) { // Disallow rename for elements that are defined in the standard TypeScript library. var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); if (defaultLibFileName) { - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var current = declarations_10[_i]; - var sourceFile_2 = current.getSourceFile(); - var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); - if (sourceFile_2 && getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var current = declarations_11[_i]; + var sourceFile_3 = current.getSourceFile(); + // TODO (drosen): When is there no source file? + if (!sourceFile_3) { + continue; + } + var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_3.fileName)); + if (canonicalName === canonicalDefaultLibName) { return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); } } @@ -49483,10 +52945,10 @@ var ts; if (kind) { return { canRename: true, - localizedErrorMessage: undefined, - displayName: displayName, - fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kind: kind, + displayName: displayName, + localizedErrorMessage: undefined, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), kindModifiers: getSymbolModifiers(symbol), triggerSpan: ts.createTextSpan(node.getStart(), node.getWidth()) }; @@ -49562,7 +53024,7 @@ var ts; function walk(node) { switch (node.kind) { case 69 /* Identifier */: - nameTable[node.text] = node.text; + nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; break; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -49571,9 +53033,9 @@ 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 === 232 /* ExternalModuleReference */ || + node.parent.kind === 236 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node)) { - nameTable[node.text] = node.text; + nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; } break; default: @@ -49584,7 +53046,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 167 /* ElementAccessExpression */ && + node.parent.kind === 171 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /// Classifier @@ -49632,7 +53094,7 @@ var ts; function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 123 /* GetKeyword */ || - keyword2 === 129 /* SetKeyword */ || + keyword2 === 130 /* SetKeyword */ || keyword2 === 121 /* ConstructorKeyword */ || keyword2 === 113 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". @@ -49713,7 +53175,7 @@ var ts; // (and a newline). That way when we lex we'll think we're still in a multiline comment. switch (lexState) { case 3 /* InDoubleQuoteStringLiteral */: - text = '"\\\n' + text; + text = "\"\\\n" + text; offset = 3; break; case 2 /* InSingleQuoteStringLiteral */: @@ -49791,10 +53253,10 @@ var ts; angleBracketStack--; } else if (token === 117 /* AnyKeyword */ || - token === 130 /* StringKeyword */ || - token === 128 /* NumberKeyword */ || + token === 131 /* StringKeyword */ || + token === 129 /* NumberKeyword */ || token === 120 /* BooleanKeyword */ || - token === 131 /* SymbolKeyword */) { + token === 132 /* 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, @@ -49843,7 +53305,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */ || token === 164 /* StringLiteralType */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { @@ -49966,7 +53428,7 @@ var ts; } } function isKeyword(token) { - return token >= 70 /* FirstKeyword */ && token <= 134 /* LastKeyword */; + return token >= 70 /* FirstKeyword */ && token <= 136 /* LastKeyword */; } function classFromKind(token) { if (isKeyword(token)) { @@ -49982,6 +53444,7 @@ var ts; case 8 /* NumericLiteral */: return 4 /* numericLiteral */; case 9 /* StringLiteral */: + case 164 /* StringLiteralType */: return 6 /* stringLiteral */; case 10 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; @@ -50021,18 +53484,8 @@ var ts; ts.getDefaultLibFilePath = getDefaultLibFilePath; function initializeServices() { ts.objectAllocator = { - getNodeConstructor: function (kind) { - function Node(pos, end) { - this.pos = pos; - this.end = end; - this.flags = 0 /* None */; - this.parent = undefined; - } - var proto = kind === 248 /* SourceFile */ ? new SourceFileObject() : new NodeObject(); - proto.kind = kind; - Node.prototype = proto; - return Node; - }, + getNodeConstructor: function () { return NodeObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, getSignatureConstructor: function () { return SignatureObject; } @@ -50053,12 +53506,12 @@ var ts; */ function spanInSourceFileAtLocation(sourceFile, position) { // Cannot set breakpoint in dts file - if (sourceFile.flags & 4096 /* DeclarationFile */) { + if (sourceFile.isDeclarationFile) { return undefined; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) { + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line // eg: let x =10; |--- cursor is here // let y = 10; @@ -50077,14 +53530,23 @@ var ts; // Get the span in the node based on its syntax return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); + } + function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent)); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { - if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { return spanInNode(node); } return spanInNode(otherwiseOnNode); } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } @@ -50093,126 +53555,114 @@ var ts; } function spanInNode(node) { if (node) { - if (ts.isExpression(node)) { - if (node.parent.kind === 197 /* DoStatement */) { - // Set span as if on while keyword - return spanInPreviousNode(node); - } - if (node.parent.kind === 199 /* ForStatement */) { - // For now lets set the span on this expression, fix it later - return textSpan(node); - } - if (node.parent.kind === 181 /* BinaryExpression */ && node.parent.operatorToken.kind === 24 /* CommaToken */) { - // if this is comma expression, the breakpoint is possible in this expression - return textSpan(node); - } - if (node.parent.kind === 174 /* 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 193 /* VariableStatement */: + case 197 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 211 /* VariableDeclaration */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 215 /* VariableDeclaration */: + case 143 /* PropertyDeclaration */: + case 142 /* PropertySignature */: return spanInVariableDeclaration(node); - case 138 /* Parameter */: + case 140 /* Parameter */: return spanInParameterDeclaration(node); - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 144 /* Constructor */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 217 /* FunctionDeclaration */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 146 /* Constructor */: + case 177 /* FunctionExpression */: + case 178 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 192 /* Block */: + case 196 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // Fall through - case 219 /* ModuleBlock */: + case 223 /* ModuleBlock */: return spanInBlock(node); - case 244 /* CatchClause */: + case 248 /* CatchClause */: return spanInBlock(node.block); - case 195 /* ExpressionStatement */: + case 199 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 204 /* ReturnStatement */: + case 208 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 198 /* WhileStatement */: + case 202 /* WhileStatement */: // Span on while(...) - return textSpan(node, ts.findNextToken(node.expression, node)); - case 197 /* DoStatement */: + return textSpanEndingAtNextToken(node, node.expression); + case 201 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 210 /* DebuggerStatement */: + case 214 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 196 /* IfStatement */: + case 200 /* IfStatement */: // set on if(..) span - return textSpan(node, ts.findNextToken(node.expression, node)); - case 207 /* LabeledStatement */: + return textSpanEndingAtNextToken(node, node.expression); + case 211 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: + case 207 /* BreakStatement */: + case 206 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 199 /* ForStatement */: + case 203 /* ForStatement */: return spanInForStatement(node); - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - // span on for (a in ...) - return textSpan(node, ts.findNextToken(node.expression, node)); - case 206 /* SwitchStatement */: + case 204 /* ForInStatement */: + // span of for (a in ...) + return textSpanEndingAtNextToken(node, node.expression); + case 205 /* ForOfStatement */: + // span in initializer + return spanInInitializerOfForLike(node); + case 210 /* SwitchStatement */: // span on switch(...) - return textSpan(node, ts.findNextToken(node.expression, node)); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + return textSpanEndingAtNextToken(node, node.expression); + case 245 /* CaseClause */: + case 246 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 209 /* TryStatement */: + case 213 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 208 /* ThrowStatement */: + case 212 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 227 /* ExportAssignment */: + case 231 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 221 /* ImportEqualsDeclaration */: + case 225 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 222 /* ImportDeclaration */: + case 226 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 228 /* ExportDeclaration */: + case 232 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 247 /* EnumMember */: - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 218 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 251 /* EnumMember */: + case 167 /* BindingElement */: // span on complete node return textSpan(node); - case 205 /* WithStatement */: + case 209 /* WithStatement */: // span in statement return spanInNode(node.statement); + case 141 /* Decorator */: + return spanInNodeArray(node.parent.decorators); + case 165 /* ObjectBindingPattern */: + case 166 /* ArrayBindingPattern */: + return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 219 /* InterfaceDeclaration */: + case 220 /* TypeAliasDeclaration */: return undefined; // Tokens: case 23 /* SemicolonToken */: @@ -50224,6 +53674,8 @@ var ts; return spanInOpenBraceToken(node); case 16 /* CloseBraceToken */: return spanInCloseBraceToken(node); + case 20 /* CloseBracketToken */: + return spanInCloseBracketToken(node); case 17 /* OpenParenToken */: return spanInOpenParenToken(node); case 18 /* CloseParenToken */: @@ -50240,67 +53692,155 @@ var ts; case 72 /* CatchKeyword */: case 85 /* FinallyKeyword */: return spanInNextNode(node); + case 136 /* OfKeyword */: + return spanInOfKeyword(node); default: + // Destructuring pattern in destructuring assignment + // [a, b, c] of + // [a, b, c] = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); + } + // Set breakpoint on identifier element of destructuring pattern + // a or ...c or d: x from + // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + if ((node.kind === 69 /* Identifier */ || + node.kind == 189 /* SpreadElementExpression */ || + node.kind === 249 /* PropertyAssignment */ || + node.kind === 250 /* ShorthandPropertyAssignment */) && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + return textSpan(node); + } + if (node.kind === 185 /* BinaryExpression */) { + var binaryExpression = node; + // Set breakpoint in destructuring pattern if its destructuring assignment + // [a, b, c] or {a, b, c} of + // [a, b, c] = expression or + // {a, b, c} = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); + } + if (binaryExpression.operatorToken.kind === 56 /* EqualsToken */ && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { + // Set breakpoint on assignment expression element of destructuring pattern + // a = expression of + // [a = expression, b, c] = someExpression or + // { a = expression, b, c } = someExpression + return textSpan(node); + } + if (binaryExpression.operatorToken.kind === 24 /* CommaToken */) { + return spanInNode(binaryExpression.left); + } + } + if (ts.isExpression(node)) { + switch (node.parent.kind) { + case 201 /* DoStatement */: + // Set span as if on while keyword + return spanInPreviousNode(node); + case 141 /* Decorator */: + // Set breakpoint on the decorator emit + return spanInNode(node.parent); + case 203 /* ForStatement */: + case 205 /* ForOfStatement */: + return textSpan(node); + case 185 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 24 /* CommaToken */) { + // if this is comma expression, the breakpoint is possible in this expression + return textSpan(node); + } + break; + case 178 /* ArrowFunction */: + if (node.parent.body === node) { + // If this is body of arrow function, it is allowed to have the breakpoint + return textSpan(node); + } + break; + } + } // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 245 /* PropertyAssignment */ && node.parent.name === node) { + if (node.parent.kind === 249 /* PropertyAssignment */ && + node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } // Breakpoint in type assertion goes to its operand - if (node.parent.kind === 171 /* TypeAssertionExpression */ && node.parent.type === node) { - return spanInNode(node.parent.expression); + if (node.parent.kind === 175 /* TypeAssertionExpression */ && node.parent.type === node) { + return spanInNextNode(node.parent.type); } // return type of function go to previous token if (ts.isFunctionLike(node.parent) && node.parent.type === node) { return spanInPreviousNode(node); } + // initializer of variable/parameter declaration go to previous node + if ((node.parent.kind === 215 /* VariableDeclaration */ || + node.parent.kind === 140 /* Parameter */)) { + var paramOrVarDecl = node.parent; + if (paramOrVarDecl.initializer === node || + paramOrVarDecl.type === node || + ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + } + if (node.parent.kind === 185 /* BinaryExpression */) { + var binaryExpression = node.parent; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && + (binaryExpression.right === node || + binaryExpression.operatorToken === node)) { + // If initializer of destructuring assignment move to previous token + return spanInPreviousNode(node); + } + } // Default go to parent to set the breakpoint return spanInNode(node.parent); } } + function textSpanFromVariableDeclaration(variableDeclaration) { + var declarations = variableDeclaration.parent.declarations; + if (declarations && declarations[0] === variableDeclaration) { + // First declaration - include let keyword + return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); + } + else { + // Span only on this declaration + return textSpan(variableDeclaration); + } + } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 200 /* ForInStatement */ || - variableDeclaration.parent.parent.kind === 201 /* ForOfStatement */) { + if (variableDeclaration.parent.parent.kind === 204 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.parent.kind === 193 /* VariableStatement */; - var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 199 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); - var declarations = isParentVariableStatement - ? variableDeclaration.parent.parent.declarationList.declarations - : isDeclarationOfForStatement - ? variableDeclaration.parent.parent.initializer.declarations - : undefined; - // Breakpoint is possible in variableDeclaration only if there is initialization - if (variableDeclaration.initializer || (variableDeclaration.flags & 2 /* Export */)) { - if (declarations && declarations[0] === variableDeclaration) { - if (isParentVariableStatement) { - // First declaration - include let keyword - return textSpan(variableDeclaration.parent, variableDeclaration); - } - else { - ts.Debug.assert(isDeclarationOfForStatement); - // Include let keyword from for statement declarations in the span - return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); - } - } - else { - // Span only on this declaration - return textSpan(variableDeclaration); - } + // If this is a destructuring pattern set breakpoint in binding pattern + if (ts.isBindingPattern(variableDeclaration.name)) { + return spanInBindingPattern(variableDeclaration.name); } - else if (declarations && declarations[0] !== variableDeclaration) { + // Breakpoint is possible in variableDeclaration only if there is initialization + // or its declaration from 'for of' + if (variableDeclaration.initializer || + (variableDeclaration.flags & 1 /* Export */) || + variableDeclaration.parent.parent.kind === 205 /* ForOfStatement */) { + return textSpanFromVariableDeclaration(variableDeclaration); + } + var declarations = variableDeclaration.parent.declarations; + if (declarations && declarations[0] !== variableDeclaration) { // If we cant set breakpoint on this declaration, set it on previous one - var indexOfCurrentDeclaration = ts.indexOf(declarations, variableDeclaration); - return spanInVariableDeclaration(declarations[indexOfCurrentDeclaration - 1]); + // Because the variable declaration may be binding pattern and + // we would like to set breakpoint in last binding element if thats the case, + // use preceding token instead + return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); } } function canHaveSpanInParameterDeclaration(parameter) { // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - !!(parameter.flags & 8 /* Public */) || !!(parameter.flags & 16 /* Private */); + !!(parameter.flags & 4 /* Public */) || !!(parameter.flags & 8 /* Private */); } function spanInParameterDeclaration(parameter) { - if (canHaveSpanInParameterDeclaration(parameter)) { + if (ts.isBindingPattern(parameter.name)) { + // set breakpoint in binding pattern + return spanInBindingPattern(parameter.name); + } + else if (canHaveSpanInParameterDeclaration(parameter)) { return textSpan(parameter); } else { @@ -50317,8 +53857,8 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 2 /* Export */) || - (functionDeclaration.parent.kind === 214 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); + return !!(functionDeclaration.flags & 1 /* Export */) || + (functionDeclaration.parent.kind === 218 /* ClassDeclaration */ && functionDeclaration.kind !== 146 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -50341,34 +53881,39 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 218 /* ModuleDeclaration */: + case 222 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement - case 198 /* WhileStatement */: - case 196 /* IfStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: + case 202 /* WhileStatement */: + case 200 /* IfStatement */: + case 204 /* ForInStatement */: 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 199 /* ForStatement */: + case 203 /* ForStatement */: + case 205 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } + function spanInInitializerOfForLike(forLikeStaement) { + if (forLikeStaement.initializer.kind === 216 /* VariableDeclarationList */) { + // declaration list, set breakpoint in first declaration + var variableDeclarationList = forLikeStaement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + // Expression - set breakpoint in it + return spanInNode(forLikeStaement.initializer); + } + } function spanInForStatement(forStatement) { if (forStatement.initializer) { - if (forStatement.initializer.kind === 212 /* VariableDeclarationList */) { - var variableDeclarationList = forStatement.initializer; - if (variableDeclarationList.declarations.length > 0) { - return spanInNode(variableDeclarationList.declarations[0]); - } - } - else { - return spanInNode(forStatement.initializer); - } + return spanInInitializerOfForLike(forStatement); } if (forStatement.condition) { return textSpan(forStatement.condition); @@ -50377,16 +53922,44 @@ var ts; return textSpan(forStatement.incrementor); } } + function spanInBindingPattern(bindingPattern) { + // Set breakpoint in first binding element + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 191 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Empty binding pattern of binding element, set breakpoint on binding element + if (bindingPattern.parent.kind === 167 /* BindingElement */) { + return textSpan(bindingPattern.parent); + } + // Variable declaration is used as the span + return textSpanFromVariableDeclaration(bindingPattern.parent); + } + function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { + ts.Debug.assert(node.kind !== 166 /* ArrayBindingPattern */ && node.kind !== 165 /* ObjectBindingPattern */); + var elements = node.kind === 168 /* ArrayLiteralExpression */ ? + node.elements : + node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 191 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Could be ArrayLiteral from destructuring assignment or + // just nested element in another destructuring assignment + // set breakpoint on assignment when parent is destructuring assignment + // Otherwise set breakpoint for this element + return textSpan(node.parent.kind === 185 /* BinaryExpression */ ? node.parent : node); + } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 217 /* EnumDeclaration */: + case 221 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 214 /* ClassDeclaration */: + case 218 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 220 /* CaseBlock */: + case 224 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -50394,24 +53967,24 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 219 /* ModuleBlock */: + case 223 /* ModuleBlock */: // If this is not instantiated module block no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } - case 217 /* EnumDeclaration */: - case 214 /* ClassDeclaration */: + case 221 /* EnumDeclaration */: + case 218 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 192 /* Block */: + case 196 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // fall through. - case 244 /* CatchClause */: + case 248 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 220 /* CaseBlock */: + case 224 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -50419,33 +53992,66 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; + case 165 /* ObjectBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); // Default to parent node default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var objectLiteral = node.parent; + return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral); + } + return spanInNode(node.parent); + } + } + function spanInCloseBracketToken(node) { + switch (node.parent.kind) { + case 166 /* ArrayBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var arrayLiteral = node.parent; + return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral); + } + // Default to parent node return spanInNode(node.parent); } } function spanInOpenParenToken(node) { - if (node.parent.kind === 197 /* DoStatement */) { - // Go to while keyword and do action instead + if (node.parent.kind === 201 /* DoStatement */ || + node.parent.kind === 172 /* CallExpression */ || + node.parent.kind === 173 /* NewExpression */) { return spanInPreviousNode(node); } + if (node.parent.kind === 176 /* ParenthesizedExpression */) { + return spanInNextNode(node); + } // Default to parent node return spanInNode(node.parent); } function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 144 /* Constructor */: - case 198 /* WhileStatement */: - case 197 /* DoStatement */: - case 199 /* ForStatement */: + case 177 /* FunctionExpression */: + case 217 /* FunctionDeclaration */: + case 178 /* ArrowFunction */: + case 145 /* MethodDeclaration */: + case 144 /* MethodSignature */: + case 147 /* GetAccessor */: + case 148 /* SetAccessor */: + case 146 /* Constructor */: + case 202 /* WhileStatement */: + case 201 /* DoStatement */: + case 203 /* ForStatement */: + case 205 /* ForOfStatement */: + case 172 /* CallExpression */: + case 173 /* NewExpression */: + case 176 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -50454,21 +54060,31 @@ var ts; } function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration - if (ts.isFunctionLike(node.parent) || node.parent.kind === 245 /* PropertyAssignment */) { + if (ts.isFunctionLike(node.parent) || + node.parent.kind === 249 /* PropertyAssignment */ || + node.parent.kind === 140 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 171 /* TypeAssertionExpression */) { - return spanInNode(node.parent.expression); + if (node.parent.kind === 175 /* TypeAssertionExpression */) { + return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 197 /* DoStatement */) { + if (node.parent.kind === 201 /* DoStatement */) { // Set span on while expression - return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); + return textSpanEndingAtNextToken(node, node.parent.expression); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInOfKeyword(node) { + if (node.parent.kind === 205 /* ForOfStatement */) { + // set using next token + return spanInNextNode(node); } // Default to parent node return spanInNode(node.parent); @@ -50495,6 +54111,9 @@ var ts; /// /* @internal */ var debugObjectHost = this; +// We need to use 'null' to interface with the managed side. +/* tslint:disable:no-null */ +/* tslint:disable:no-in-operator */ /* @internal */ var ts; (function (ts) { @@ -50506,7 +54125,6 @@ var ts; var ScriptSnapshotShimAdapter = (function () { function ScriptSnapshotShimAdapter(scriptSnapshotShim) { this.scriptSnapshotShim = scriptSnapshotShim; - this.lineStartPositions = null; } ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { return this.scriptSnapshotShim.getText(start, end); @@ -50532,7 +54150,7 @@ var ts; } }; return ScriptSnapshotShimAdapter; - })(); + }()); var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { var _this = this; @@ -50550,6 +54168,9 @@ var ts; }); }; } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } LanguageServiceShimHostAdapter.prototype.log = function (s) { if (this.loggingEnabled) { @@ -50587,14 +54208,17 @@ var ts; return this.files = JSON.parse(encoded); }; LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { - // Shim the API changes for 1.5 release. This should be removed once - // TypeScript 1.5 has shipped. - if (this.files && this.files.indexOf(fileName) < 0) { - return undefined; - } var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); }; + LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { + if ("getScriptKind" in this.shimHost) { + return this.shimHost.getScriptKind(fileName); + } + else { + return 0 /* Unknown */; + } + }; LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) { return this.shimHost.getScriptVersion(fileName); }; @@ -50619,17 +54243,10 @@ var ts; return this.shimHost.getCurrentDirectory(); }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { - // Wrap the API changes for 1.5 release. This try/catch - // should be removed once TypeScript 1.5 has shipped. - try { - return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); - } - catch (e) { - return ""; - } + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; return LanguageServiceShimHostAdapter; - })(); + }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; /** A cancellation that throttles calls to the host */ var ThrottledCancellationToken = (function () { @@ -50651,23 +54268,17 @@ var ts; return false; }; return ThrottledCancellationToken; - })(); + }()); var CoreServicesShimHostAdapter = (function () { function CoreServicesShimHostAdapter(shimHost) { + var _this = this; this.shimHost = shimHost; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude) { - // Wrap the API changes for 1.5 release. This try/catch - // should be removed once TypeScript 1.5 has shipped. - // Also consider removing the optional designation for - // the exclude param at this time. - var encoded; - try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); - } - catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension); - } + var encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -50677,18 +54288,19 @@ var ts; return this.shimHost.readFile(fileName); }; return CoreServicesShimHostAdapter; - })(); + }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; if (logPerformance) { logger.log(actionDescription); - var start = Date.now(); + start = Date.now(); } var result = action(); if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof (result) === "string") { + if (typeof result === "string") { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -50721,7 +54333,7 @@ var ts; this.factory.unregisterShim(this); }; return ShimBase; - })(); + }()); function realizeDiagnostics(diagnostics, newLine) { return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); } @@ -50770,9 +54382,7 @@ var ts; * Update the list of scripts known to the compiler */ LanguageServiceShimObject.prototype.refresh = function (throwOnError) { - this.forwardJSONCall("refresh(" + throwOnError + ")", function () { - return null; - }); + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); }; LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { var _this = this; @@ -50787,33 +54397,25 @@ var ts; }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); - return classifications; - }); + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - // directly serialize the spans out to a string. This is much faster to decode - // on the managed side versus a full JSON array. - return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); - }); + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { var _this = this; @@ -50843,10 +54445,7 @@ var ts; */ LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { - var quickInfo = _this.languageService.getQuickInfoAtPosition(fileName, position); - return quickInfo; - }); + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); }; /// NAMEORDOTTEDNAMESPAN /** @@ -50855,10 +54454,7 @@ var ts; */ LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { var _this = this; - return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { - var spanInfo = _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); - return spanInfo; - }); + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); }; /** * STATEMENTSPAN @@ -50866,18 +54462,12 @@ var ts; */ LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { - var spanInfo = _this.languageService.getBreakpointStatementAtPosition(fileName, position); - return spanInfo; - }); + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; /// SIGNATUREHELP LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { - var signatureInfo = _this.languageService.getSignatureHelpItems(fileName, position); - return signatureInfo; - }); + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); }; /// GOTO DEFINITION /** @@ -50886,9 +54476,7 @@ var ts; */ LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; /// GOTO Type /** @@ -50897,29 +54485,20 @@ var ts; */ LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getTypeDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { - return _this.languageService.getRenameInfo(fileName, position); - }); + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); }; LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { - return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); - }); + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); }; /// GET BRACE MATCHING LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { - var textRanges = _this.languageService.getBraceMatchingAtPosition(fileName, position); - return textRanges; - }); + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); }; /// GET SMART INDENT LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { @@ -50932,21 +54511,15 @@ var ts; /// GET REFERENCES LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getReferencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { var _this = this; - return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { - return _this.languageService.findReferences(fileName, position); - }); + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); }; LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getOccurrencesAtPosition(fileName, position); - }); + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { var _this = this; @@ -50965,41 +54538,32 @@ var ts; */ LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { - var completion = _this.languageService.getCompletionsAtPosition(fileName, position); - return completion; - }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; /** Get a string based representation of a completion list entry details */ LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")", function () { - var details = _this.languageService.getCompletionEntryDetails(fileName, position, entryName); - return details; - }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); - return edits; + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsForDocument(fileName, localOptions); - return edits; + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { var _this = this; return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { var localOptions = JSON.parse(options); - var edits = _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); - return edits; + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { @@ -51010,45 +54574,27 @@ var ts; /** Return a list of symbols that are interesting to navigate to */ LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { - var items = _this.languageService.getNavigateToItems(searchValue, maxResultCount); - return items; - }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; - return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { - var items = _this.languageService.getNavigationBarItems(fileName); - return items; - }); + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; - return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { - var items = _this.languageService.getOutliningSpans(fileName); - return items; - }); + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); }; LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { var _this = this; - return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { - var items = _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); - return items; - }); + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); }; /// Emit LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { var _this = this; - return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { - var output = _this.languageService.getEmitOutput(fileName); - // Shim the API changes for 1.5 release. This should be removed once - // TypeScript 1.5 has shipped. - output.emitOutputStatus = output.emitSkipped ? 1 : 0; - return output; - }); + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); }; return LanguageServiceShimObject; - })(ShimBase); + }(ShimBase)); function convertClassifications(classifications) { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } @@ -51067,17 +54613,17 @@ var ts; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); - var items = classification.entries; var result = ""; - for (var i = 0; i < items.length; i++) { - result += items[i].length + "\n"; - result += items[i].classification + "\n"; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; } result += classification.finalLexState; return result; }; return ClassifierShimObject; - })(ShimBase); + }(ShimBase)); var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { @@ -51102,7 +54648,8 @@ var ts; }; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength())); + // for now treat files as JavaScript + var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); var convertResult = { referencedFiles: [], importedFiles: [], @@ -51135,24 +54682,23 @@ var ts; return { options: {}, files: [], - errors: [realizeDiagnostic(result.error, '\r\n')] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } - var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(ts.normalizeSlashes(fileName))); + var normalizedFileName = ts.normalizeSlashes(fileName); + var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { options: configFile.options, files: configFile.fileNames, - errors: realizeDiagnostics(configFile.errors, '\r\n') + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { - return this.forwardJSONCall("getDefaultCompilationSettings()", function () { - return ts.getDefaultCompilerOptions(); - }); + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); }; return CoreServicesShimObject; - })(ShimBase); + }(ShimBase)); var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; @@ -51166,7 +54712,7 @@ var ts; TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { try { if (this.documentRegistry === undefined) { - this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var hostAdapter = new LanguageServiceShimHostAdapter(host); var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); @@ -51199,7 +54745,7 @@ var ts; TypeScriptServicesFactory.prototype.close = function () { // Forget all the registered shims this._shims = []; - this.documentRegistry = ts.createDocumentRegistry(); + this.documentRegistry = undefined; }; TypeScriptServicesFactory.prototype.registerShim = function (shim) { this._shims.push(shim); @@ -51214,12 +54760,14 @@ var ts; throw new Error("Invalid operation"); }; return TypeScriptServicesFactory; - })(); + }()); ts.TypeScriptServicesFactory = TypeScriptServicesFactory; if (typeof module !== "undefined" && module.exports) { module.exports = ts; } })(ts || (ts = {})); +/* tslint:enable:no-in-operator */ +/* tslint:enable:no-null */ /// TODO: this is used by VS, clean this up on both sides of the interface /* @internal */ var TypeScript; @@ -51229,5 +54777,9 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); +/* tslint:disable:no-unused-variable */ +// 'toolsVersion' gets consumed by the managed side, so it's not unused. +// TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "1.6"; +var toolsVersion = "1.9"; +/* tslint:enable:no-unused-variable */ diff --git a/package.json b/package.json index 7b8abfaae43..cc74bf2c27c 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "http://typescriptlang.org/", - "version": "1.8.0", + "version": "1.9.0", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ @@ -35,7 +35,8 @@ "browserify": "latest", "istanbul": "latest", "mocha-fivemat-progress-reporter": "latest", - "tslint": "latest", + "tslint": "next", + "typescript": "next", "tsd": "latest" }, "scripts": { diff --git a/pull_request_template.md b/pull_request_template.md new file mode 100644 index 00000000000..683e6acbf89 --- /dev/null +++ b/pull_request_template.md @@ -0,0 +1,16 @@ + + +Fixes # diff --git a/scripts/ior.ts b/scripts/ior.ts index f0c142a266c..eb67e62a275 100644 --- a/scripts/ior.ts +++ b/scripts/ior.ts @@ -76,8 +76,11 @@ module Commands { fs.mkdirSync(directoryPath); } } + function normalizeSlashes(path: string): string { + return path.replace(/\\/g, "/"); + } function transalatePath(outputFolder:string, path: string): string { - return outputFolder + directorySeparator + path.replace(":", ""); + return normalizeSlashes(outputFolder + directorySeparator + path.replace(":", "")); } function fileExists(path: string): boolean { return fs.existsSync(path); @@ -86,7 +89,7 @@ module Commands { var filename = transalatePath(outputFolder, f.path); ensureDirectoriesExist(getDirectoryPath(filename)); console.log("writing filename: " + filename); - fs.writeFile(filename, f.result.contents, (err) => { }); + fs.writeFileSync(filename, f.result.contents); }); console.log("Command: tsc "); diff --git a/scripts/tslint/booleanTriviaRule.ts b/scripts/tslint/booleanTriviaRule.ts index be32a870ff4..756728a1a11 100644 --- a/scripts/tslint/booleanTriviaRule.ts +++ b/scripts/tslint/booleanTriviaRule.ts @@ -1,6 +1,5 @@ -/// -/// - +import * as Lint from "tslint/lib/lint"; +import * as ts from "typescript"; export class Rule extends Lint.Rules.AbstractRule { public static FAILURE_STRING_FACTORY = (name: string, currently: string) => `Tag boolean argument as '${name}' (currently '${currently}')`; @@ -19,7 +18,7 @@ class BooleanTriviaWalker extends Lint.RuleWalker { visitCallExpression(node: ts.CallExpression) { super.visitCallExpression(node); - if (node.arguments) { + if (node.arguments) { const targetCallSignature = this.checker.getResolvedSignature(node); if (!!targetCallSignature) { const targetParameters = targetCallSignature.getParameters(); @@ -27,7 +26,9 @@ class BooleanTriviaWalker extends Lint.RuleWalker { for (let index = 0; index < targetParameters.length; index++) { const param = targetParameters[index]; const arg = node.arguments[index]; - if (!(arg && param)) continue; + if (!(arg && param)) { + continue; + } const argType = this.checker.getContextualType(arg); if (argType && (argType.getFlags() & ts.TypeFlags.Boolean)) { @@ -37,14 +38,16 @@ class BooleanTriviaWalker extends Lint.RuleWalker { let triviaContent: string; const ranges = ts.getLeadingCommentRanges(arg.getFullText(), 0); if (ranges && ranges.length === 1 && ranges[0].kind === ts.SyntaxKind.MultiLineCommentTrivia) { - triviaContent = arg.getFullText().slice(ranges[0].pos + 2, ranges[0].end - 2); //+/-2 to remove /**/ + triviaContent = arg.getFullText().slice(ranges[0].pos + 2, ranges[0].end - 2); // +/-2 to remove /**/ } - if (triviaContent !== param.getName()) { + + const paramName = param.getName(); + if (triviaContent !== paramName && triviaContent !== paramName + ":") { this.addFailure(this.createFailure(arg.getStart(source), arg.getWidth(source), Rule.FAILURE_STRING_FACTORY(param.getName(), triviaContent))); } } } } - } + } } } diff --git a/scripts/tslint/nextLineRule.ts b/scripts/tslint/nextLineRule.ts index 6d803fc7f88..d25652f7bce 100644 --- a/scripts/tslint/nextLineRule.ts +++ b/scripts/tslint/nextLineRule.ts @@ -1,5 +1,5 @@ -/// -/// +import * as Lint from "tslint/lib/lint"; +import * as ts from "typescript"; const OPTION_CATCH = "check-catch"; const OPTION_ELSE = "check-else"; diff --git a/scripts/tslint/noInOperatorRule.ts b/scripts/tslint/noInOperatorRule.ts new file mode 100644 index 00000000000..527e8c1b895 --- /dev/null +++ b/scripts/tslint/noInOperatorRule.ts @@ -0,0 +1,20 @@ +import * as Lint from "tslint/lib/lint"; +import * as ts from "typescript"; + + +export class Rule extends Lint.Rules.AbstractRule { + public static FAILURE_STRING = "Don't use the 'in' keyword - use 'hasProperty' to check for key presence instead"; + + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { + return this.applyWithWalker(new InWalker(sourceFile, this.getOptions())); + } +} + +class InWalker extends Lint.RuleWalker { + visitNode(node: ts.Node) { + super.visitNode(node); + if (node.kind === ts.SyntaxKind.InKeyword && node.parent && node.parent.kind === ts.SyntaxKind.BinaryExpression) { + this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); + } + } +} diff --git a/scripts/tslint/noIncrementDecrementRule.ts b/scripts/tslint/noIncrementDecrementRule.ts new file mode 100644 index 00000000000..75f4d2f5c08 --- /dev/null +++ b/scripts/tslint/noIncrementDecrementRule.ts @@ -0,0 +1,37 @@ +import * as Lint from "tslint/lib/lint"; +import * as ts from "typescript"; + + +export class Rule extends Lint.Rules.AbstractRule { + public static POSTFIX_FAILURE_STRING = "Don't use '++' or '--' postfix operators outside statements or for loops."; + public static PREFIX_FAILURE_STRING = "Don't use '++' or '--' prefix operators."; + + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { + return this.applyWithWalker(new IncrementDecrementWalker(sourceFile, this.getOptions())); + } +} + +class IncrementDecrementWalker extends Lint.RuleWalker { + + visitPostfixUnaryExpression(node: ts.PostfixUnaryExpression) { + super.visitPostfixUnaryExpression(node); + if (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator == ts.SyntaxKind.MinusMinusToken) { + this.visitIncrementDecrement(node); + } + } + + visitPrefixUnaryExpression(node: ts.PrefixUnaryExpression) { + super.visitPrefixUnaryExpression(node); + if (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator == ts.SyntaxKind.MinusMinusToken) { + this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.PREFIX_FAILURE_STRING)); + } + } + + visitIncrementDecrement(node: ts.UnaryExpression) { + if (node.parent && (node.parent.kind === ts.SyntaxKind.ExpressionStatement || + node.parent.kind === ts.SyntaxKind.ForStatement)) { + return; + } + this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.POSTFIX_FAILURE_STRING)); + } +} diff --git a/scripts/tslint/noNullRule.ts b/scripts/tslint/noNullRule.ts index 2a2c5bc3717..8e9deca996b 100644 --- a/scripts/tslint/noNullRule.ts +++ b/scripts/tslint/noNullRule.ts @@ -1,5 +1,5 @@ -/// -/// +import * as Lint from "tslint/lib/lint"; +import * as ts from "typescript"; export class Rule extends Lint.Rules.AbstractRule { diff --git a/scripts/tslint/preferConstRule.ts b/scripts/tslint/preferConstRule.ts index 29160a9c634..aaa1b0e53d5 100644 --- a/scripts/tslint/preferConstRule.ts +++ b/scripts/tslint/preferConstRule.ts @@ -1,5 +1,5 @@ -/// -/// +import * as Lint from "tslint/lib/lint"; +import * as ts from "typescript"; export class Rule extends Lint.Rules.AbstractRule { @@ -85,12 +85,12 @@ class PreferConstWalker extends Lint.RuleWalker { visitBinaryExpression(node: ts.BinaryExpression) { if (isAssignmentOperator(node.operatorToken.kind)) { - this.visitLHSExpressions(node.left); + this.visitLeftHandSideExpression(node.left); } super.visitBinaryExpression(node); } - private visitLHSExpressions(node: ts.Expression) { + private visitLeftHandSideExpression(node: ts.Expression) { while (node.kind === ts.SyntaxKind.ParenthesizedExpression) { node = (node as ts.ParenthesizedExpression).expression; } @@ -101,23 +101,25 @@ class PreferConstWalker extends Lint.RuleWalker { this.visitBindingLiteralExpression(node as (ts.ArrayLiteralExpression | ts.ObjectLiteralExpression)); } } - + private visitBindingLiteralExpression(node: ts.ArrayLiteralExpression | ts.ObjectLiteralExpression) { if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) { const pattern = node as ts.ObjectLiteralExpression; for (const element of pattern.properties) { - if (element.name.kind === ts.SyntaxKind.Identifier) { - this.markAssignment(element.name as ts.Identifier) + const kind = element.kind; + + if (kind === ts.SyntaxKind.ShorthandPropertyAssignment) { + this.markAssignment((element as ts.ShorthandPropertyAssignment).name); } - else if (isBindingPattern(element.name)) { - this.visitBindingPatternIdentifiers(element.name as ts.BindingPattern); + else if (kind === ts.SyntaxKind.PropertyAssignment) { + this.visitLeftHandSideExpression((element as ts.PropertyAssignment).initializer); } } } else if (node.kind === ts.SyntaxKind.ArrayLiteralExpression) { const pattern = node as ts.ArrayLiteralExpression; for (const element of pattern.elements) { - this.visitLHSExpressions(element); + this.visitLeftHandSideExpression(element); } } } @@ -145,7 +147,7 @@ class PreferConstWalker extends Lint.RuleWalker { private visitAnyUnaryExpression(node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression) { if (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) { - this.visitLHSExpressions(node.operand); + this.visitLeftHandSideExpression(node.operand); } } @@ -211,12 +213,12 @@ class PreferConstWalker extends Lint.RuleWalker { } } - private collectNameIdentifiers(value: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map) { + private collectNameIdentifiers(declaration: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map) { if (node.kind === ts.SyntaxKind.Identifier) { - table[(node as ts.Identifier).text] = {declaration: value, usages: 0}; + table[(node as ts.Identifier).text] = { declaration, usages: 0 }; } else { - this.collectBindingPatternIdentifiers(value, node as ts.BindingPattern, table); + this.collectBindingPatternIdentifiers(declaration, node as ts.BindingPattern, table); } } diff --git a/scripts/tslint/typeOperatorSpacingRule.ts b/scripts/tslint/typeOperatorSpacingRule.ts index 23925493340..7ceef2372bf 100644 --- a/scripts/tslint/typeOperatorSpacingRule.ts +++ b/scripts/tslint/typeOperatorSpacingRule.ts @@ -1,5 +1,5 @@ -/// -/// +import * as Lint from "tslint/lib/lint"; +import * as ts from "typescript"; export class Rule extends Lint.Rules.AbstractRule { @@ -13,10 +13,10 @@ export class Rule extends Lint.Rules.AbstractRule { class TypeOperatorSpacingWalker extends Lint.RuleWalker { public visitNode(node: ts.Node) { if (node.kind === ts.SyntaxKind.UnionType || node.kind === ts.SyntaxKind.IntersectionType) { - let types = (node).types; + const types = (node).types; let expectedStart = types[0].end + 2; // space, | or & for (let i = 1; i < types.length; i++) { - let currentType = types[i]; + const currentType = types[i]; if (expectedStart !== currentType.pos || currentType.getLeadingTriviaWidth() !== 1) { const failure = this.createFailure(currentType.pos, currentType.getWidth(), Rule.FAILURE_STRING); this.addFailure(failure); diff --git a/scripts/word2md.js b/scripts/word2md.js deleted file mode 100644 index e80275d5b2d..00000000000 --- a/scripts/word2md.js +++ /dev/null @@ -1,235 +0,0 @@ -// word2md - Word to Markdown conversion tool -// -// word2md converts a Microsoft Word document to Markdown formatted text. The tool uses the -// Word Automation APIs to start an instance of Word and access the contents of the document -// being converted. The tool must be run using the cscript.exe script host and requires Word -// to be installed on the target machine. The name of the document to convert must be specified -// as a command line argument and the resulting Markdown is written to standard output. The -// tool recognizes the specific Word styles used in the TypeScript Language Specification. -var sys = (function () { - var fileStream = new ActiveXObject("ADODB.Stream"); - fileStream.Type = 2 /*text*/; - var binaryStream = new ActiveXObject("ADODB.Stream"); - binaryStream.Type = 1 /*binary*/; - var args = []; - for (var i = 0; i < WScript.Arguments.length; i++) { - args[i] = WScript.Arguments.Item(i); - } - return { - args: args, - createObject: function (typeName) { return new ActiveXObject(typeName); }, - write: function (s) { - WScript.StdOut.Write(s); - }, - writeFile: function (fileName, data) { - fileStream.Open(); - binaryStream.Open(); - try { - // Write characters in UTF-8 encoding - fileStream.Charset = "utf-8"; - fileStream.WriteText(data); - // We don't want the BOM, skip it by setting the starting location to 3 (size of BOM). - fileStream.Position = 3; - fileStream.CopyTo(binaryStream); - binaryStream.SaveToFile(fileName, 2 /*overwrite*/); - } - finally { - binaryStream.Close(); - fileStream.Close(); - } - } - }; -})(); -function convertDocumentToMarkdown(doc) { - var result = ""; - var lastStyle; - var lastInTable; - var tableColumnCount; - var tableCellIndex; - var columnAlignment = []; - function setProperties(target, properties) { - for (var name in properties) { - if (properties.hasOwnProperty(name)) { - var value = properties[name]; - if (typeof value === "object") { - setProperties(target[name], value); - } - else { - target[name] = value; - } - } - } - } - function findReplace(findText, findOptions, replaceText, replaceOptions) { - var find = doc.range().find; - find.clearFormatting(); - setProperties(find, findOptions); - var replace = find.replacement; - replace.clearFormatting(); - setProperties(replace, replaceOptions); - find.execute(findText, false, false, false, false, false, true, 0, true, replaceText, 2); - } - function fixHyperlinks() { - var count = doc.hyperlinks.count; - for (var i = 0; i < count; i++) { - var hyperlink = doc.hyperlinks.item(i + 1); - var address = hyperlink.address; - if (address && address.length > 0) { - var textToDisplay = hyperlink.textToDisplay; - hyperlink.textToDisplay = "[" + textToDisplay + "](" + address + ")"; - } - } - } - function write(s) { - result += s; - } - function writeTableHeader() { - for (var i = 0; i < tableColumnCount - 1; i++) { - switch (columnAlignment[i]) { - case 1: - write("|:---:"); - break; - case 2: - write("|---:"); - break; - default: - write("|---"); - } - } - write("|\n"); - } - function trimEndFormattingMarks(text) { - var i = text.length; - while (i > 0 && text.charCodeAt(i - 1) < 0x20) - i--; - return text.substr(0, i); - } - function writeBlockEnd() { - switch (lastStyle) { - case "Code": - write("```\n\n"); - break; - case "List Paragraph": - case "Table": - case "TOC": - write("\n"); - break; - } - } - function writeParagraph(p) { - var text = p.range.text; - var style = p.style.nameLocal; - var inTable = p.range.tables.count > 0; - var level = 1; - var sectionBreak = text.indexOf("\x0C") >= 0; - text = trimEndFormattingMarks(text); - if (inTable) { - style = "Table"; - } - else if (style.match(/\s\d$/)) { - level = +style.substr(style.length - 1); - style = style.substr(0, style.length - 2); - } - if (lastStyle && style !== lastStyle) { - writeBlockEnd(); - } - switch (style) { - case "Heading": - case "Appendix": - var section = p.range.listFormat.listString; - write("####".substr(0, level) + ' ' + section + " " + text + "\n\n"); - break; - case "Normal": - if (text.length) { - write(text + "\n\n"); - } - break; - case "List Paragraph": - write(" ".substr(0, p.range.listFormat.listLevelNumber * 2 - 2) + "* " + text + "\n"); - break; - case "Grammar": - write("  " + text.replace(/\s\s\s/g, " ").replace(/\x0B/g, " \n   ") + "\n\n"); - break; - case "Code": - if (lastStyle !== "Code") { - write("```TypeScript\n"); - } - else { - write("\n"); - } - write(text.replace(/\x0B/g, " \n") + "\n"); - break; - case "Table": - if (!lastInTable) { - tableColumnCount = p.range.tables.item(1).columns.count + 1; - tableCellIndex = 0; - } - if (tableCellIndex < tableColumnCount) { - columnAlignment[tableCellIndex] = p.alignment; - } - write("|" + text); - tableCellIndex++; - if (tableCellIndex % tableColumnCount === 0) { - write("\n"); - if (tableCellIndex === tableColumnCount) { - writeTableHeader(); - } - } - break; - case "TOC Heading": - write("## " + text + "\n\n"); - break; - case "TOC": - var strings = text.split("\t"); - write(" ".substr(0, level * 2 - 2) + "* [" + strings[0] + " " + strings[1] + "](#" + strings[0] + ")\n"); - break; - } - if (sectionBreak) { - write("
\n\n"); - } - lastStyle = style; - lastInTable = inTable; - } - function writeDocument() { - var title = doc.builtInDocumentProperties.item(1) + ""; - if (title.length) { - write("# " + title + "\n\n"); - } - for (var p = doc.paragraphs.first; p; p = p.next()) { - writeParagraph(p); - } - writeBlockEnd(); - } - findReplace("<", {}, "<", {}); - findReplace("<", { style: "Code" }, "<", {}); - findReplace("<", { style: "Code Fragment" }, "<", {}); - findReplace("<", { style: "Terminal" }, "<", {}); - findReplace("", { font: { subscript: true } }, "^&", { font: { subscript: false } }); - findReplace("", { style: "Code Fragment" }, "`^&`", { style: -66 /* default font */ }); - findReplace("", { style: "Production" }, "*^&*", { style: -66 /* default font */ }); - findReplace("", { style: "Terminal" }, "`^&`", { style: -66 /* default font */ }); - findReplace("", { font: { bold: true, italic: true } }, "***^&***", { font: { bold: false, italic: false } }); - findReplace("", { font: { italic: true } }, "*^&*", { font: { italic: false } }); - doc.fields.toggleShowCodes(); - findReplace("^19 REF", {}, "[^&](#^&)", {}); - doc.fields.toggleShowCodes(); - fixHyperlinks(); - writeDocument(); - result = result.replace(/\x85/g, "\u2026"); - result = result.replace(/\x96/g, "\u2013"); - result = result.replace(/\x97/g, "\u2014"); - return result; -} -function main(args) { - if (args.length !== 2) { - sys.write("Syntax: word2md \n"); - return; - } - var app = sys.createObject("Word.Application"); - var doc = app.documents.open(args[0]); - sys.writeFile(args[1], convertDocumentToMarkdown(doc)); - doc.close(false); - app.quit(); -} -main(sys.args); -//# sourceMappingURL=file:///c:/ts/scripts/word2md.js.map \ No newline at end of file diff --git a/scripts/word2md.ts b/scripts/word2md.ts index ec9ed634b3c..f602c700ff9 100644 --- a/scripts/word2md.ts +++ b/scripts/word2md.ts @@ -72,6 +72,9 @@ module Word { listFormat: ListFormat; tables: Tables; text: string; + textRetrievalMode: { + includeHiddenText: boolean; + } words: Ranges; } @@ -258,13 +261,27 @@ function convertDocumentToMarkdown(doc: Word.Document): string { function writeParagraph(p: Word.Paragraph) { - var text = p.range.text; + var range = p.range; + var text = range.text; var style = p.style.nameLocal; - var inTable = p.range.tables.count > 0; + var inTable = range.tables.count > 0; var level = 1; var sectionBreak = text.indexOf("\x0C") >= 0; text = trimEndFormattingMarks(text); + if (text === "/") { + // An inline image shows up in the text as a "/". When we see a paragraph + // consisting of nothing but "/", we check to see if the paragraph contains + // hidden text and, if so, emit that instead. The hidden text is assumed to + // contain an appropriate markdown image link. + range.textRetrievalMode.includeHiddenText = true; + var fullText = range.text; + range.textRetrievalMode.includeHiddenText = false; + if (text !== fullText) { + text = "  " + fullText.substr(1); + } + } + if (inTable) { style = "Table"; } @@ -280,7 +297,7 @@ function convertDocumentToMarkdown(doc: Word.Document): string { case "Heading": case "Appendix": - var section = p.range.listFormat.listString; + var section = range.listFormat.listString; write("####".substr(0, level) + '
' + section + " " + text + "\n\n"); break; @@ -291,7 +308,7 @@ function convertDocumentToMarkdown(doc: Word.Document): string { break; case "List Paragraph": - write(" ".substr(0, p.range.listFormat.listLevelNumber * 2 - 2) + "* " + text + "\n"); + write(" ".substr(0, range.listFormat.listLevelNumber * 2 - 2) + "* " + text + "\n"); break; case "Grammar": @@ -310,7 +327,7 @@ function convertDocumentToMarkdown(doc: Word.Document): string { case "Table": if (!lastInTable) { - tableColumnCount = p.range.tables.item(1).columns.count + 1; + tableColumnCount = range.tables.item(1).columns.count + 1; tableCellIndex = 0; } if (tableCellIndex < tableColumnCount) { diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 6edba58cb11..6957be484f3 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -1,3 +1,4 @@ +/// /// /* @internal */ @@ -6,12 +7,12 @@ namespace ts { export const enum ModuleInstanceState { NonInstantiated = 0, - Instantiated = 1, - ConstEnumOnly = 2 + Instantiated = 1, + ConstEnumOnly = 2 } const enum Reachability { - Unintialized = 1 << 0, + Uninitialized = 1 << 0, Reachable = 1 << 1, Unreachable = 1 << 2, ReportedUnreachable = 1 << 3 @@ -116,6 +117,12 @@ namespace ts { let labelIndexMap: Map; let implicitLabels: number[]; + // state used for emit helpers + let hasClassExtends: boolean; + let hasAsyncFunctions: boolean; + let hasDecorators: boolean; + let hasParameterDecorators: boolean; + // 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). @@ -130,6 +137,7 @@ namespace ts { options = opts; inStrictMode = !!file.externalModuleIndicator; classifiableNames = {}; + Symbol = objectAllocator.getSymbolConstructor(); if (!file.locals) { @@ -138,6 +146,8 @@ namespace ts { file.classifiableNames = classifiableNames; } + file = undefined; + options = undefined; parent = undefined; container = undefined; blockScopeContainer = undefined; @@ -147,6 +157,10 @@ namespace ts { labelStack = undefined; labelIndexMap = undefined; implicitLabels = undefined; + hasClassExtends = false; + hasAsyncFunctions = false; + hasDecorators = false; + hasParameterDecorators = false; } return bindSourceFile; @@ -174,20 +188,30 @@ namespace ts { symbol.members = {}; } - if (symbolFlags & SymbolFlags.Value && !symbol.valueDeclaration) { - symbol.valueDeclaration = node; - } + if (symbolFlags & SymbolFlags.Value) { + const valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === SyntaxKind.ModuleDeclaration)) { + // other kinds of value declarations take precedence over modules + symbol.valueDeclaration = node; + } + } } // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node: Declaration): string { if (node.name) { - if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) { - return `"${(node.name).text}"`; + if (isAmbientModule(node)) { + return isGlobalScopeAugmentation(node) ? "__global" : `"${(node.name).text}"`; } if (node.name.kind === SyntaxKind.ComputedPropertyName) { const nameExpression = (node.name).expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (isStringOrNumericLiteral(nameExpression.kind)) { + return (nameExpression).text; + } + Debug.assert(isWellKnownSymbolSyntactically(nameExpression)); return getPropertyNameForKnownSymbolName((nameExpression).name.text); } @@ -208,9 +232,34 @@ namespace ts { return "__export"; case SyntaxKind.ExportAssignment: return (node).isExportEquals ? "export=" : "default"; + case SyntaxKind.BinaryExpression: + switch (getSpecialPropertyAssignmentKind(node)) { + case SpecialPropertyAssignmentKind.ModuleExports: + // module.exports = ... + return "export="; + case SpecialPropertyAssignmentKind.ExportsProperty: + case SpecialPropertyAssignmentKind.ThisProperty: + // exports.x = ... or this.y = ... + return ((node as BinaryExpression).left as PropertyAccessExpression).name.text; + case SpecialPropertyAssignmentKind.PrototypeProperty: + // className.prototype.methodName = ... + return (((node as BinaryExpression).left as PropertyAccessExpression).expression as PropertyAccessExpression).name.text; + } + Debug.fail("Unknown binary declaration kind"); + break; + case SyntaxKind.FunctionDeclaration: case SyntaxKind.ClassDeclaration: return node.flags & NodeFlags.Default ? "default" : undefined; + case SyntaxKind.JSDocFunctionType: + return isJSDocConstructSignature(node) ? "__new" : "__call"; + case SyntaxKind.Parameter: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + Debug.assert(node.parent.kind === SyntaxKind.JSDocFunctionType); + let functionType = node.parent; + let index = indexOf(functionType.parameters, node); + return "p" + index; } } @@ -230,6 +279,7 @@ namespace ts { Debug.assert(!hasDynamicName(node)); const isDefaultExport = node.flags & NodeFlags.Default; + // The exported symbol for an export default function/class node is always named "default" const name = isDefaultExport && parent ? "default" : getDeclarationName(node); @@ -319,7 +369,12 @@ namespace ts { // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. - if (hasExportModifier || container.flags & NodeFlags.ExportContext) { + + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) { const exportKind = (symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | (symbolFlags & SymbolFlags.Type ? SymbolFlags.ExportType : 0) | @@ -339,7 +394,7 @@ namespace ts { // 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 + // Before we recurse into a node's children, we first save the existing parent, container // and block-container. Then after we pop out of processing the children, we restore // these saved values. const saveParent = parent; @@ -364,7 +419,7 @@ namespace ts { // 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 + // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. const containerFlags = getContainerFlags(node); if (containerFlags & ContainerFlags.IsContainer) { @@ -376,7 +431,6 @@ namespace ts { addToContainerChain(container); } - else if (containerFlags & ContainerFlags.IsBlockScopedContainer) { blockScopeContainer = node; blockScopeContainer.locals = undefined; @@ -394,6 +448,9 @@ namespace ts { // reset all reachability check related flags on node (for incremental scenarios) flags &= ~NodeFlags.ReachabilityCheckFlags; + // reset all emit helper flags on node (for incremental scenarios) + flags &= ~NodeFlags.EmitHelperFlags; + if (kind === SyntaxKind.InterfaceDeclaration) { seenThisKeyword = false; } @@ -411,6 +468,10 @@ namespace ts { labelStack = labelIndexMap = implicitLabels = undefined; } + if (isInJavaScriptFile(node) && node.jsDocComment) { + bind(node.jsDocComment); + } + bindReachableStatement(node); if (currentReachabilityState === Reachability.Reachable && isFunctionLikeKind(kind) && nodeIsPresent((node).body)) { @@ -424,6 +485,21 @@ namespace ts { flags = seenThisKeyword ? flags | NodeFlags.ContainsThis : flags & ~NodeFlags.ContainsThis; } + if (kind === SyntaxKind.SourceFile) { + if (hasClassExtends) { + flags |= NodeFlags.HasClassExtends; + } + if (hasDecorators) { + flags |= NodeFlags.HasDecorators; + } + if (hasParameterDecorators) { + flags |= NodeFlags.HasParamDecorators; + } + if (hasAsyncFunctions) { + flags |= NodeFlags.HasAsyncFunctions; + } + } + node.flags = flags; if (saveState) { @@ -441,7 +517,7 @@ namespace ts { /** * Returns true if node and its subnodes were successfully traversed. - * Returning false means that node was not examined and caller needs to dive into the node himself. + * Returning false means that node was not examined and caller needs to dive into the node himself. */ function bindReachableStatement(node: Node): void { if (checkUnreachable(node)) { @@ -551,7 +627,7 @@ namespace ts { } function bindIfStatement(n: IfStatement): void { - // denotes reachability state when entering 'thenStatement' part of the if statement: + // denotes reachability state when entering 'thenStatement' part of the if statement: // i.e. if condition is false then thenStatement is unreachable const ifTrueState = n.expression.kind === SyntaxKind.FalseKeyword ? Reachability.Unreachable : currentReachabilityState; // denotes reachability state when entering 'elseStatement': @@ -610,7 +686,7 @@ namespace ts { // post catch/finally state is reachable if // - post try state is reachable - control flow can fall out of try block // - post catch state is reachable - control flow can fall out of catch block - currentReachabilityState = or(postTryState, postCatchState); + currentReachabilityState = n.catchClause ? or(postTryState, postCatchState) : postTryState; } function bindSwitchStatement(n: SwitchStatement): void { @@ -624,7 +700,7 @@ namespace ts { const hasDefault = forEach(n.caseBlock.clauses, c => c.kind === SyntaxKind.DefaultClause); - // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case + // post switch state is unreachable if switch is exhaustive (has a default case ) and does not have fallthrough from the last case const postSwitchState = hasDefault && currentReachabilityState !== Reachability.Reachable ? Reachability.Unreachable : preSwitchState; popImplicitLabel(postSwitchLabel, postSwitchState); @@ -633,10 +709,14 @@ namespace ts { function bindCaseBlock(n: CaseBlock): void { const startState = currentReachabilityState; - for (const clause of n.clauses) { + for (let i = 0; i < n.clauses.length; i++) { + const clause = n.clauses[i]; currentReachabilityState = startState; bind(clause); - if (clause.statements.length && currentReachabilityState === Reachability.Reachable && options.noFallthroughCasesInSwitch) { + if (clause.statements.length && + i !== n.clauses.length - 1 && // allow fallthrough from the last case + currentReachabilityState === Reachability.Reachable && + options.noFallthroughCasesInSwitch) { errorOnFirstToken(clause, Diagnostics.Fallthrough_case_in_switch); } } @@ -659,8 +739,9 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: - case SyntaxKind.TypeLiteral: case SyntaxKind.ObjectLiteralExpression: + case SyntaxKind.TypeLiteral: + case SyntaxKind.JSDocRecordType: return ContainerFlags.IsContainer; case SyntaxKind.CallSignature: @@ -673,6 +754,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.FunctionType: + case SyntaxKind.JSDocFunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: @@ -690,7 +772,7 @@ namespace ts { 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' + // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following // example: // @@ -746,6 +828,7 @@ namespace ts { case SyntaxKind.TypeLiteral: case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.JSDocRecordType: // 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 @@ -766,6 +849,7 @@ namespace ts { case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: + case SyntaxKind.JSDocFunctionType: 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, @@ -814,8 +898,16 @@ namespace ts { function bindModuleDeclaration(node: ModuleDeclaration) { setExportContextFlag(node); - if (node.name.kind === SyntaxKind.StringLiteral) { - declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes); + if (isAmbientModule(node)) { + if (node.flags & NodeFlags.Export) { + errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (isExternalModuleAugmentation(node)) { + declareSymbolAndAddToSymbolTable(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes); + } + else { + declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes); + } } else { const state = getModuleInstanceState(node); @@ -844,7 +936,7 @@ namespace ts { } } - function bindFunctionOrConstructorType(node: SignatureDeclaration) { + function bindFunctionOrConstructorType(node: SignatureDeclaration): void { // For a given function symbol "<...>(...) => T" we want to generate a symbol identical // to the one we would get for: { <...>(...): T } // @@ -875,7 +967,7 @@ namespace ts { const identifier = prop.name; - // ECMA-262 11.1.5 Object Initialiser + // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and // IsDataDescriptor(propId.descriptor) is true. @@ -919,7 +1011,7 @@ namespace ts { declareModuleMember(node, symbolFlags, symbolExcludes); break; } - // fall through. + // fall through. default: if (!blockScopeContainer.locals) { blockScopeContainer.locals = {}; @@ -1029,7 +1121,7 @@ namespace ts { } function checkStrictModeNumericLiteral(node: LiteralExpression) { - if (inStrictMode && node.flags & NodeFlags.OctalLiteral) { + if (inStrictMode && node.isOctalLiteral) { file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } @@ -1069,7 +1161,7 @@ namespace ts { return "__" + indexOf((node.parent).parameters, node); } - function bind(node: Node) { + function bind(node: Node): void { if (!node) { return; } @@ -1140,14 +1232,37 @@ namespace ts { // 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'"; + return nodeText === '"use strict"' || nodeText === "'use strict'"; } function bindWorker(node: Node) { switch (node.kind) { + /* Strict mode checks */ case SyntaxKind.Identifier: return checkStrictModeIdentifier(node); case SyntaxKind.BinaryExpression: + if (isInJavaScriptFile(node)) { + const specialKind = getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case SpecialPropertyAssignmentKind.ExportsProperty: + bindExportsPropertyAssignment(node); + break; + case SpecialPropertyAssignmentKind.ModuleExports: + bindModuleExportsAssignment(node); + break; + case SpecialPropertyAssignmentKind.PrototypeProperty: + bindPrototypePropertyAssignment(node); + break; + case SpecialPropertyAssignmentKind.ThisProperty: + bindThisPropertyAssignment(node); + break; + case SpecialPropertyAssignmentKind.None: + // Nothing to do + break; + default: + Debug.fail("Unknown special property assignment kind"); + } + } return checkStrictModeBinaryExpression(node); case SyntaxKind.CatchClause: return checkStrictModeCatchClause(node); @@ -1161,10 +1276,11 @@ namespace ts { return checkStrictModePrefixUnaryExpression(node); case SyntaxKind.WithStatement: return checkStrictModeWithStatement(node); - case SyntaxKind.ThisKeyword: + case SyntaxKind.ThisType: seenThisKeyword = true; return; - + case SyntaxKind.TypePredicate: + return checkTypePredicate(node as TypePredicateNode); case SyntaxKind.TypeParameter: return declareSymbolAndAddToSymbolTable(node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes); case SyntaxKind.Parameter: @@ -1174,12 +1290,14 @@ namespace ts { return bindVariableDeclarationOrBindingElement(node); case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: + case SyntaxKind.JSDocRecordMember: return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | ((node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes); case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); case SyntaxKind.EnumMember: return bindPropertyOrMethodOrAccessor(node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes); + case SyntaxKind.CallSignature: case SyntaxKind.ConstructSignature: case SyntaxKind.IndexSignature: @@ -1193,8 +1311,7 @@ namespace ts { return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Method | ((node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes); case SyntaxKind.FunctionDeclaration: - checkStrictModeFunctionName(node); - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes); + return bindFunctionDeclaration(node); case SyntaxKind.Constructor: return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None); case SyntaxKind.GetAccessor: @@ -1203,16 +1320,24 @@ namespace ts { return bindPropertyOrMethodOrAccessor(node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: + case SyntaxKind.JSDocFunctionType: return bindFunctionOrConstructorType(node); case SyntaxKind.TypeLiteral: + case SyntaxKind.JSDocRecordType: return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type"); case SyntaxKind.ObjectLiteralExpression: return bindObjectLiteralExpression(node); case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - checkStrictModeFunctionName(node); - const bindingName = (node).name ? (node).name.text : "__function"; - return bindAnonymousDeclaration(node, SymbolFlags.Function, bindingName); + return bindFunctionExpression(node); + + case SyntaxKind.CallExpression: + if (isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + + // Members of classes, interfaces, and modules case SyntaxKind.ClassExpression: case SyntaxKind.ClassDeclaration: return bindClassLikeDeclaration(node); @@ -1224,11 +1349,15 @@ namespace ts { return bindEnumDeclaration(node); case SyntaxKind.ModuleDeclaration: return bindModuleDeclaration(node); + + // Imports and exports case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.NamespaceImport: case SyntaxKind.ImportSpecifier: case SyntaxKind.ExportSpecifier: return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); + case SyntaxKind.GlobalModuleExportDeclaration: + return bindGlobalModuleExportDeclaration(node); case SyntaxKind.ImportClause: return bindImportClause(node); case SyntaxKind.ExportDeclaration: @@ -1240,19 +1369,35 @@ namespace ts { } } + function checkTypePredicate(node: TypePredicateNode) { + const { parameterName, type } = node; + if (parameterName && parameterName.kind === SyntaxKind.Identifier) { + checkStrictModeIdentifier(parameterName as Identifier); + } + if (parameterName && parameterName.kind === SyntaxKind.ThisType) { + seenThisKeyword = true; + } + bind(type); + } + function bindSourceFileIfExternalModule() { setExportContextFlag(file); if (isExternalModule(file)) { - bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName)}"`); + bindSourceFileAsExternalModule(); } } - function bindExportAssignment(node: ExportAssignment) { + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName) }"`); + } + + function bindExportAssignment(node: ExportAssignment | BinaryExpression) { + const boundExpression = node.kind === SyntaxKind.ExportAssignment ? (node).expression : (node).right; 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) { + else if (boundExpression.kind === SyntaxKind.Identifier && node.kind === SyntaxKind.ExportAssignment) { // 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); } @@ -1262,6 +1407,33 @@ namespace ts { } } + function bindGlobalModuleExportDeclaration(node: GlobalModuleExportDeclaration) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Modifiers_cannot_appear_here)); + } + + if (node.parent.kind !== SyntaxKind.SourceFile) { + file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + return; + } + else { + const parent = node.parent as SourceFile; + + if (!isExternalModule(parent)) { + file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + return; + } + + if (!parent.isDeclarationFile) { + file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + return; + } + } + + file.symbol.globalExports = file.symbol.globalExports || {}; + declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); + } + function bindExportDeclaration(node: ExportDeclaration) { if (!container.symbol || !container.symbol.exports) { // Export * in some sort of block construct @@ -1279,7 +1451,81 @@ namespace ts { } } + function setCommonJsModuleIndicator(node: Node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + } + + function bindExportsPropertyAssignment(node: BinaryExpression) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, SymbolFlags.Property | SymbolFlags.Export, SymbolFlags.None); + } + + function bindModuleExportsAssignment(node: BinaryExpression) { + // 'module.exports = expr' assignment + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node, SymbolFlags.Property | SymbolFlags.Export | SymbolFlags.ValueModule, SymbolFlags.None); + } + + function bindThisPropertyAssignment(node: BinaryExpression) { + // Declare a 'member' in case it turns out the container was an ES5 class + if (container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) { + container.symbol.members = container.symbol.members || {}; + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(container.symbol.members, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes & ~SymbolFlags.Property); + } + } + + function bindPrototypePropertyAssignment(node: BinaryExpression) { + // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. + + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + const leftSideOfAssignment = node.left as PropertyAccessExpression; + const classPrototype = leftSideOfAssignment.expression as PropertyAccessExpression; + const constructorFunction = classPrototype.expression as Identifier; + + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + + const funcSymbol = container.locals[constructorFunction.text]; + if (!funcSymbol || !(funcSymbol.flags & SymbolFlags.Function)) { + return; + } + + // Set up the members collection if it doesn't exist already + if (!funcSymbol.members) { + funcSymbol.members = {}; + } + + // Declare the method/property + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, SymbolFlags.Property, SymbolFlags.PropertyExcludes); + } + + function bindCallExpression(node: CallExpression) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && isRequireCall(node, /*checkArgumentIsStringLiteral*/false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node: ClassLikeDeclaration) { + if (!isDeclarationFile(file) && !isInAmbientContext(node)) { + if (getClassExtendsHeritageClauseElement(node) !== undefined) { + hasClassExtends = true; + } + if (nodeIsDecorated(node)) { + hasDecorators = true; + } + } + if (node.kind === SyntaxKind.ClassDeclaration) { bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes); } @@ -1349,6 +1595,13 @@ namespace ts { } function bindParameter(node: ParameterDeclaration) { + if (!isDeclarationFile(file) && + !isInAmbientContext(node) && + nodeIsDecorated(node)) { + hasDecorators = true; + hasParameterDecorators = true; + } + 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) @@ -1364,16 +1617,45 @@ namespace ts { // If this is a property-parameter, then also declare the property symbol into the // containing class. - if (node.flags & NodeFlags.AccessibilityModifier && - node.parent.kind === SyntaxKind.Constructor && - isClassLike(node.parent.parent)) { - + if (isParameterPropertyDeclaration(node)) { const classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); } } + function bindFunctionDeclaration(node: FunctionDeclaration) { + if (!isDeclarationFile(file) && !isInAmbientContext(node)) { + if (isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + } + + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes); + } + + function bindFunctionExpression(node: FunctionExpression) { + if (!isDeclarationFile(file) && !isInAmbientContext(node)) { + if (isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + } + + checkStrictModeFunctionName(node); + const bindingName = (node).name ? (node).name.text : "__function"; + return bindAnonymousDeclaration(node, SymbolFlags.Function, bindingName); + } + function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { + if (!isDeclarationFile(file) && !isInAmbientContext(node)) { + if (isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; + } + if (nodeIsDecorated(node)) { + hasDecorators = true; + } + } + return hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -1387,14 +1669,14 @@ namespace ts { if (hasProperty(labelIndexMap, name.text)) { return false; } - labelIndexMap[name.text] = labelStack.push(Reachability.Unintialized) - 1; + labelIndexMap[name.text] = labelStack.push(Reachability.Uninitialized) - 1; return true; } function pushImplicitLabel(): number { initializeReachabilityStateIfNecessary(); - const index = labelStack.push(Reachability.Unintialized) - 1; + const index = labelStack.push(Reachability.Uninitialized) - 1; implicitLabels.push(index); return index; } @@ -1424,7 +1706,7 @@ namespace ts { } function setCurrentStateAtLabel(innerMergedState: Reachability, outerState: Reachability, label: Identifier): void { - if (innerMergedState === Reachability.Unintialized) { + if (innerMergedState === Reachability.Uninitialized) { if (label && !options.allowUnusedLabels) { file.bindDiagnostics.push(createDiagnosticForNode(label, Diagnostics.Unused_label)); } @@ -1445,7 +1727,7 @@ namespace ts { return false; } const stateAtLabel = labelStack[index]; - labelStack[index] = stateAtLabel === Reachability.Unintialized ? outerState : or(stateAtLabel, outerState); + labelStack[index] = stateAtLabel === Reachability.Uninitialized ? outerState : or(stateAtLabel, outerState); return true; } @@ -1467,7 +1749,7 @@ namespace ts { // unreachable code is reported if // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error + // - statement is in not ambient context (statements in ambient context is already an error // so we should not report extras) AND // - node is not variable statement OR // - node is block scoped variable statement OR diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ba4d6960bd0..76f32b2fece 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7,7 +7,10 @@ namespace ts { let nextMergeId = 1; export function getNodeId(node: Node): number { - if (!node.id) node.id = nextNodeId++; + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } return node.id; } @@ -15,7 +18,8 @@ namespace ts { export function getSymbolId(symbol: Symbol): number { if (!symbol.id) { - symbol.id = nextSymbolId++; + symbol.id = nextSymbolId; + nextSymbolId++; } return symbol.id; @@ -45,11 +49,14 @@ namespace ts { const compilerOptions = host.getCompilerOptions(); const languageVersion = compilerOptions.target || ScriptTarget.ES3; - const modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; + const modulekind = getEmitModuleKind(compilerOptions); + const allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ModuleKind.System; + const strictNullChecks = compilerOptions.strictNullChecks; const emitResolver = createResolver(); const undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined"); + undefinedSymbol.declarations = []; const argumentsSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "arguments"); const checker: TypeChecker = { @@ -59,12 +66,11 @@ namespace ts { getTypeCount: () => typeCount, isUndefinedSymbol: symbol => symbol === undefinedSymbol, isArgumentsSymbol: symbol => symbol === argumentsSymbol, + isUnknownSymbol: symbol => symbol === unknownSymbol, getDiagnostics, getGlobalDiagnostics, - - // The language service will always care about the narrowed type of a symbol, because that is - // the type the language says the symbol should have. - getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, + getTypeOfSymbolAtLocation, + getSymbolsOfParameterPropertyDeclaration, getDeclaredTypeOfSymbol, getPropertiesOfType, getPropertyOfType, @@ -75,6 +81,7 @@ namespace ts { getSymbolsInScope, getSymbolAtLocation, getShorthandAssignmentValueSymbol, + getExportSpecifierLocalTargetSymbol, getTypeAtLocation: getTypeOfNode, typeToString, getSymbolDisplayBuilder, @@ -100,18 +107,20 @@ namespace ts { const unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown"); const resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__"); + const nullableWideningFlags = strictNullChecks ? 0 : TypeFlags.ContainsUndefinedOrNull; const anyType = createIntrinsicType(TypeFlags.Any, "any"); const stringType = createIntrinsicType(TypeFlags.String, "string"); const numberType = createIntrinsicType(TypeFlags.Number, "number"); const booleanType = createIntrinsicType(TypeFlags.Boolean, "boolean"); const esSymbolType = createIntrinsicType(TypeFlags.ESSymbol, "symbol"); const voidType = createIntrinsicType(TypeFlags.Void, "void"); - const undefinedType = createIntrinsicType(TypeFlags.Undefined | TypeFlags.ContainsUndefinedOrNull, "undefined"); - const nullType = createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsUndefinedOrNull, "null"); + const undefinedType = createIntrinsicType(TypeFlags.Undefined | nullableWideningFlags, "undefined"); + const nullType = createIntrinsicType(TypeFlags.Null | nullableWideningFlags, "null"); + const emptyArrayElementType = createIntrinsicType(TypeFlags.Undefined | TypeFlags.ContainsUndefinedOrNull, "undefined"); const unknownType = createIntrinsicType(TypeFlags.Any, "unknown"); - const circularType = createIntrinsicType(TypeFlags.Any, "__circular__"); const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const emptyUnionType = emptyObjectType; const emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; @@ -122,8 +131,10 @@ namespace ts { const noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - const anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - const unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + const anySignature = createSignature(undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + const unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + + const enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); const globals: SymbolTable = {}; @@ -134,20 +145,19 @@ namespace ts { let globalObjectType: ObjectType; let globalFunctionType: ObjectType; let globalArrayType: GenericType; + let globalReadonlyArrayType: GenericType; let globalStringType: ObjectType; let globalNumberType: ObjectType; let globalBooleanType: ObjectType; let globalRegExpType: ObjectType; let globalTemplateStringsArrayType: ObjectType; let globalESSymbolType: ObjectType; - let jsxElementType: ObjectType; - /** Lazily loaded, use getJsxIntrinsicElementType() */ - let jsxIntrinsicElementsType: ObjectType; let globalIterableType: GenericType; let globalIteratorType: GenericType; let globalIterableIteratorType: GenericType; let anyArrayType: Type; + let anyReadonlyArrayType: Type; let getGlobalClassDecoratorType: () => ObjectType; let getGlobalParameterDecoratorType: () => ObjectType; let getGlobalPropertyDecoratorType: () => ObjectType; @@ -162,15 +172,12 @@ namespace ts { let jsxElementClassType: Type; + let deferredNodes: Node[]; + const tupleTypes: Map = {}; const unionTypes: Map = {}; const intersectionTypes: Map = {}; const stringLiteralTypes: Map = {}; - let emitExtends = false; - let emitDecorate = false; - let emitParam = false; - let emitAwaiter = false; - const emitGenerator = false; const resolutionTargets: TypeSystemEntity[] = []; const resolutionResults: boolean[] = []; @@ -200,21 +207,30 @@ namespace ts { "symbol": { type: esSymbolType, flags: TypeFlags.ESSymbol + }, + "undefined": { + type: undefinedType, + flags: TypeFlags.ContainsUndefinedOrNull } }; + let jsxElementType: ObjectType; + /** Things we lazy load from the JSX namespace */ + const jsxTypes: Map = {}; const JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", ElementClass: "ElementClass", ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - Element: "Element" + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" }; - + const subtypeRelation: Map = {}; const assignableRelation: Map = {}; const comparableRelation: Map = {}; - const identityRelation: Map = {}; + const identityRelation: Map = {}; // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. let _displayBuilder: SymbolDisplayBuilder; @@ -228,6 +244,10 @@ namespace ts { ResolvedReturnType } + const builtinGlobals: SymbolTable = { + [undefinedSymbol.name]: undefinedSymbol + }; + initializeTypeChecker(); return checker; @@ -273,7 +293,10 @@ namespace ts { } function recordMergedSymbol(target: Symbol, source: Symbol) { - if (!source.mergeId) source.mergeId = nextMergeId++; + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } mergedSymbols[source.mergeId] = target; } @@ -296,7 +319,12 @@ namespace ts { target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (!target.valueDeclaration && source.valueDeclaration) target.valueDeclaration = source.valueDeclaration; + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === SyntaxKind.ModuleDeclaration && source.valueDeclaration.kind !== SyntaxKind.ModuleDeclaration))) { + // other kinds of value declarations take precedence over modules + target.valueDeclaration = source.valueDeclaration; + } forEach(source.declarations, node => { target.declarations.push(node); }); @@ -349,6 +377,57 @@ namespace ts { } } + function mergeModuleAugmentation(moduleName: LiteralExpression): void { + const moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + + if (isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + let mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & SymbolFlags.Namespace) { + // if module symbol has already been merged - it is safe to use it. + // otherwise clone it + mainModule = mainModule.flags & SymbolFlags.Merged ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + + function addToSymbolTable(target: SymbolTable, source: SymbolTable, message: DiagnosticMessage) { + for (const id in source) { + if (hasProperty(source, id)) { + if (hasProperty(target, id)) { + // Error on redeclarations + forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } + } + } + + function addDeclarationDiagnostic(id: string, message: DiagnosticMessage) { + return (declaration: Declaration) => diagnostics.add(createDiagnosticForNode(declaration, message, id)); + } + } + function getSymbolLinks(symbol: Symbol): SymbolLinks { if (symbol.flags & SymbolFlags.Transient) return symbol; const id = getSymbolId(symbol); @@ -360,12 +439,8 @@ namespace ts { return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } - function getSourceFile(node: Node): SourceFile { - return getAncestor(node, SyntaxKind.SourceFile); - } - function isGlobalSourceFile(node: Node) { - return node.kind === SyntaxKind.SourceFile && !isExternalModule(node); + return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node); } function getSymbol(symbols: SymbolTable, name: string, meaning: SymbolFlags): Symbol { @@ -386,6 +461,26 @@ namespace ts { // return undefined if we can't find a symbol. } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): [Symbol, Symbol] { + const constructorDeclaration = parameter.parent; + const classDeclaration = parameter.parent.parent; + + const parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, SymbolFlags.Value); + const propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, SymbolFlags.Value); + + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + + Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration: Declaration, usage: Node): boolean { const declarationFile = getSourceFileOfNode(declaration); const useFile = getSourceFileOfNode(usage); @@ -468,28 +563,65 @@ namespace 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)) { - // 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) { + let useResult = true; + if (isFunctionLike(location) && lastLocation && lastLocation !== (location).body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & SymbolFlags.Type && lastLocation.kind !== SyntaxKind.JSDocComment) { + useResult = result.flags & SymbolFlags.TypeParameter + // type parameters are visible in parameter list, return type and type parameter list + ? lastLocation === (location).type || + lastLocation.kind === SyntaxKind.Parameter || + lastLocation.kind === SyntaxKind.TypeParameter + // local types not visible outside the function body + : false; + } + if (meaning & SymbolFlags.Value && result.flags & SymbolFlags.FunctionScopedVariable) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === SyntaxKind.Parameter || + ( + lastLocation === (location).type && + result.valueDeclaration.kind === SyntaxKind.Parameter + ); + } + } + + if (useResult) { break loop; } - result = undefined; + else { + result = undefined; + } } } switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalModule(location)) break; + if (!isExternalOrCommonJsModule(location)) break; case SyntaxKind.ModuleDeclaration: const moduleExports = getSymbolOfNode(location).exports; - if (location.kind === SyntaxKind.SourceFile || - (location.kind === SyntaxKind.ModuleDeclaration && (location).name.kind === SyntaxKind.StringLiteral)) { + if (location.kind === SyntaxKind.SourceFile || isAmbientModule(location)) { - // 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. + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports["default"]) { + const localSymbol = getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { + break loop; + } + result = undefined; + } + + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. // Two things to note about this: // 1. We have to check this without calling getSymbol. The problem with calling getSymbol // on an export specifier is that it might find the export specifier itself, and try to @@ -503,13 +635,6 @@ namespace ts { getDeclarationOfKind(moduleExports[name], SyntaxKind.ExportSpecifier)) { break; } - - result = moduleExports["default"]; - const localSymbol = getLocalSymbolForExportDefault(result); - if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { - break loop; - } - result = undefined; } if (result = getSymbol(moduleExports, name, meaning & SymbolFlags.ModuleMember)) { @@ -638,7 +763,9 @@ namespace ts { if (!result) { if (nameNotFoundMessage) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); + } } return undefined; } @@ -675,6 +802,43 @@ namespace ts { return result; } + function checkAndReportErrorForMissingPrefix(errorLocation: Node, name: string, nameArg: string | Identifier): boolean { + if (!errorLocation || (errorLocation.kind === SyntaxKind.Identifier && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + return false; + } + + const container = getThisContainer(errorLocation, /* includeArrowFunctions */ true); + let location = container; + while (location) { + if (isClassLike(location.parent)) { + const classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + + // Check to see if a static member exists. + const constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg), symbolToString(classSymbol)); + return true; + } + + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !(location.flags & NodeFlags.Static)) { + const instanceType = (getDeclaredTypeOfSymbol(classSymbol)).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); + return true; + } + } + } + + location = location.parent; + } + return false; + } + function checkResolvedBlockScopedVariable(result: Symbol, errorLocation: Node): void { Debug.assert((result.flags & SymbolFlags.BlockScopedVariable) !== 0); // Block-scoped variables cannot be used before their definition @@ -729,11 +893,18 @@ namespace ts { function getTargetOfImportClause(node: ImportClause): Symbol { const moduleSymbol = resolveExternalModuleName(node, (node.parent).moduleSpecifier); + if (moduleSymbol) { - const exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); - if (!exportDefaultSymbol) { + const exportDefaultSymbol = moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); + + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } return exportDefaultSymbol; } } @@ -743,15 +914,6 @@ namespace ts { return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } - function getMemberOfModuleVariable(moduleSymbol: Symbol, name: string): Symbol { - if (moduleSymbol.flags & SymbolFlags.Variable) { - const typeAnnotation = (moduleSymbol.valueDeclaration).type; - if (typeAnnotation) { - return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); - } - } - } - // This function creates a synthetic symbol that combines the value side of one symbol with the // type/namespace side of another symbol. Consider this example: // @@ -807,8 +969,15 @@ namespace ts { if (targetSymbol) { const name = specifier.propertyName || specifier.name; if (name.text) { + let symbolFromVariable: Symbol; + // First check if module was specified with "export=". If so, get the member from the resolved type + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.text); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); + } const symbolFromModule = getExportOfModule(targetSymbol, name.text); - const symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); const symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; @@ -824,6 +993,10 @@ namespace ts { return getExternalModuleMember(node.parent.parent.parent, node); } + function getTargetOfGlobalModuleExportDeclaration(node: GlobalModuleExportDeclaration): Symbol { + return resolveExternalModuleSymbol(node.parent.symbol); + } + function getTargetOfExportSpecifier(node: ExportSpecifier): Symbol { return (node.parent.parent).moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : @@ -848,6 +1021,8 @@ namespace ts { return getTargetOfExportSpecifier(node); case SyntaxKind.ExportAssignment: return getTargetOfExportAssignment(node); + case SyntaxKind.GlobalModuleExportDeclaration: + return getTargetOfGlobalModuleExportDeclaration(node); } } @@ -982,12 +1157,15 @@ namespace ts { } function resolveExternalModuleName(location: Node, moduleReferenceExpression: Expression): Symbol { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, Diagnostics.Cannot_find_module_0); + } + + function resolveExternalModuleNameWorker(location: Node, moduleReferenceExpression: Expression, moduleNotFoundError: DiagnosticMessage): Symbol { if (moduleReferenceExpression.kind !== SyntaxKind.StringLiteral) { return; } const moduleReferenceLiteral = moduleReferenceExpression; - const searchPath = getDirectoryPath(getSourceFile(location).fileName); // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. @@ -996,30 +1174,40 @@ namespace ts { if (moduleName === undefined) { return; } + const isRelative = isExternalModuleNameRelative(moduleName); if (!isRelative) { - const symbol = getSymbol(globals, "\"" + moduleName + "\"", SymbolFlags.ValueModule); + const symbol = getSymbol(globals, '"' + moduleName + '"', SymbolFlags.ValueModule); if (symbol) { - return symbol; + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(symbol); } } - const resolvedModule = getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); + const resolvedModule = getResolvedModule(getSourceFileOfNode(location), moduleReferenceLiteral.text); const sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - return sourceFile.symbol; + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); } - error(moduleReferenceLiteral, Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - return; + if (moduleNotFoundError) { + // report errors only if it was requested + error(moduleReferenceLiteral, Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; } - error(moduleReferenceLiteral, Diagnostics.Cannot_find_module_0, moduleName); + if (moduleNotFoundError) { + // report errors only if it was requested + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); + } + return undefined; } // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, // and an external module with no 'export =' declaration resolves to the module itself. function resolveExternalModuleSymbol(moduleSymbol: Symbol): Symbol { - return moduleSymbol && resolveSymbol(moduleSymbol.exports["export="]) || moduleSymbol; + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports["export="])) || moduleSymbol; } // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' @@ -1034,8 +1222,8 @@ namespace ts { return symbol; } - function getExportAssignmentSymbol(moduleSymbol: Symbol): Symbol { - return moduleSymbol.exports["export="]; + function hasExportAssignmentSymbol(moduleSymbol: Symbol): boolean { + return moduleSymbol.exports["export="] !== undefined; } function getExportsOfModuleAsArray(moduleSymbol: Symbol): Symbol[] { @@ -1051,39 +1239,81 @@ namespace ts { return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } - function extendExportSymbols(target: SymbolTable, source: SymbolTable) { + interface ExportCollisionTracker { + specifierText: string; + exportsWithDuplicate: ExportDeclaration[]; + } + + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target: SymbolTable, source: SymbolTable, lookupTable?: Map, exportNode?: ExportDeclaration) { for (const id in source) { if (id !== "default" && !hasProperty(target, id)) { target[id] = source[id]; + if (lookupTable && exportNode) { + lookupTable[id] = { + specifierText: getTextOfNode(exportNode.moduleSpecifier) + } as ExportCollisionTracker; + } + } + else if (lookupTable && exportNode && id !== "default" && hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + if (!lookupTable[id].exportsWithDuplicate) { + lookupTable[id].exportsWithDuplicate = [exportNode]; + } + else { + lookupTable[id].exportsWithDuplicate.push(exportNode); + } } } } function getExportsForModule(moduleSymbol: Symbol): SymbolTable { - let result: SymbolTable; const visitedSymbols: Symbol[] = []; - visit(moduleSymbol); - return result || moduleSymbol.exports; + return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. - function visit(symbol: Symbol) { - if (symbol && symbol.flags & SymbolFlags.HasExports && !contains(visitedSymbols, symbol)) { - visitedSymbols.push(symbol); - if (symbol !== moduleSymbol) { - if (!result) { - result = cloneSymbolTable(moduleSymbol.exports); - } - extendExportSymbols(result, symbol.exports); - } - // All export * declarations are collected in an __export symbol by the binder - const exportStars = symbol.exports["__export"]; - if (exportStars) { - for (const node of exportStars.declarations) { - visit(resolveExternalModuleName(node, (node).moduleSpecifier)); - } - } + function visit(symbol: Symbol): SymbolTable { + if (!(symbol && symbol.flags & SymbolFlags.HasExports && !contains(visitedSymbols, symbol))) { + return; } + visitedSymbols.push(symbol); + const symbols = cloneSymbolTable(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + const exportStars = symbol.exports["__export"]; + if (exportStars) { + const nestedSymbols: SymbolTable = {}; + const lookupTable: Map = {}; + for (const node of exportStars.declarations) { + const resolvedModule = resolveExternalModuleName(node, (node as ExportDeclaration).moduleSpecifier); + const exportedSymbols = visit(resolvedModule); + extendExportSymbols( + nestedSymbols, + exportedSymbols, + lookupTable, + node as ExportDeclaration + ); + } + for (const id in lookupTable) { + const { exportsWithDuplicate } = lookupTable[id]; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || hasProperty(symbols, id)) { + continue; + } + for (const node of exportsWithDuplicate) { + diagnostics.add(createDiagnosticForNode( + node, + Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, + lookupTable[id].specifierText, + id + )); + } + } + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; } } @@ -1137,7 +1367,8 @@ namespace ts { function createType(flags: TypeFlags): Type { const result = new Type(checker, flags); - result.id = typeCount++; + result.id = typeCount; + typeCount++; return result; } @@ -1180,19 +1411,19 @@ namespace ts { return result || emptyArray; } - function setObjectTypeMembers(type: ObjectType, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexType: Type, numberIndexType: Type): ResolvedType { + function setObjectTypeMembers(type: ObjectType, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo, numberIndexInfo: IndexInfo): ResolvedType { (type).members = members; (type).properties = getNamedMembers(members); (type).callSignatures = callSignatures; (type).constructSignatures = constructSignatures; - if (stringIndexType) (type).stringIndexType = stringIndexType; - if (numberIndexType) (type).numberIndexType = numberIndexType; + if (stringIndexInfo) (type).stringIndexInfo = stringIndexInfo; + if (numberIndexInfo) (type).numberIndexInfo = numberIndexInfo; return type; } - function createAnonymousType(symbol: Symbol, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexType: Type, numberIndexType: Type): ResolvedType { + function createAnonymousType(symbol: Symbol, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo, numberIndexInfo: IndexInfo): ResolvedType { return setObjectTypeMembers(createObjectType(TypeFlags.Anonymous, symbol), - members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function forEachSymbolTableInScope(enclosingDeclaration: Node, callback: (symbolTable: SymbolTable) => T): T { @@ -1206,7 +1437,7 @@ namespace ts { } switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalModule(location)) { + if (!isExternalOrCommonJsModule(location)) { break; } case SyntaxKind.ModuleDeclaration: @@ -1214,12 +1445,6 @@ namespace ts { return result; } break; - case SyntaxKind.ClassDeclaration: - case SyntaxKind.InterfaceDeclaration: - if (result = callback(getSymbolOfNode(location).members)) { - return result; - } - break; } } @@ -1247,7 +1472,7 @@ namespace ts { function isAccessible(symbolFromSymbolTable: Symbol, resolvedAliasSymbol?: Symbol) { if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) - // and if symbolfrom symbolTable or alias resolution matches the symbol, + // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible return !forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && canQualifySymbol(symbolFromSymbolTable, meaning); @@ -1285,7 +1510,9 @@ namespace ts { } if (symbol) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + } } } @@ -1318,7 +1545,25 @@ namespace ts { return qualify; } - function isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult { + function isPropertyOrMethodDeclarationSymbol(symbol: Symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (const declaration of symbol.declarations) { + switch (declaration.kind) { + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + continue; + default: + return false; + } + } + return true; + } + return false; + } + + function isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessibilityResult { if (symbol && enclosingDeclaration && !(symbol.flags & SymbolFlags.TypeParameter)) { const initialSymbol = symbol; let meaningToLook = meaning; @@ -1328,7 +1573,7 @@ namespace ts { if (accessibleSymbolChain) { const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); if (!hasAccessibleDeclarations) { - return { + return { accessibility: SymbolAccessibility.NotAccessible, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, SymbolFlags.Namespace) : undefined, @@ -1387,8 +1632,7 @@ namespace ts { } function hasExternalModuleSymbol(declaration: Node) { - return (declaration.kind === SyntaxKind.ModuleDeclaration && (declaration).name.kind === SyntaxKind.StringLiteral) || - (declaration.kind === SyntaxKind.SourceFile && isExternalModule(declaration)); + return isAmbientModule(declaration) || (declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol: Symbol): SymbolVisibilityResult { @@ -1430,7 +1674,7 @@ namespace ts { function isEntityNameVisible(entityName: EntityName | Expression, enclosingDeclaration: Node): SymbolVisibilityResult { // get symbol of the first identifier of the entityName let meaning: SymbolFlags; - if (entityName.parent.kind === SyntaxKind.TypeQuery) { + if (entityName.parent.kind === SyntaxKind.TypeQuery || isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { // Typeof value meaning = SymbolFlags.Value | SymbolFlags.ExportValue; } @@ -1477,9 +1721,9 @@ namespace ts { return result; } - function signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { + function signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string { const writer = getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); const result = writer.string(); releaseStringWriter(writer); @@ -1499,6 +1743,25 @@ namespace ts { return result; } + function typePredicateToString(typePredicate: TypePredicate, enclosingDeclaration?: Declaration, flags?: TypeFormatFlags): string { + const writer = getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + const result = writer.string(); + releaseStringWriter(writer); + + return result; + } + + function visibilityToString(flags: NodeFlags) { + if (flags === NodeFlags.Private) { + return "private"; + } + if (flags === NodeFlags.Protected) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type: Type): Symbol { if (type.symbol && type.symbol.flags & SymbolFlags.TypeLiteral) { let node = type.symbol.declarations[0].parent; @@ -1512,6 +1775,12 @@ namespace ts { return undefined; } + function isTopLevelInExternalModuleAugmentation(node: Node): boolean { + return node && node.parent && + node.parent.kind === SyntaxKind.ModuleBlock && + isExternalModuleAugmentation(node.parent.parent); + } + function getSymbolDisplayBuilder(): SymbolDisplayBuilder { function getNameOfSymbol(symbol: Symbol): string { @@ -1654,7 +1923,7 @@ namespace ts { writeAnonymousType(type, flags); } else if (type.flags & TypeFlags.StringLiteral) { - writer.writeStringLiteral((type).text); + writer.writeStringLiteral(`"${escapeString((type).text)}"`); } else { // Should never get here @@ -1687,11 +1956,13 @@ namespace ts { } if (pos < end) { writePunctuation(writer, SyntaxKind.LessThanToken); - writeType(typeArguments[pos++], TypeFormatFlags.None); + writeType(typeArguments[pos], TypeFormatFlags.None); + pos++; while (pos < end) { writePunctuation(writer, SyntaxKind.CommaToken); writeSpace(writer); - writeType(typeArguments[pos++], TypeFormatFlags.None); + writeType(typeArguments[pos], TypeFormatFlags.None); + pos++; } writePunctuation(writer, SyntaxKind.GreaterThanToken); } @@ -1807,20 +2078,40 @@ namespace ts { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, SymbolFlags.Value, SymbolFormatFlags.None, typeFormatFlags); } - function getIndexerParameterName(type: ObjectType, indexKind: IndexKind, fallbackName: string): string { - const declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); - if (!declaration) { - // declaration might not be found if indexer was added from the contextual type. - // in this case use fallback name - return fallbackName; + function writeIndexSignature(info: IndexInfo, keyword: SyntaxKind) { + if (info) { + if (info.isReadonly) { + writeKeyword(writer, SyntaxKind.ReadonlyKeyword); + writeSpace(writer); + } + writePunctuation(writer, SyntaxKind.OpenBracketToken); + writer.writeParameter(info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : "x"); + writePunctuation(writer, SyntaxKind.ColonToken); + writeSpace(writer); + writeKeyword(writer, keyword); + writePunctuation(writer, SyntaxKind.CloseBracketToken); + writePunctuation(writer, SyntaxKind.ColonToken); + writeSpace(writer); + writeType(info.type, TypeFormatFlags.None); + writePunctuation(writer, SyntaxKind.SemicolonToken); + writer.writeLine(); + } + } + + function writePropertyWithModifiers(prop: Symbol) { + if (isReadonlySymbol(prop)) { + writeKeyword(writer, SyntaxKind.ReadonlyKeyword); + writeSpace(writer); + } + buildSymbolDisplay(prop, writer); + if (prop.flags & SymbolFlags.Optional) { + writePunctuation(writer, SyntaxKind.QuestionToken); } - Debug.assert(declaration.parameters.length !== 0); - return declarationNameToString(declaration.parameters[0].name); } function writeLiteralType(type: ObjectType, flags: TypeFormatFlags) { const resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) { + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { writePunctuation(writer, SyntaxKind.OpenBraceToken); writePunctuation(writer, SyntaxKind.CloseBraceToken); @@ -1831,7 +2122,7 @@ namespace ts { if (flags & TypeFormatFlags.InElementType) { writePunctuation(writer, SyntaxKind.OpenParenToken); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, /*kind*/ undefined, symbolStack); if (flags & TypeFormatFlags.InElementType) { writePunctuation(writer, SyntaxKind.CloseParenToken); } @@ -1843,7 +2134,7 @@ namespace ts { } writeKeyword(writer, SyntaxKind.NewKeyword); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, symbolStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | TypeFormatFlags.WriteArrowStyleSignature, /*kind*/ undefined, symbolStack); if (flags & TypeFormatFlags.InElementType) { writePunctuation(writer, SyntaxKind.CloseParenToken); } @@ -1857,65 +2148,30 @@ namespace ts { writer.writeLine(); writer.increaseIndent(); for (const signature of resolved.callSignatures) { - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } for (const signature of resolved.constructSignatures) { - writeKeyword(writer, SyntaxKind.NewKeyword); - writeSpace(writer); - - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); - writePunctuation(writer, SyntaxKind.SemicolonToken); - writer.writeLine(); - } - if (resolved.stringIndexType) { - // [x: string]: - writePunctuation(writer, SyntaxKind.OpenBracketToken); - writer.writeParameter(getIndexerParameterName(resolved, IndexKind.String, /*fallbackName*/"x")); - writePunctuation(writer, SyntaxKind.ColonToken); - writeSpace(writer); - writeKeyword(writer, SyntaxKind.StringKeyword); - writePunctuation(writer, SyntaxKind.CloseBracketToken); - writePunctuation(writer, SyntaxKind.ColonToken); - writeSpace(writer); - writeType(resolved.stringIndexType, TypeFormatFlags.None); - writePunctuation(writer, SyntaxKind.SemicolonToken); - writer.writeLine(); - } - if (resolved.numberIndexType) { - // [x: number]: - writePunctuation(writer, SyntaxKind.OpenBracketToken); - writer.writeParameter(getIndexerParameterName(resolved, IndexKind.Number, /*fallbackName*/"x")); - writePunctuation(writer, SyntaxKind.ColonToken); - writeSpace(writer); - writeKeyword(writer, SyntaxKind.NumberKeyword); - writePunctuation(writer, SyntaxKind.CloseBracketToken); - writePunctuation(writer, SyntaxKind.ColonToken); - writeSpace(writer); - writeType(resolved.numberIndexType, TypeFormatFlags.None); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, SignatureKind.Construct, symbolStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } + writeIndexSignature(resolved.stringIndexInfo, SyntaxKind.StringKeyword); + writeIndexSignature(resolved.numberIndexInfo, SyntaxKind.NumberKeyword); for (const p of resolved.properties) { const t = getTypeOfSymbol(p); if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) { const signatures = getSignaturesOfType(t, SignatureKind.Call); for (const signature of signatures) { - buildSymbolDisplay(p, writer); - if (p.flags & SymbolFlags.Optional) { - writePunctuation(writer, SyntaxKind.QuestionToken); - } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + writePropertyWithModifiers(p); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } } else { - buildSymbolDisplay(p, writer); - if (p.flags & SymbolFlags.Optional) { - writePunctuation(writer, SyntaxKind.QuestionToken); - } + writePropertyWithModifiers(p); writePunctuation(writer, SyntaxKind.ColonToken); writeSpace(writer); writeType(t, TypeFormatFlags.None); @@ -1929,10 +2185,10 @@ namespace ts { } } - function buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags) { + function buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags) { const targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & SymbolFlags.Class || targetSymbol.flags & SymbolFlags.Interface || targetSymbol.flags & SymbolFlags.TypeAlias) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); } } @@ -1952,7 +2208,12 @@ namespace ts { if (isRestParameter(parameterNode)) { writePunctuation(writer, SyntaxKind.DotDotDotToken); } - appendSymbolNameOnly(p, writer); + if (isBindingPattern(parameterNode.name)) { + buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + appendSymbolNameOnly(p, writer); + } if (isOptionalParameter(parameterNode)) { writePunctuation(writer, SyntaxKind.QuestionToken); } @@ -1962,20 +2223,63 @@ namespace ts { buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); } + function buildBindingPatternDisplay(bindingPattern: BindingPattern, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { + // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. + if (bindingPattern.kind === SyntaxKind.ObjectBindingPattern) { + writePunctuation(writer, SyntaxKind.OpenBraceToken); + buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, e => buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack)); + writePunctuation(writer, SyntaxKind.CloseBraceToken); + } + else if (bindingPattern.kind === SyntaxKind.ArrayBindingPattern) { + writePunctuation(writer, SyntaxKind.OpenBracketToken); + const elements = bindingPattern.elements; + buildDisplayForCommaSeparatedList(elements, writer, e => buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack)); + if (elements && elements.hasTrailingComma) { + writePunctuation(writer, SyntaxKind.CommaToken); + } + writePunctuation(writer, SyntaxKind.CloseBracketToken); + } + } + + function buildBindingElementDisplay(bindingElement: BindingElement, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { + if (bindingElement.kind === SyntaxKind.OmittedExpression) { + return; + } + Debug.assert(bindingElement.kind === SyntaxKind.BindingElement); + if (bindingElement.propertyName) { + writer.writeSymbol(getTextOfNode(bindingElement.propertyName), bindingElement.symbol); + writePunctuation(writer, SyntaxKind.ColonToken); + writeSpace(writer); + } + if (isBindingPattern(bindingElement.name)) { + buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + if (bindingElement.dotDotDotToken) { + writePunctuation(writer, SyntaxKind.DotDotDotToken); + } + appendSymbolNameOnly(bindingElement.symbol, writer); + } + } + 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++) { - if (i > 0) { - writePunctuation(writer, SyntaxKind.CommaToken); - writeSpace(writer); - } - buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, symbolStack); - } + buildDisplayForCommaSeparatedList(typeParameters, writer, p => buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack)); writePunctuation(writer, SyntaxKind.GreaterThanToken); } } + function buildDisplayForCommaSeparatedList(list: T[], writer: SymbolWriter, action: (item: T) => void) { + for (let i = 0; i < list.length; i++) { + if (i > 0) { + writePunctuation(writer, SyntaxKind.CommaToken); + writeSpace(writer); + } + action(list[i]); + } + } + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters: TypeParameter[], mapper: TypeMapper, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { if (typeParameters && typeParameters.length) { writePunctuation(writer, SyntaxKind.LessThanToken); @@ -2002,6 +2306,19 @@ namespace ts { writePunctuation(writer, SyntaxKind.CloseParenToken); } + function buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]): void { + if (isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, SyntaxKind.ThisKeyword); + } + writeSpace(writer); + writeKeyword(writer, SyntaxKind.IsKeyword); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { if (flags & TypeFormatFlags.WriteArrowStyleSignature) { writeSpace(writer); @@ -2012,21 +2329,21 @@ namespace ts { } writeSpace(writer); - let returnType: Type; if (signature.typePredicate) { - writer.writeParameter(signature.typePredicate.parameterName); - writeSpace(writer); - writeKeyword(writer, SyntaxKind.IsKeyword); - writeSpace(writer); - returnType = signature.typePredicate.type; + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); } else { - returnType = getReturnTypeOfSignature(signature); + const returnType = getReturnTypeOfSignature(signature); + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { + function buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind, symbolStack?: Symbol[]) { + if (kind === SignatureKind.Construct) { + writeKeyword(writer, SyntaxKind.NewKeyword); + writeSpace(writer); + } + if (signature.target && (flags & TypeFormatFlags.WriteTypeArgumentsOfSignature)) { // Instantiated signature, write type arguments instead // This is achieved by passing in the mapper separately @@ -2037,6 +2354,7 @@ namespace ts { } buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); } @@ -2044,6 +2362,7 @@ namespace ts { buildSymbolDisplay, buildTypeDisplay, buildTypeParameterDisplay, + buildTypePredicateDisplay, buildParameterDisplay, buildDisplayForParametersAndDelimiters, buildDisplayForTypeParametersAndDelimiters, @@ -2054,65 +2373,15 @@ namespace ts { } function isDeclarationVisible(node: Declaration): boolean { - function getContainingExternalModule(node: Node) { - for (; node; node = node.parent) { - if (node.kind === SyntaxKind.ModuleDeclaration) { - if ((node).name.kind === SyntaxKind.StringLiteral) { - return node; - } - } - else if (node.kind === SyntaxKind.SourceFile) { - return isExternalModule(node) ? node : undefined; - } + if (node) { + const links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); } - Debug.fail("getContainingModule cant reach here"); + return links.isVisible; } - function isUsedInExportAssignment(node: Node) { - // Get source File and see if it is external module and has export assigned symbol - const externalModule = getContainingExternalModule(node); - let exportAssignmentSymbol: Symbol; - let resolvedExportSymbol: Symbol; - if (externalModule) { - // This is export assigned symbol node - const externalModuleSymbol = getSymbolOfNode(externalModule); - exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - const symbolOfNode = getSymbolOfNode(node); - if (isSymbolUsedInExportAssignment(symbolOfNode)) { - return true; - } - - // if symbolOfNode is alias declaration, resolve the symbol declaration and check - if (symbolOfNode.flags & SymbolFlags.Alias) { - return isSymbolUsedInExportAssignment(resolveAlias(symbolOfNode)); - } - } - - // Check if the symbol is used in export assignment - function isSymbolUsedInExportAssignment(symbol: Symbol) { - if (exportAssignmentSymbol === symbol) { - return true; - } - - if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & SymbolFlags.Alias)) { - // if export assigned symbol is alias declaration, resolve the alias - resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol); - if (resolvedExportSymbol === symbol) { - return true; - } - - // Container of resolvedExportSymbol is visible - return forEach(resolvedExportSymbol.declarations, (current: Node) => { - while (current) { - if (current === node) { - return true; - } - current = current.parent; - } - }); - } - } - } + return false; function determineIfDeclarationIsVisible() { switch (node.kind) { @@ -2132,6 +2401,10 @@ namespace ts { case SyntaxKind.FunctionDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.ImportEqualsDeclaration: + // external module augmentation is always visible + if (isExternalModuleAugmentation(node)) { + return true; + } const parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(getCombinedNodeFlags(node) & NodeFlags.Export) && @@ -2183,22 +2456,14 @@ namespace ts { case SyntaxKind.SourceFile: return true; - // Export assignements do not create name bindings outside the module + // Export assignments do not create name bindings outside the module case SyntaxKind.ExportAssignment: return false; default: - Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); + return false; } } - - if (node) { - const links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } } function collectLinkedAliases(node: Identifier): Node[] { @@ -2232,7 +2497,9 @@ namespace ts { const firstIdentifier = getFirstIdentifier(internalModuleReference); const importSymbol = resolveName(declaration, firstIdentifier.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, Diagnostics.Cannot_find_name_0, firstIdentifier); - buildVisibleNodeList(importSymbol.declarations); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } } }); } @@ -2260,7 +2527,7 @@ namespace ts { return false; } resolutionTargets.push(target); - resolutionResults.push(true); + resolutionResults.push(/*items*/ true); resolutionPropertyNames.push(propertyName); return true; } @@ -2306,10 +2573,21 @@ namespace ts { function getDeclarationContainer(node: Node): Node { node = getRootDeclaration(node); + while (node) { + switch (node.kind) { + case SyntaxKind.VariableDeclaration: + case SyntaxKind.VariableDeclarationList: + case SyntaxKind.ImportSpecifier: + case SyntaxKind.NamedImports: + case SyntaxKind.NamespaceImport: + case SyntaxKind.ImportClause: + node = node.parent; + break; - // Parent chain: - // VaribleDeclaration -> VariableDeclarationList -> VariableStatement -> 'Declaration Container' - return node.kind === SyntaxKind.VariableDeclaration ? node.parent.parent.parent : node.parent; + default: + return node.parent; + } + } } function getTypeOfPrototypeProperty(prototype: Symbol): Type { @@ -2317,7 +2595,7 @@ namespace ts { // 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'. - const classType = getDeclaredTypeOfSymbol(prototype.parent); + const classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); return classType.typeParameters ? createTypeReference(classType, map(classType.typeParameters, _ => anyType)) : classType; } @@ -2338,7 +2616,27 @@ namespace ts { return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); } - // Return the inferred type for a binding element + function getTextOfPropertyName(name: PropertyName): string { + switch (name.kind) { + case SyntaxKind.Identifier: + return (name).text; + case SyntaxKind.StringLiteral: + case SyntaxKind.NumericLiteral: + return (name).text; + case SyntaxKind.ComputedPropertyName: + if (isStringOrNumericLiteral((name).expression.kind)) { + return ((name).expression).text; + } + } + + return undefined; + } + + function isComputedNonLiteralName(name: PropertyName): boolean { + return name.kind === SyntaxKind.ComputedPropertyName && !isStringOrNumericLiteral((name).expression.kind); + } + + /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration: BindingElement): Type { const pattern = declaration.parent; const parentType = getTypeForBindingElementParent(pattern.parent); @@ -2360,10 +2658,20 @@ namespace ts { if (pattern.kind === SyntaxKind.ObjectBindingPattern) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) const name = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name)) { + // computed properties with non-literal names are treated as 'any' + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - type = getTypeOfPropertyOfType(parentType, name.text) || - isNumericLiteralName(name.text) && getIndexTypeOfType(parentType, IndexKind.Number) || + const text = getTextOfPropertyName(name); + + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, IndexKind.Number) || getIndexTypeOfType(parentType, IndexKind.String); if (!type) { error(name, Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), declarationNameToString(name)); @@ -2396,14 +2704,65 @@ namespace ts { type = createArrayType(elementType); } } + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && declaration.initializer && !(getNullableKind(checkExpressionCached(declaration.initializer)) & TypeFlags.Undefined)) { + type = removeNullableKind(type, TypeFlags.Undefined); + } return type; } + function getTypeForVariableLikeDeclarationFromJSDocComment(declaration: VariableLikeDeclaration) { + const jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return getTypeFromTypeNode(jsDocType); + } + } + + function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration: VariableLikeDeclaration): JSDocType { + // First, see if this node has an @type annotation on it directly. + const typeTag = getJSDocTypeTag(declaration); + if (typeTag && typeTag.typeExpression) { + return typeTag.typeExpression.type; + } + + if (declaration.kind === SyntaxKind.VariableDeclaration && + declaration.parent.kind === SyntaxKind.VariableDeclarationList && + declaration.parent.parent.kind === SyntaxKind.VariableStatement) { + + // @type annotation might have been on the variable statement, try that instead. + const annotation = getJSDocTypeTag(declaration.parent.parent); + if (annotation && annotation.typeExpression) { + return annotation.typeExpression.type; + } + } + else if (declaration.kind === SyntaxKind.Parameter) { + // If it's a parameter, see if the parent has a jsdoc comment with an @param + // annotation. + const paramTag = getCorrespondingJSDocParameterTag(declaration); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type; + } + } + + return undefined; + } + // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration): Type { - // A variable declared in a for..in statement is always of type any + if (declaration.flags & NodeFlags.JavaScriptFile) { + // If this is a variable in a JavaScript file, then use the JSDoc type (if it has + // one as its type), otherwise fallback to the below standard TS codepaths to + // try to figure it out. + const type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (type && type !== unknownType) { + return type; + } + } + + // A variable declared in a for..in statement is always of type string if (declaration.parent.parent.kind === SyntaxKind.ForInStatement) { - return anyType; + return stringType; } if (declaration.parent.parent.kind === SyntaxKind.ForOfStatement) { @@ -2420,7 +2779,8 @@ namespace ts { // Use type from type annotation if one is present if (declaration.type) { - return getTypeFromTypeNode(declaration.type); + const type = getTypeFromTypeNode(declaration.type); + return strictNullChecks && declaration.questionToken ? addNullableKind(type, TypeFlags.Undefined) : type; } if (declaration.kind === SyntaxKind.Parameter) { @@ -2435,7 +2795,7 @@ namespace ts { // Use contextual parameter type if one is available const type = getContextuallyTypedParameterType(declaration); if (type) { - return type; + return strictNullChecks && declaration.questionToken ? addNullableKind(type, TypeFlags.Undefined) : type; } } @@ -2474,10 +2834,18 @@ namespace ts { // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern: BindingPattern, includePatternInType: boolean): Type { const members: SymbolTable = {}; + let hasComputedProperties = false; forEach(pattern.elements, e => { - const flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0); const name = e.propertyName || e.name; - const symbol = createSymbol(flags, name.text); + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + hasComputedProperties = true; + return; + } + + const text = getTextOfPropertyName(name); + const flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0); + const symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; @@ -2486,6 +2854,9 @@ namespace ts { if (includePatternInType) { result.pattern = pattern; } + if (hasComputedProperties) { + result.flags |= TypeFlags.ObjectLiteralPatternWithComputedProperties; + } return result; } @@ -2536,7 +2907,10 @@ namespace 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 !== SyntaxKind.PropertyAssignment ? getWidenedType(type) : type; + if (declaration.kind === SyntaxKind.PropertyAssignment) { + return type; + } + return getWidenedType(type); } // Rest parameters default to type any[], other parameters default to type any @@ -2568,6 +2942,18 @@ namespace ts { if (declaration.kind === SyntaxKind.ExportAssignment) { return links.type = checkExpression((declaration).expression); } + // Handle module.exports = expr + if (declaration.kind === SyntaxKind.BinaryExpression) { + return links.type = getUnionType(map(symbol.declarations, (decl: BinaryExpression) => checkExpressionCached(decl.right))); + } + if (declaration.kind === SyntaxKind.PropertyAccessExpression) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === SyntaxKind.BinaryExpression) { + // Handle exports.p = expr or this.p = expr or className.prototype.method = expr + return links.type = checkExpressionCached((declaration.parent).right); + } + } // Handle variable, parameter or property if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { return unknownType; @@ -2610,12 +2996,22 @@ namespace ts { function getTypeOfAccessors(symbol: Symbol): Type { const links = getSymbolLinks(symbol); if (!links.type) { + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + + if (getter && getter.flags & NodeFlags.JavaScriptFile) { + const jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); + if (jsDocType) { + return links.type = jsDocType; + } + } + if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { return unknownType; } - const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); - const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + let type: Type; + // First try to see if the user specified a return type on the get-accessor. const getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { @@ -2848,10 +3244,6 @@ namespace ts { return type.resolvedBaseConstructorType; } - function hasClassBaseType(type: InterfaceType): boolean { - return !!forEach(getBaseTypes(type), t => !!(t.symbol.flags & SymbolFlags.Class)); - } - function getBaseTypes(type: InterfaceType): ObjectType[] { const isClass = type.symbol.flags & SymbolFlags.Class; const isInterface = type.symbol.flags & SymbolFlags.Interface; @@ -2871,23 +3263,25 @@ namespace ts { function resolveBaseTypesOfClass(type: InterfaceType): void { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - const baseContructorType = getBaseConstructorTypeOfClass(type); - if (!(baseContructorType.flags & TypeFlags.ObjectType)) { + const baseConstructorType = getBaseConstructorTypeOfClass(type); + if (!(baseConstructorType.flags & TypeFlags.ObjectType)) { return; } const 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 + const originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & SymbolFlags.Class && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // 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); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.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. - const constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); + const constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments); if (!constructors.length) { error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return; @@ -2914,6 +3308,18 @@ namespace ts { } } + function areAllOuterTypeParametersApplied(type: Type): boolean { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + const outerTypeParameters = (type).outerTypeParameters; + if (outerTypeParameters) { + const last = outerTypeParameters.length - 1; + const typeArguments = (type).typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } + function resolveBaseTypesOfInterface(type: InterfaceType): void { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; for (const declaration of type.symbol.declarations) { @@ -2991,7 +3397,7 @@ namespace ts { (type).typeArguments = type.typeParameters; type.thisType = createType(TypeFlags.TypeParameter | TypeFlags.ThisType); type.thisType.symbol = symbol; - type.thisType.constraint = getTypeWithThisArgument(type); + type.thisType.constraint = type; } } return links.declaredType; @@ -3099,7 +3505,9 @@ namespace ts { case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.VoidKeyword: - case SyntaxKind.StringLiteral: + case SyntaxKind.UndefinedKeyword: + case SyntaxKind.NullKeyword: + case SyntaxKind.StringLiteralType: return true; case SyntaxKind.ArrayType: return isIndependentType((node).elementType); @@ -3132,7 +3540,7 @@ namespace ts { // Returns true if the class or interface member given by the symbol is free of "this" references. The // function may return false for symbols that are actually free of "this" references because it is not // feasible to perform a complete analysis in all cases. In particular, property members with types - // inferred from their initializers and function members with inferred return types are convervatively + // inferred from their initializers and function members with inferred return types are conservatively // assumed not to be free of "this" references. function isIndependentMember(symbol: Symbol): boolean { if (symbol.declarations && symbol.declarations.length === 1) { @@ -3178,22 +3586,14 @@ namespace ts { } } - function addInheritedSignatures(signatures: Signature[], baseSignatures: Signature[]) { - if (baseSignatures) { - for (const signature of baseSignatures) { - signatures.push(signature); - } - } - } - function resolveDeclaredMembers(type: InterfaceType): InterfaceTypeWithDeclaredMembers { if (!(type).declaredProperties) { const symbol = type.symbol; (type).declaredProperties = getNamedMembers(symbol.members); (type).declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]); (type).declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]); - (type).declaredStringIndexType = getIndexTypeOfSymbol(symbol, IndexKind.String); - (type).declaredNumberIndexType = getIndexTypeOfSymbol(symbol, IndexKind.Number); + (type).declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.String); + (type).declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.Number); } return type; } @@ -3211,15 +3611,15 @@ namespace ts { let members = source.symbol.members; let callSignatures = source.declaredCallSignatures; let constructSignatures = source.declaredConstructSignatures; - let stringIndexType = source.declaredStringIndexType; - let numberIndexType = source.declaredNumberIndexType; + let stringIndexInfo = source.declaredStringIndexInfo; + let numberIndexInfo = source.declaredNumberIndexInfo; if (!rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { mapper = createTypeMapper(typeParameters, typeArguments); members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); - stringIndexType = instantiateType(source.declaredStringIndexType, mapper); - numberIndexType = instantiateType(source.declaredNumberIndexType, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); } const baseTypes = getBaseTypes(source); if (baseTypes.length) { @@ -3232,11 +3632,11 @@ namespace ts { addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Call)); constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Construct)); - stringIndexType = stringIndexType || getIndexTypeOfType(instantiatedBaseType, IndexKind.String); - numberIndexType = numberIndexType || getIndexTypeOfType(instantiatedBaseType, IndexKind.Number); + stringIndexInfo = stringIndexInfo || getIndexInfoOfType(instantiatedBaseType, IndexKind.String); + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, IndexKind.Number); } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveClassOrInterfaceMembers(type: InterfaceType): void { @@ -3266,16 +3666,16 @@ namespace ts { } function cloneSignature(sig: Signature): Signature { - return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, - 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: InterfaceType): Signature[] { - if (!hasClassBaseType(classType)) { - return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; - } const baseConstructorType = getBaseConstructorTypeOfClass(classType); const baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; + } const baseTypeNode = getBaseTypeNodeOfClass(classType); const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); const typeArgCount = typeArguments ? typeArguments.length : 0; @@ -3308,12 +3708,12 @@ namespace ts { const arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); const members = createTupleTypeMemberSymbols(type.elementTypes); addInheritedMembers(members, arrayType.properties); - setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexInfo, arrayType.numberIndexInfo); } function findMatchingSignature(signatureList: Signature[], signature: Signature, partialMatch: boolean, ignoreReturnTypes: boolean): Signature { for (const s of signatureList) { - if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreReturnTypes, compareTypesIdentical)) { return s; } } @@ -3376,16 +3776,18 @@ namespace ts { return result || emptyArray; } - function getUnionIndexType(types: Type[], kind: IndexKind): Type { + function getUnionIndexInfo(types: Type[], kind: IndexKind): IndexInfo { const indexTypes: Type[] = []; + let isAnyReadonly = false; for (const type of types) { - const indexType = getIndexTypeOfType(type, kind); - if (!indexType) { + const indexInfo = getIndexInfoOfType(type, kind); + if (!indexInfo) { return undefined; } - indexTypes.push(indexType); + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; } - return getUnionType(indexTypes); + return createIndexInfo(getUnionType(indexTypes), isAnyReadonly); } function resolveUnionTypeMembers(type: UnionType) { @@ -3393,64 +3795,61 @@ namespace ts { // type use getPropertiesOfType (only the language service uses this). const callSignatures = getUnionSignatures(type.types, SignatureKind.Call); const constructSignatures = getUnionSignatures(type.types, SignatureKind.Construct); - const stringIndexType = getUnionIndexType(type.types, IndexKind.String); - const numberIndexType = getUnionIndexType(type.types, IndexKind.Number); - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + const stringIndexInfo = getUnionIndexInfo(type.types, IndexKind.String); + const numberIndexInfo = getUnionIndexInfo(type.types, IndexKind.Number); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function intersectTypes(type1: Type, type2: Type): Type { return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); } + function intersectIndexInfos(info1: IndexInfo, info2: IndexInfo): IndexInfo { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo( + getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function resolveIntersectionTypeMembers(type: IntersectionType) { // The members and properties collections are empty for intersection types. To get all properties of an // intersection type use getPropertiesOfType (only the language service uses this). let callSignatures: Signature[] = emptyArray; let constructSignatures: Signature[] = emptyArray; - let stringIndexType: Type = undefined; - let numberIndexType: Type = undefined; + let stringIndexInfo: IndexInfo = undefined; + let numberIndexInfo: IndexInfo = undefined; for (const t of type.types) { callSignatures = concatenate(callSignatures, getSignaturesOfType(t, SignatureKind.Call)); constructSignatures = concatenate(constructSignatures, getSignaturesOfType(t, SignatureKind.Construct)); - stringIndexType = intersectTypes(stringIndexType, getIndexTypeOfType(t, IndexKind.String)); - numberIndexType = intersectTypes(numberIndexType, getIndexTypeOfType(t, IndexKind.Number)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, IndexKind.String)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, IndexKind.Number)); } - setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } function resolveAnonymousTypeMembers(type: AnonymousType) { const symbol = type.symbol; - let members: SymbolTable; - let callSignatures: Signature[]; - let constructSignatures: Signature[]; - let stringIndexType: Type; - let numberIndexType: Type; - if (type.target) { - members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); - callSignatures = instantiateList(getSignaturesOfType(type.target, SignatureKind.Call), type.mapper, instantiateSignature); - constructSignatures = instantiateList(getSignaturesOfType(type.target, SignatureKind.Construct), type.mapper, instantiateSignature); - stringIndexType = instantiateType(getIndexTypeOfType(type.target, IndexKind.String), type.mapper); - numberIndexType = instantiateType(getIndexTypeOfType(type.target, IndexKind.Number), type.mapper); + const members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + const callSignatures = instantiateList(getSignaturesOfType(type.target, SignatureKind.Call), type.mapper, instantiateSignature); + const constructSignatures = instantiateList(getSignaturesOfType(type.target, SignatureKind.Construct), type.mapper, instantiateSignature); + const stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, IndexKind.String), type.mapper); + const numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, IndexKind.Number), type.mapper); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & SymbolFlags.TypeLiteral) { - members = symbol.members; - callSignatures = getSignaturesOfSymbol(members["__call"]); - constructSignatures = getSignaturesOfSymbol(members["__new"]); - stringIndexType = getIndexTypeOfSymbol(symbol, IndexKind.String); - numberIndexType = getIndexTypeOfSymbol(symbol, IndexKind.Number); + const members = symbol.members; + const callSignatures = getSignaturesOfSymbol(members["__call"]); + const constructSignatures = getSignaturesOfSymbol(members["__new"]); + const stringIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.String); + const numberIndexInfo = getIndexInfoOfSymbol(symbol, IndexKind.Number); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else { // Combinations of function, class, enum and module - members = emptySymbols; - callSignatures = emptyArray; - constructSignatures = emptyArray; + let members = emptySymbols; + let constructSignatures: Signature[] = emptyArray; if (symbol.flags & SymbolFlags.HasExports) { members = getExportsOfSymbol(symbol); } - if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method)) { - callSignatures = getSignaturesOfSymbol(symbol); - } if (symbol.flags & SymbolFlags.Class) { const classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); @@ -3463,10 +3862,16 @@ namespace ts { addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } - stringIndexType = undefined; - numberIndexType = (symbol.flags & SymbolFlags.Enum) ? stringType : undefined; + const numberIndexInfo = symbol.flags & SymbolFlags.Enum ? enumNumberIndexInfo : undefined; + setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method)) { + (type).callSignatures = getSignaturesOfSymbol(symbol); + } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveStructuredTypeMembers(type: ObjectType): ResolvedType { @@ -3493,7 +3898,7 @@ namespace ts { return type; } - // Return properties of an object type or an empty array for other types + /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type: Type): Symbol[] { if (type.flags & TypeFlags.ObjectType) { return resolveStructuredTypeMembers(type).properties; @@ -3501,8 +3906,8 @@ namespace ts { return emptyArray; } - // If the given type is an object type and that type has a property by the given name, - // return the symbol for that property.Otherwise return undefined. + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type: Type, name: string): Symbol { if (type.flags & TypeFlags.ObjectType) { const resolved = resolveStructuredTypeMembers(type); @@ -3534,6 +3939,21 @@ namespace ts { return type.flags & TypeFlags.UnionOrIntersection ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + /** + * The apparent type of a type parameter is the base constraint instantiated with the type parameter + * as the type argument for the 'this' type. + */ + function getApparentTypeOfTypeParameter(type: TypeParameter) { + if (!type.resolvedApparentType) { + let constraintType = getConstraintOfTypeParameter(type); + while (constraintType && constraintType.flags & TypeFlags.TypeParameter) { + constraintType = getConstraintOfTypeParameter(constraintType); + } + type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); + } + return type.resolvedApparentType; + } + /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -3541,12 +3961,7 @@ namespace ts { */ function getApparentType(type: Type): Type { if (type.flags & TypeFlags.TypeParameter) { - do { - type = getConstraintOfTypeParameter(type); - } while (type && type.flags & TypeFlags.TypeParameter); - if (!type) { - type = emptyObjectType; - } + type = getApparentTypeOfTypeParameter(type); } if (type.flags & TypeFlags.StringLike) { type = globalStringType; @@ -3566,11 +3981,14 @@ namespace ts { function createUnionOrIntersectionProperty(containingType: UnionOrIntersectionType, name: string): Symbol { const types = containingType.types; let props: Symbol[]; + // Flags we want to propagate to the result if they exist in all source symbols + let commonFlags = (containingType.flags & TypeFlags.Intersection) ? SymbolFlags.Optional : SymbolFlags.None; for (const current of types) { const type = getApparentType(current); if (type !== unknownType) { const prop = getPropertyOfType(type, name); if (prop && !(getDeclarationFlagsFromSymbol(prop) & (NodeFlags.Private | NodeFlags.Protected))) { + commonFlags &= prop.flags; if (!props) { props = [prop]; } @@ -3598,7 +4016,12 @@ namespace ts { } propTypes.push(getTypeOfSymbol(prop)); } - const result = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | SymbolFlags.SyntheticProperty, name); + const result = createSymbol( + SymbolFlags.Property | + SymbolFlags.Transient | + SymbolFlags.SyntheticProperty | + commonFlags, + name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & TypeFlags.Union ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -3660,29 +4083,22 @@ namespace ts { return getSignaturesOfStructuredType(getApparentType(type), kind); } - function typeHasConstructSignatures(type: Type): boolean { - const apparentType = getApparentType(type); - if (apparentType.flags & (TypeFlags.ObjectType | TypeFlags.Union)) { + function getIndexInfoOfStructuredType(type: Type, kind: IndexKind): IndexInfo { + if (type.flags & TypeFlags.StructuredType) { const resolved = resolveStructuredTypeMembers(type); - return resolved.constructSignatures.length > 0; + return kind === IndexKind.String ? resolved.stringIndexInfo : resolved.numberIndexInfo; } - return false; - } - - function typeHasCallOrConstructSignatures(type: Type): boolean { - const apparentType = getApparentType(type); - if (apparentType.flags & TypeFlags.StructuredType) { - const resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; - } - return false; } function getIndexTypeOfStructuredType(type: Type, kind: IndexKind): Type { - if (type.flags & TypeFlags.StructuredType) { - const resolved = resolveStructuredTypeMembers(type); - return kind === IndexKind.String ? resolved.stringIndexType : resolved.numberIndexType; - } + const info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo { + return getIndexInfoOfStructuredType(getApparentType(type), kind); } // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and @@ -3691,6 +4107,30 @@ namespace ts { return getIndexTypeOfStructuredType(getApparentType(type), kind); } + function getImplicitIndexTypeOfType(type: Type, kind: IndexKind): Type { + if (isObjectLiteralType(type)) { + const propTypes: Type[] = []; + for (const prop of getPropertiesOfType(type)) { + if (kind === IndexKind.String || isNumericLiteralName(prop.name)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + return getUnionType(propTypes); + } + return undefined; + } + + function getTypeParametersFromJSDocTemplate(declaration: SignatureDeclaration): TypeParameter[] { + if (declaration.flags & NodeFlags.JavaScriptFile) { + const templateTag = getJSDocTemplateTag(declaration); + if (templateTag) { + return getTypeParametersFromDeclaration(templateTag.typeParameters); + } + } + + return undefined; + } + // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(typeParameterDeclarations: TypeParameterDeclaration[]): TypeParameter[] { @@ -3715,6 +4155,23 @@ namespace ts { } function isOptionalParameter(node: ParameterDeclaration) { + if (node.flags & NodeFlags.JavaScriptFile) { + if (node.type && node.type.kind === SyntaxKind.JSDocOptionalType) { + return true; + } + + const paramTag = getCorrespondingJSDocParameterTag(node); + if (paramTag) { + if (paramTag.isBracketed) { + return true; + } + + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === SyntaxKind.JSDocOptionalType; + } + } + } + if (hasQuestionToken(node)) { return true; } @@ -3722,7 +4179,7 @@ namespace ts { if (node.initializer) { const signatureDeclaration = node.parent; const signature = getSignatureFromDeclaration(signatureDeclaration); - const parameterIndex = signatureDeclaration.parameters.indexOf(node); + const parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -3730,6 +4187,24 @@ namespace ts { return false; } + function createTypePredicateFromTypePredicateNode(node: TypePredicateNode): IdentifierTypePredicate | ThisTypePredicate { + if (node.parameterName.kind === SyntaxKind.Identifier) { + const parameterName = node.parameterName as Identifier; + return { + kind: TypePredicateKind.Identifier, + parameterName: parameterName ? parameterName.text : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex((node.parent as SignatureDeclaration).parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + } as IdentifierTypePredicate; + } + else { + return { + kind: TypePredicateKind.This, + type: getTypeFromTypeNode(node.type) + } as ThisTypePredicate; + } + } + function getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature { const links = getNodeLinks(declaration); if (!links.resolvedSignature) { @@ -3737,14 +4212,30 @@ namespace ts { getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)) : undefined; const typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; + declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : + getTypeParametersFromJSDocTemplate(declaration); const parameters: Symbol[] = []; let hasStringLiterals = false; let minArgumentCount = -1; - for (let i = 0, n = declaration.parameters.length; i < n; i++) { + const isJSConstructSignature = isJSDocConstructSignature(declaration); + let returnType: Type = undefined; + let typePredicate: TypePredicate = undefined; + + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (let i = isJSConstructSignature ? 1 : 0, n = declaration.parameters.length; i < n; i++) { const param = declaration.parameters[i]; - parameters.push(param.symbol); - if (param.type && param.type.kind === SyntaxKind.StringLiteral) { + + let paramSymbol = param.symbol; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & SymbolFlags.Property) && !isBindingPattern(param.name)) { + const resolvedSymbol = resolveName(param, paramSymbol.name, SymbolFlags.Value, undefined, undefined); + paramSymbol = resolvedSymbol; + } + parameters.push(paramSymbol); + + if (param.type && param.type.kind === SyntaxKind.StringLiteralType) { hasStringLiterals = true; } @@ -3763,23 +4254,27 @@ namespace ts { minArgumentCount = declaration.parameters.length; } - let returnType: Type; - let typePredicate: TypePredicate; - if (classType) { + if (isJSConstructSignature) { + minArgumentCount--; + returnType = getTypeFromTypeNode(declaration.parameters[0].type); + } + else if (classType) { returnType = classType; } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); if (declaration.type.kind === SyntaxKind.TypePredicate) { - const typePredicateNode = declaration.type; - typePredicate = { - parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, - parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, - type: getTypeFromTypeNode(typePredicateNode.type) - }; + typePredicate = createTypePredicateFromTypePredicateNode(declaration.type as TypePredicateNode); } } else { + if (declaration.flags & NodeFlags.JavaScriptFile) { + const type = getReturnTypeFromJSDocComment(declaration); + if (type && type !== unknownType) { + returnType = type; + } + } + // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. if (declaration.kind === SyntaxKind.GetAccessor && !hasDynamicName(declaration)) { @@ -3792,8 +4287,7 @@ namespace ts { } } - links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, - minArgumentCount, hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, minArgumentCount, hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -3817,6 +4311,7 @@ namespace ts { case SyntaxKind.SetAccessor: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: + case SyntaxKind.JSDocFunctionType: // Don't include signature if node is the implementation of an overloaded function. A node is considered // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). @@ -3832,6 +4327,18 @@ namespace ts { return result; } + function resolveExternalModuleTypeByLiteral(name: StringLiteral) { + const moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + const resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + + return anyType; + } + function getReturnTypeOfSignature(signature: Signature): Type { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, TypeSystemPropertyName.ResolvedReturnType)) { @@ -3875,7 +4382,7 @@ namespace ts { } function getSignatureInstantiation(signature: Signature, typeArguments: Type[]): Signature { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature: Signature): Signature { @@ -3885,7 +4392,7 @@ namespace ts { signature.erasedSignatureCache = instantiateSignature(getErasedSignature(signature.target), signature.mapper); } else { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); } } return signature.erasedSignatureCache; @@ -3931,24 +4438,53 @@ namespace ts { return undefined; } - function getIndexTypeOfSymbol(symbol: Symbol, kind: IndexKind): Type { - const declaration = getIndexDeclarationOfSymbol(symbol, kind); - return declaration - ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType - : undefined; + function createIndexInfo(type: Type, isReadonly: boolean, declaration?: SignatureDeclaration): IndexInfo { + return { type, isReadonly, declaration }; } - function getConstraintOfTypeParameter(type: TypeParameter): Type { - if (!type.constraint) { - if (type.target) { - const targetConstraint = getConstraintOfTypeParameter(type.target); - type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + function getIndexInfoOfSymbol(symbol: Symbol, kind: IndexKind): IndexInfo { + const declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, + (declaration.flags & NodeFlags.Readonly) !== 0, declaration); + } + return undefined; + } + + function getConstraintDeclaration(type: TypeParameter) { + return (getDeclarationOfKind(type.symbol, SyntaxKind.TypeParameter)).constraint; + } + + function hasConstraintReferenceTo(type: Type, target: TypeParameter): boolean { + let checked: Type[]; + while (type && !(type.flags & TypeFlags.ThisType) && type.flags & TypeFlags.TypeParameter && !contains(checked, type)) { + if (type === target) { + return true; + } + (checked || (checked = [])).push(type); + const constraintDeclaration = getConstraintDeclaration(type); + type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration); + } + return false; + } + + function getConstraintOfTypeParameter(typeParameter: TypeParameter): Type { + if (!typeParameter.constraint) { + if (typeParameter.target) { + const targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode((getDeclarationOfKind(type.symbol, SyntaxKind.TypeParameter)).constraint); + const constraintDeclaration = getConstraintDeclaration(typeParameter); + let constraint = getTypeFromTypeNode(constraintDeclaration); + if (hasConstraintReferenceTo(constraint, typeParameter)) { + error(constraintDeclaration, Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + constraint = unknownType; + } + typeParameter.constraint = constraint; } } - return type.constraint === noConstraintType ? undefined : type.constraint; + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter: TypeParameter): Symbol { @@ -3980,10 +4516,12 @@ namespace ts { // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker // that care about the presence of such types at arbitrary depth in a containing type. - function getPropagatingFlagsOfTypes(types: Type[]): TypeFlags { + function getPropagatingFlagsOfTypes(types: Type[], excludeKinds: TypeFlags): TypeFlags { let result: TypeFlags = 0; for (const type of types) { - result |= type.flags; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } } return result & TypeFlags.PropagatingFlags; } @@ -3992,7 +4530,8 @@ namespace ts { const id = getTypeListId(typeArguments); let type = target.instantiations[id]; if (!type) { - const flags = TypeFlags.Reference | (typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0); + const propagatedFlags = typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + const flags = TypeFlags.Reference | propagatedFlags; type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; @@ -4000,58 +4539,9 @@ namespace ts { return type; } - function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode: TypeReferenceNode | ExpressionWithTypeArguments, typeParameterSymbol: Symbol): boolean { - const links = getNodeLinks(typeReferenceNode); - if (links.isIllegalTypeReferenceInConstraint !== undefined) { - return links.isIllegalTypeReferenceInConstraint; - } - - // bubble up to the declaration - let currentNode: Node = typeReferenceNode; - // forEach === exists - while (!forEach(typeParameterSymbol.declarations, d => d.parent === currentNode.parent)) { - 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 === SyntaxKind.TypeParameter; - return links.isIllegalTypeReferenceInConstraint; - } - - function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter: TypeParameterDeclaration): void { - let typeParameterSymbol: Symbol; - function check(n: Node): void { - if (n.kind === SyntaxKind.TypeReference && (n).typeName.kind === SyntaxKind.Identifier) { - const links = getNodeLinks(n); - if (links.isIllegalTypeReferenceInConstraint === undefined) { - const symbol = resolveName(typeParameter, ((n).typeName).text, SymbolFlags.Type, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (symbol && (symbol.flags & SymbolFlags.TypeParameter)) { - // 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 - - // symbol.declaration.parent === typeParameter.parent - // -> 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); - } - } - if (links.isIllegalTypeReferenceInConstraint) { - error(typeParameter, Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); - } - } - forEachChild(n, check); - } - - if (typeParameter.constraint) { - typeParameterSymbol = getSymbolOfNode(typeParameter); - check(typeParameter.constraint); - } - } - // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments, symbol: Symbol): Type { - const type = getDeclaredTypeOfSymbol(symbol); + function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { + const type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); const typeParameters = type.localTypeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { @@ -4073,7 +4563,7 @@ namespace ts { // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. - function getTypeFromTypeAliasReference(node: TypeReferenceNode | ExpressionWithTypeArguments, symbol: Symbol): Type { + function getTypeFromTypeAliasReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { const type = getDeclaredTypeOfSymbol(symbol); const links = getSymbolLinks(symbol); const typeParameters = links.typeParameters; @@ -4094,14 +4584,7 @@ namespace ts { } // 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; - } + function getTypeFromNonGenericTypeReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol): Type { if (node.typeArguments) { error(node, Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); return unknownType; @@ -4109,18 +4592,83 @@ namespace ts { return getDeclaredTypeOfSymbol(symbol); } - function getTypeFromTypeReference(node: TypeReferenceNode | ExpressionWithTypeArguments): Type { + function getTypeReferenceName(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference): LeftHandSideExpression | EntityName { + switch (node.kind) { + case SyntaxKind.TypeReference: + return (node).typeName; + case SyntaxKind.JSDocTypeReference: + return (node).name; + case SyntaxKind.ExpressionWithTypeArguments: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + if (isSupportedExpressionWithTypeArguments(node)) { + return (node).expression; + } + + // fall through; + } + + return undefined; + } + + function resolveTypeReferenceName( + node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, + typeReferenceName: LeftHandSideExpression | EntityName) { + + if (!typeReferenceName) { + return unknownSymbol; + } + + return resolveEntityName(typeReferenceName, SymbolFlags.Type) || unknownSymbol; + } + + function getTypeReferenceType(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference, symbol: Symbol) { + if (symbol === unknownSymbol) { + return unknownType; + } + + if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { + return getTypeFromClassOrInterfaceReference(node, symbol); + } + + if (symbol.flags & SymbolFlags.TypeAlias) { + return getTypeFromTypeAliasReference(node, symbol); + } + + if (symbol.flags & SymbolFlags.Value && node.kind === SyntaxKind.JSDocTypeReference) { + // A JSDocTypeReference may have resolved to a value (as opposed to a type). In + // that case, the type of this reference is just the type of the value we resolved + // to. + return getTypeOfSymbol(symbol); + } + + return getTypeFromNonGenericTypeReference(node, symbol); + } + + function getTypeFromTypeReference(node: TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - // We only support expressions that are simple qualified names. For other expressions this produces undefined. - const typeNameOrExpression = node.kind === SyntaxKind.TypeReference ? (node).typeName : - isSupportedExpressionWithTypeArguments(node) ? (node).expression : - undefined; - const symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, SymbolFlags.Type) || unknownSymbol; - const type = symbol === unknownSymbol ? unknownType : - symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? getTypeFromClassOrInterfaceReference(node, symbol) : - symbol.flags & SymbolFlags.TypeAlias ? getTypeFromTypeAliasReference(node, symbol) : - getTypeFromNonGenericTypeReference(node, symbol); + let symbol: Symbol; + let type: Type; + if (node.kind === SyntaxKind.JSDocTypeReference) { + const typeReferenceName = getTypeReferenceName(node); + symbol = resolveTypeReferenceName(node, typeReferenceName); + type = getTypeReferenceType(node, symbol); + + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + else { + // We only support expressions that are simple qualified names. For other expressions this produces undefined. + const typeNameOrExpression = node.kind === SyntaxKind.TypeReference ? (node).typeName : + isSupportedExpressionWithTypeArguments(node) ? (node).expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, SymbolFlags.Type) || unknownSymbol; + type = symbol === unknownSymbol ? unknownType : + symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? getTypeFromClassOrInterfaceReference(node, symbol) : + symbol.flags & SymbolFlags.TypeAlias ? getTypeFromTypeAliasReference(node, symbol) : + getTypeFromNonGenericTypeReference(node, symbol); + } // 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; @@ -4186,10 +4734,6 @@ namespace ts { return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } - function tryGetGlobalType(name: string, arity = 0): ObjectType { - return getTypeOfGlobalSymbol(getGlobalSymbol(name, SymbolFlags.Type, /*diagnostic*/ undefined), arity); - } - /** * Returns a type that is inside a namespace at the global scope, e.g. * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type @@ -4247,7 +4791,8 @@ namespace ts { } function createNewTupleType(elementTypes: Type[]) { - const type = createObjectType(TypeFlags.Tuple | getPropagatingFlagsOfTypes(elementTypes)); + const propagatedFlags = getPropagatingFlagsOfTypes(elementTypes, /*excludeKinds*/ 0); + const type = createObjectType(TypeFlags.Tuple | propagatedFlags); type.elementTypes = elementTypes; return type; } @@ -4260,10 +4805,21 @@ namespace ts { return links.resolvedType; } - function addTypeToSet(typeSet: Type[], type: Type, typeSetKind: TypeFlags) { + interface TypeSet extends Array { + containsAny?: boolean; + containsUndefined?: boolean; + containsNull?: boolean; + } + + function addTypeToSet(typeSet: TypeSet, type: Type, typeSetKind: TypeFlags) { if (type.flags & typeSetKind) { addTypesToSet(typeSet, (type).types, typeSetKind); } + else if (type.flags & (TypeFlags.Any | TypeFlags.Undefined | TypeFlags.Null)) { + if (type.flags & TypeFlags.Any) typeSet.containsAny = true; + if (type.flags & TypeFlags.Undefined) typeSet.containsUndefined = true; + if (type.flags & TypeFlags.Null) typeSet.containsNull = true; + } else if (!contains(typeSet, type)) { typeSet.push(type); } @@ -4271,7 +4827,7 @@ namespace ts { // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. - function addTypesToSet(typeSet: Type[], types: Type[], typeSetKind: TypeFlags) { + function addTypesToSet(typeSet: TypeSet, types: Type[], typeSetKind: TypeFlags) { for (const type of types) { addTypeToSet(typeSet, type, typeSetKind); } @@ -4296,25 +4852,6 @@ namespace ts { } } - function containsTypeAny(types: Type[]): boolean { - for (const type of types) { - if (isTypeAny(type)) { - return true; - } - } - return false; - } - - function removeAllButLast(types: Type[], typeToRemove: Type) { - let i = types.length; - while (i > 0 && types.length > 1) { - i--; - if (types[i] === typeToRemove) { - types.splice(i, 1); - } - } - } - // We reduce the constituent type set to only include types that aren't subtypes of other types, unless // the noSubtypeReduction flag is specified, in which case we perform a simple deduplication based on // object identity. Subtype reduction is possible only when union types are known not to circularly @@ -4324,27 +4861,31 @@ namespace ts { // a named type that circularly references itself. function getUnionType(types: Type[], noSubtypeReduction?: boolean): Type { if (types.length === 0) { - return emptyObjectType; + return emptyUnionType; } - const typeSet: Type[] = []; + const typeSet = [] as TypeSet; addTypesToSet(typeSet, types, TypeFlags.Union); - if (containsTypeAny(typeSet)) { + if (typeSet.containsAny) { return anyType; } - if (noSubtypeReduction) { - removeAllButLast(typeSet, undefinedType); - removeAllButLast(typeSet, nullType); + if (strictNullChecks) { + if (typeSet.containsNull) typeSet.push(nullType); + if (typeSet.containsUndefined) typeSet.push(undefinedType); } - else { + if (!noSubtypeReduction) { removeSubtypes(typeSet); } - if (typeSet.length === 1) { + if (typeSet.length === 0) { + return typeSet.containsNull ? nullType : undefinedType; + } + else if (typeSet.length === 1) { return typeSet[0]; } const id = getTypeListId(typeSet); let type = unionTypes[id]; if (!type) { - type = unionTypes[id] = createObjectType(TypeFlags.Union | getPropagatingFlagsOfTypes(typeSet)); + const propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ TypeFlags.Nullable); + type = unionTypes[id] = createObjectType(TypeFlags.Union | propagatedFlags); type.types = typeSet; } return type; @@ -4367,18 +4908,23 @@ namespace ts { if (types.length === 0) { return emptyObjectType; } - const typeSet: Type[] = []; + const typeSet = [] as TypeSet; addTypesToSet(typeSet, types, TypeFlags.Intersection); - if (containsTypeAny(typeSet)) { + if (typeSet.containsAny) { return anyType; } + if (strictNullChecks) { + if (typeSet.containsNull) typeSet.push(nullType); + if (typeSet.containsUndefined) typeSet.push(undefinedType); + } if (typeSet.length === 1) { return typeSet[0]; } const id = getTypeListId(typeSet); let type = intersectionTypes[id]; if (!type) { - type = intersectionTypes[id] = createObjectType(TypeFlags.Intersection | getPropagatingFlagsOfTypes(typeSet)); + const propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ TypeFlags.Nullable); + type = intersectionTypes[id] = createObjectType(TypeFlags.Intersection | propagatedFlags); type.types = typeSet; } return type; @@ -4401,20 +4947,38 @@ namespace ts { return links.resolvedType; } - function getStringLiteralType(node: StringLiteral): StringLiteralType { - if (hasProperty(stringLiteralTypes, node.text)) { - return stringLiteralTypes[node.text]; + function getStringLiteralTypeForText(text: string): StringLiteralType { + if (hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; } - const type = stringLiteralTypes[node.text] = createType(TypeFlags.StringLiteral); - type.text = getTextOfNode(node); + const type = stringLiteralTypes[text] = createType(TypeFlags.StringLiteral); + type.text = text; return type; } - function getTypeFromStringLiteral(node: StringLiteral): Type { + function getTypeFromStringLiteralTypeNode(node: StringLiteralTypeNode): Type { const links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralType(node); + links.resolvedType = getStringLiteralTypeForText(node.text); + } + return links.resolvedType; + } + + function getTypeFromJSDocVariadicType(node: JSDocVariadicType): Type { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + + function getTypeFromJSDocTupleType(node: JSDocTupleType): Type { + const links = getNodeLinks(node); + if (!links.resolvedType) { + const types = map(node.types, getTypeFromTypeNode); + links.resolvedType = createTupleType(types); } return links.resolvedType; } @@ -4443,6 +5007,8 @@ namespace ts { function getTypeFromTypeNode(node: TypeNode): Type { switch (node.kind) { case SyntaxKind.AnyKeyword: + case SyntaxKind.JSDocAllType: + case SyntaxKind.JSDocUnknownType: return anyType; case SyntaxKind.StringKeyword: return stringType; @@ -4454,11 +5020,16 @@ namespace ts { return esSymbolType; case SyntaxKind.VoidKeyword: return voidType; - case SyntaxKind.ThisKeyword: + case SyntaxKind.UndefinedKeyword: + return undefinedType; + case SyntaxKind.NullKeyword: + return nullType; + case SyntaxKind.ThisType: return getTypeFromThisTypeNode(node); - case SyntaxKind.StringLiteral: - return getTypeFromStringLiteral(node); + case SyntaxKind.StringLiteralType: + return getTypeFromStringLiteralTypeNode(node); case SyntaxKind.TypeReference: + case SyntaxKind.JSDocTypeReference: return getTypeFromTypeReference(node); case SyntaxKind.TypePredicate: return booleanType; @@ -4467,18 +5038,27 @@ namespace ts { case SyntaxKind.TypeQuery: return getTypeFromTypeQueryNode(node); case SyntaxKind.ArrayType: + case SyntaxKind.JSDocArrayType: return getTypeFromArrayTypeNode(node); case SyntaxKind.TupleType: return getTypeFromTupleTypeNode(node); case SyntaxKind.UnionType: + case SyntaxKind.JSDocUnionType: return getTypeFromUnionTypeNode(node); case SyntaxKind.IntersectionType: return getTypeFromIntersectionTypeNode(node); case SyntaxKind.ParenthesizedType: - return getTypeFromTypeNode((node).type); + case SyntaxKind.JSDocNullableType: + case SyntaxKind.JSDocNonNullableType: + case SyntaxKind.JSDocConstructorType: + case SyntaxKind.JSDocThisType: + case SyntaxKind.JSDocOptionalType: + return getTypeFromTypeNode((node).type); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.TypeLiteral: + case SyntaxKind.JSDocFunctionType: + case SyntaxKind.JSDocRecordType: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode @@ -4486,6 +5066,10 @@ namespace ts { case SyntaxKind.QualifiedName: const symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); + case SyntaxKind.JSDocTupleType: + return getTypeFromJSDocTupleType(node); + case SyntaxKind.JSDocVariadicType: + return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -4510,57 +5094,48 @@ namespace ts { return t => t === source1 ? target1 : t === source2 ? target2 : t; } - function createTypeMapper(sources: Type[], targets: Type[]): TypeMapper { - switch (sources.length) { - case 1: return createUnaryTypeMapper(sources[0], targets[0]); - case 2: return createBinaryTypeMapper(sources[0], targets[0], sources[1], targets[1]); - } + function createArrayTypeMapper(sources: Type[], targets: Type[]): TypeMapper { return t => { for (let i = 0; i < sources.length; i++) { if (t === sources[i]) { - return targets[i]; + return targets ? targets[i] : anyType; } } return t; }; } - function createUnaryTypeEraser(source: Type): TypeMapper { - return t => t === source ? anyType : t; - } - - function createBinaryTypeEraser(source1: Type, source2: Type): TypeMapper { - return t => t === source1 || t === source2 ? anyType : t; + function createTypeMapper(sources: Type[], targets: Type[]): TypeMapper { + const count = sources.length; + const mapper: TypeMapper = + count == 1 ? createUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + createArrayTypeMapper(sources, targets); + mapper.mappedTypes = sources; + return mapper; } function createTypeEraser(sources: Type[]): TypeMapper { - switch (sources.length) { - case 1: return createUnaryTypeEraser(sources[0]); - case 2: return createBinaryTypeEraser(sources[0], sources[1]); - } - return t => { - for (const source of sources) { - if (t === source) { - return anyType; - } - } - return t; - }; + return createTypeMapper(sources, undefined); } - function createInferenceMapper(context: InferenceContext): TypeMapper { - const mapper: TypeMapper = t => { - for (let i = 0; i < context.typeParameters.length; i++) { - if (t === context.typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); + function getInferenceMapper(context: InferenceContext): TypeMapper { + if (!context.mapper) { + const mapper: TypeMapper = t => { + const typeParameters = context.typeParameters; + for (let i = 0; i < typeParameters.length; i++) { + if (t === typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } } - } - return t; - }; - - mapper.context = context; - return mapper; + return t; + }; + mapper.mappedTypes = context.typeParameters; + mapper.context = context; + context.mapper = mapper; + } + return context.mapper; } function identityMapper(type: Type): Type { @@ -4568,35 +5143,50 @@ namespace ts { } function combineTypeMappers(mapper1: TypeMapper, mapper2: TypeMapper): TypeMapper { - return t => instantiateType(mapper1(t), mapper2); + const mapper: TypeMapper = t => instantiateType(mapper1(t), mapper2); + mapper.mappedTypes = mapper1.mappedTypes; + return mapper; } - function instantiateTypeParameter(typeParameter: TypeParameter, mapper: TypeMapper): TypeParameter { + function cloneTypeParameter(typeParameter: TypeParameter): TypeParameter { const result = createType(TypeFlags.TypeParameter); result.symbol = typeParameter.symbol; - if (typeParameter.constraint) { - result.constraint = instantiateType(typeParameter.constraint, mapper); + result.target = typeParameter; + return result; + } + + function cloneTypePredicate(predicate: TypePredicate, mapper: TypeMapper): ThisTypePredicate | IdentifierTypePredicate { + if (isIdentifierTypePredicate(predicate)) { + return { + kind: TypePredicateKind.Identifier, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + } as IdentifierTypePredicate; } else { - result.target = typeParameter; - result.mapper = mapper; + return { + kind: TypePredicateKind.This, + type: instantiateType(predicate.type, mapper) + } as ThisTypePredicate; } - return result; } 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); + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (const tp of freshTypeParameters) { + tp.mapper = mapper; + } } if (signature.typePredicate) { - freshTypePredicate = { - parameterName: signature.typePredicate.parameterName, - parameterIndex: signature.typePredicate.parameterIndex, - type: instantiateType(signature.typePredicate.type, mapper) - }; + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } const result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), @@ -4650,13 +5240,70 @@ namespace ts { return result; } + function isSymbolInScopeOfMappedTypeParameter(symbol: Symbol, mapper: TypeMapper) { + const mappedTypes = mapper.mappedTypes; + // Starting with the parent of the symbol's declaration, check if the mapper maps any of + // the type parameters introduced by enclosing declarations. We just pick the first + // declaration since multiple declarations will all have the same parent anyway. + let node = symbol.declarations[0].parent; + while (node) { + switch (node.kind) { + case SyntaxKind.FunctionType: + case SyntaxKind.ConstructorType: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.Constructor: + case SyntaxKind.CallSignature: + case SyntaxKind.ConstructSignature: + case SyntaxKind.IndexSignature: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.TypeAliasDeclaration: + const declaration = node; + if (declaration.typeParameters) { + for (const d of declaration.typeParameters) { + if (contains(mappedTypes, getDeclaredTypeOfTypeParameter(d.symbol))) { + return true; + } + } + } + if (isClassLike(node) || node.kind === SyntaxKind.InterfaceDeclaration) { + const thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + if (thisType && contains(mappedTypes, thisType)) { + return true; + } + } + break; + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.SourceFile: + return false; + } + node = node.parent; + } + return false; + } + function instantiateType(type: Type, mapper: TypeMapper): Type { if (type && mapper !== identityMapper) { if (type.flags & TypeFlags.TypeParameter) { return mapper(type); } if (type.flags & TypeFlags.Anonymous) { - return type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) ? + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. We skip instantiation + // if none of the type parameters that are in scope in the type's declaration are mapped by + // the given mapper, however we can only do that analysis if the type isn't itself an + // instantiation. + return type.symbol && + type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && + (type.flags & TypeFlags.Instantiated || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? instantiateAnonymousType(type, mapper) : type; } if (type.flags & TypeFlags.Reference) { @@ -4675,6 +5322,10 @@ namespace ts { return type; } + function instantiateIndexInfo(info: IndexInfo, mapper: TypeMapper): IndexInfo { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElement): boolean { @@ -4730,10 +5381,14 @@ namespace ts { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); } - function compareTypes(source: Type, target: Type): Ternary { + function compareTypesIdentical(source: Type, target: Type): Ternary { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? Ternary.True : Ternary.False; } + function compareTypesAssignable(source: Type, target: Type): Ternary { + return checkTypeRelatedTo(source, target, assignableRelation, /*errorNode*/ undefined) ? Ternary.True : Ternary.False; + } + function isTypeSubtypeOf(source: Type, target: Type): boolean { return checkTypeSubtypeOf(source, target, /*errorNode*/ undefined); } @@ -4766,17 +5421,164 @@ namespace ts { return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } - function isSignatureAssignableTo(source: Signature, target: Signature): boolean { - const sourceType = getOrCreateTypeFromSignature(source); - const targetType = getOrCreateTypeFromSignature(target); - return checkTypeRelatedTo(sourceType, targetType, assignableRelation, /*errorNode*/ undefined); + function isSignatureAssignableTo(source: Signature, + target: Signature, + ignoreReturnTypes: boolean): boolean { + return compareSignaturesRelated(source, target, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== Ternary.False; + } + + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source: Signature, + target: Signature, + ignoreReturnTypes: boolean, + reportErrors: boolean, + errorReporter: (d: DiagnosticMessage, arg0?: string, arg1?: string) => void, + compareTypes: (s: Type, t: Type, reportErrors?: boolean) => Ternary): Ternary { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return Ternary.True; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return Ternary.False; + } + + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + + let result = Ternary.True; + + const sourceMax = getNumNonRestParameters(source); + const targetMax = getNumNonRestParameters(target); + const checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + const sourceParams = source.parameters; + const targetParams = target.parameters; + for (let i = 0; i < checkCount; i++) { + const s = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); + const t = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); + const related = compareTypes(s, t, /*reportErrors*/ false) || compareTypes(t, s, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(Diagnostics.Types_of_parameters_0_and_1_are_incompatible, + sourceParams[i < sourceMax ? i : sourceMax].name, + targetParams[i < targetMax ? i : targetMax].name); + } + return Ternary.False; + } + result &= related; + } + + if (!ignoreReturnTypes) { + const targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + const sourceReturnType = getReturnTypeOfSignature(source); + + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return Ternary.False; + } + } + else { + result &= compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + + } + + return result; + } + + function compareTypePredicateRelatedTo(source: TypePredicate, + target: TypePredicate, + reportErrors: boolean, + errorReporter: (d: DiagnosticMessage, arg0?: string, arg1?: string) => void, + compareTypes: (s: Type, t: Type, reportErrors?: boolean) => Ternary): Ternary { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return Ternary.False; + } + + if (source.kind === TypePredicateKind.Identifier) { + const sourceIdentifierPredicate = source as IdentifierTypePredicate; + const targetIdentifierPredicate = target as IdentifierTypePredicate; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return Ternary.False; + } + } + + const related = compareTypes(source.type, target.type, reportErrors); + if (related === Ternary.False && reportErrors) { + errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + + function isImplementationCompatibleWithOverload(implementation: Signature, overload: Signature): boolean { + const erasedSource = getErasedSignature(implementation); + const erasedTarget = getErasedSignature(overload); + + // First see if the return types are compatible in either direction. + const sourceReturnType = getReturnTypeOfSignature(erasedSource); + const targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, /*errorNode*/ undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, /*errorNode*/ undefined)) { + + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + + return false; + } + + function getNumNonRestParameters(signature: Signature) { + const numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + + function getNumParametersToCheckForSignatureRelatability(source: Signature, sourceNonRestParamCount: number, target: Signature, targetNonRestParamCount: number) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + // If both have rest parameters, get the max and add 1 to + // compensate for the rest parameter. + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + // Return the count for whichever signature doesn't have rest parameters. + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). * @param source The left-hand-side of the relation. * @param target The right-hand-side of the relation. - * @param relation The relation considered. One of 'identityRelation', 'assignableRelation', 'subTypeRelation', or 'comparableRelation'. + * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. * Used as both to determine which checks are performed and as a cache of previously computed results. * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. @@ -4797,26 +5599,14 @@ namespace ts { let expandingFlags: number; let depth = 0; let overflow = false; - let elaborateErrors = false; Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - const isAssignableOrComparableRelation = relation === assignableRelation || relation === comparableRelation; - const result = isRelatedTo(source, target, errorNode !== undefined, headMessage); - + const result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (overflow) { error(errorNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { - // If we already computed this relation, but in a context where we didn't want to report errors (e.g. overload resolution), - // then we'll only have a top-level error (e.g. 'Class X does not implement interface Y') without any details. If this happened, - // request a recompuation to get a complete error message. This will be skipped if we've already done this computation in a context - // where errors were being reported. - if (errorInfo.next === undefined) { - errorInfo = undefined; - elaborateErrors = true; - isRelatedTo(source, target, errorNode !== undefined, headMessage); - } if (containingMessageChain) { errorInfo = concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } @@ -4826,6 +5616,7 @@ namespace ts { return result !== Ternary.False; function reportError(message: DiagnosticMessage, arg0?: string, arg1?: string, arg2?: string): void { + Debug.assert(!!errorNode); errorInfo = chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } @@ -4859,15 +5650,29 @@ namespace ts { } if (isTypeAny(target)) return Ternary.True; - if (source === undefinedType) return Ternary.True; - if (source === nullType && target !== undefinedType) return Ternary.True; + if (source.flags & TypeFlags.Undefined) { + if (!strictNullChecks || target.flags & (TypeFlags.Undefined | TypeFlags.Void) || source === emptyArrayElementType) return Ternary.True; + } + if (source.flags & TypeFlags.Null) { + if (!strictNullChecks || target.flags & TypeFlags.Null) return Ternary.True; + } if (source.flags & TypeFlags.Enum && target === numberType) return Ternary.True; + if (source.flags & TypeFlags.Enum && target.flags & TypeFlags.Enum) { + if (result = enumRelatedTo(source, target, reportErrors)) { + return result; + } + } if (source.flags & TypeFlags.StringLiteral && target === stringType) return Ternary.True; - if (isAssignableOrComparableRelation) { + + if (relation === assignableRelation || relation === comparableRelation) { if (isTypeAny(source)) return Ternary.True; if (source === numberType && target.flags & TypeFlags.Enum) return Ternary.True; } + if (source.flags & TypeFlags.Boolean && target.flags & TypeFlags.Boolean) { + return Ternary.True; + } + if (source.flags & TypeFlags.FreshObjectLiteral) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -4911,14 +5716,25 @@ namespace ts { // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or // A & B = (A & B) | (C & D). if (source.flags & TypeFlags.Intersection) { - // If target is a union type then the check following this one will report errors, - // so we'll suppress any errors we could run into here. - if (result = someTypeRelatedToType(source as IntersectionType, target, reportErrors && !(target.flags & TypeFlags.Union))) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) { return result; } } if (target.flags & TypeFlags.Union) { - if (result = typeRelatedToSomeType(source, target as UnionType, reportErrors)) { + if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & TypeFlags.Primitive))) { return result; } } @@ -4945,14 +5761,14 @@ namespace ts { } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - const apparentType = getApparentType(source); + const apparentSource = getApparentType(source); // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (apparentType.flags & (TypeFlags.ObjectType | TypeFlags.Intersection) && target.flags & TypeFlags.ObjectType) { + if (apparentSource.flags & (TypeFlags.ObjectType | TypeFlags.Intersection) && target.flags & TypeFlags.ObjectType) { // Report structural errors only if we haven't reported any errors yet - const reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; - if (result = objectTypeRelatedTo(apparentType, source, target, reportStructuralErrors)) { + const reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & TypeFlags.Primitive); + if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; } @@ -4976,9 +5792,6 @@ namespace ts { } return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } - if (source.flags & TypeFlags.TypeParameter && target.flags & TypeFlags.TypeParameter) { - return typeParameterIdenticalTo(source, target); - } if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union || source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) { if (result = eachTypeRelatedToSomeType(source, target, /*reportErrors*/ false)) { @@ -4997,8 +5810,9 @@ namespace ts { function isKnownProperty(type: Type, name: string): boolean { if (type.flags & TypeFlags.ObjectType) { const resolved = resolveStructuredTypeMembers(type); - if (isAssignableOrComparableRelation && (type === globalObjectType || resolved.properties.length === 0) || - resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) { + if ((relation === assignableRelation || relation === comparableRelation) && + (type === globalObjectType || resolved.properties.length === 0) || + resolved.stringIndexInfo || resolved.numberIndexInfo || getPropertyOfType(type, name)) { return true; } } @@ -5013,13 +5827,14 @@ namespace ts { } function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean { - if (someConstituentTypeHasKind(target, TypeFlags.ObjectType)) { + if (!(target.flags & TypeFlags.ObjectLiteralPatternWithComputedProperties) && maybeTypeOfKind(target, TypeFlags.ObjectType)) { for (const prop of getPropertiesOfObjectType(source)) { if (!isKnownProperty(target, prop.name)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. + Debug.assert(!!errorNode); errorNode = prop.valueDeclaration; reportError(Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); @@ -5032,10 +5847,10 @@ namespace ts { } function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType, reportErrors: boolean): Ternary { - let result = Ternary.True; + let result = Ternary.True; const sourceTypes = source.types; for (const sourceType of sourceTypes) { - const related = typeRelatedToSomeType(sourceType, target, false); + const related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); if (!related) { return Ternary.False; } @@ -5046,7 +5861,19 @@ namespace ts { function typeRelatedToSomeType(source: Type, target: UnionOrIntersectionType, reportErrors: boolean): Ternary { const targetTypes = target.types; - for (let i = 0, len = targetTypes.length; i < len; i++) { + let len = targetTypes.length; + // The null and undefined types are guaranteed to be at the end of the constituent type list. In order + // to produce the best possible errors we first check the nullable types, such that the last type we + // check and report errors from is a non-nullable type if one is present. + while (len >= 2 && targetTypes[len - 1].flags & TypeFlags.Nullable) { + const related = isRelatedTo(source, targetTypes[len - 1], /*reportErrors*/ false); + if (related) { + return related; + } + len--; + } + // Now check the non-nullable types and report errors on the last one. + for (let i = 0; i < len; i++) { const related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { return related; @@ -5070,7 +5897,19 @@ namespace ts { function someTypeRelatedToType(source: UnionOrIntersectionType, target: Type, reportErrors: boolean): Ternary { const sourceTypes = source.types; - for (let i = 0, len = sourceTypes.length; i < len; i++) { + let len = sourceTypes.length; + // The null and undefined types are guaranteed to be at the end of the constituent type list. In order + // to produce the best possible errors we first check the nullable types, such that the last type we + // check and report errors from is a non-nullable type if one is present. + while (len >= 2 && sourceTypes[len - 1].flags & TypeFlags.Nullable) { + const related = isRelatedTo(sourceTypes[len - 1], target, /*reportErrors*/ false); + if (related) { + return related; + } + len--; + } + // Now check the non-nullable types and report errors on the last one. + for (let i = 0; i < len; i++) { const related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { return related; @@ -5098,8 +5937,9 @@ namespace ts { if (sources.length !== targets.length && relation === identityRelation) { return Ternary.False; } + const length = sources.length <= targets.length ? sources.length : targets.length; let result = Ternary.True; - for (let i = 0; i < targets.length; i++) { + for (let i = 0; i < length; i++) { const related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return Ternary.False; @@ -5109,35 +5949,24 @@ namespace ts { return result; } - function typeParameterIdenticalTo(source: TypeParameter, target: TypeParameter): Ternary { - if (source.symbol.name !== target.symbol.name) { - return Ternary.False; - } - // covers case when both type parameters does not have constraint (both equal to noConstraintType) - if (source.constraint === target.constraint) { - return Ternary.True; - } - if (source.constraint === noConstraintType || target.constraint === noConstraintType) { - return Ternary.False; - } - return isIdenticalTo(source.constraint, target.constraint); - } - // Determine if two object types are related by structure. First, check if the result is already available in the global cache. // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function objectTypeRelatedTo(apparentSource: Type, originalSource: Type, target: Type, reportErrors: boolean): Ternary { + function objectTypeRelatedTo(source: Type, originalSource: Type, target: Type, reportErrors: boolean): Ternary { if (overflow) { return Ternary.False; } - const id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + const id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; const related = relation[id]; if (related !== undefined) { - // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate - // errors, we can use the cached value. Otherwise, recompute the relation - if (!elaborateErrors || (related === RelationComparisonResult.FailedAndReported)) { + if (reportErrors && related === RelationComparisonResult.Failed) { + // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported + // failure and continue computing the relation such that errors get reported. + relation[id] = RelationComparisonResult.FailedAndReported; + } + else { return related === RelationComparisonResult.Succeeded ? Ternary.True : Ternary.False; } } @@ -5159,28 +5988,28 @@ namespace ts { maybeStack = []; expandingFlags = 0; } - sourceStack[depth] = apparentSource; + sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; maybeStack[depth][id] = RelationComparisonResult.Succeeded; depth++; const saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) expandingFlags |= 1; + 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; } else { - result = propertiesRelatedTo(apparentSource, target, reportErrors); + result = propertiesRelatedTo(source, target, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, SignatureKind.Call, reportErrors); + result &= signaturesRelatedTo(source, target, SignatureKind.Call, reportErrors); if (result) { - result &= signaturesRelatedTo(apparentSource, target, SignatureKind.Construct, reportErrors); + result &= signaturesRelatedTo(source, target, SignatureKind.Construct, reportErrors); if (result) { - result &= stringIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= indexTypesRelatedTo(source, originalSource, target, IndexKind.String, reportErrors); if (result) { - result &= numberIndexTypesRelatedTo(apparentSource, originalSource, target, reportErrors); + result &= indexTypesRelatedTo(source, originalSource, target, IndexKind.Number, reportErrors); } } } @@ -5241,8 +6070,8 @@ namespace ts { } else if (targetPropFlags & NodeFlags.Protected) { const sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & SymbolFlags.Class; - const sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; - const targetClass = getDeclaredTypeOfSymbol(targetProp.parent); + const sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; + const targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { if (reportErrors) { reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, @@ -5317,181 +6146,56 @@ namespace ts { if (target === anyFunctionType || source === anyFunctionType) { return Ternary.True; } + const sourceSignatures = getSignaturesOfType(source, kind); const targetSignatures = getSignaturesOfType(target, kind); + if (kind === SignatureKind.Construct && sourceSignatures.length && targetSignatures.length) { + if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return Ternary.False; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return Ternary.False; + } + } + let result = Ternary.True; const saveErrorInfo = errorInfo; - - - if (kind === SignatureKind.Construct) { - // Only want to compare the construct signatures for abstractness guarantees. - - // Because the "abstractness" of a class is the same across all construct signatures - // (internally we are checking the corresponding declaration), it is enough to perform - // the check and report an error once over all pairs of source and target construct signatures. - // - // sourceSig and targetSig are (possibly) undefined. - // - // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. - const sourceSig = sourceSignatures[0]; - const targetSig = targetSignatures[0]; - - result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); - if (result !== Ternary.True) { - return result; - } - } - outer: for (const t of targetSignatures) { - if (!t.hasStringLiterals || target.flags & TypeFlags.FromSignature) { - let localErrors = reportErrors; - const checkedAbstractAssignability = false; - for (const s of sourceSignatures) { - if (!s.hasStringLiterals || source.flags & TypeFlags.FromSignature) { - const related = signatureRelatedTo(s, t, localErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; - } - // Only report errors from the first failure - localErrors = false; - } + // Only elaborate errors from the first failure + let shouldElaborateErrors = reportErrors; + for (const s of sourceSignatures) { + const related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; } - return Ternary.False; + shouldElaborateErrors = false; } + + if (shouldElaborateErrors) { + reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1, + typeToString(source), + signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return Ternary.False; } return result; - - function abstractSignatureRelatedTo(source: Type, sourceSig: Signature, target: Type, targetSig: Signature) { - if (sourceSig && targetSig) { - - const sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - const targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); - - if (!sourceDecl) { - // If the source object isn't itself a class declaration, it can be freely assigned, regardless - // of whether the constructed object is abstract or not. - return Ternary.True; - } - - const sourceErasedSignature = getErasedSignature(sourceSig); - const targetErasedSignature = getErasedSignature(targetSig); - - const sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - const targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - - const sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - const targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - const sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & NodeFlags.Abstract; - const targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & NodeFlags.Abstract; - - if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { - // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. - if (reportErrors) { - reportError(Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return Ternary.False; - } - } - return Ternary.True; - } } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ function signatureRelatedTo(source: Signature, target: Signature, reportErrors: boolean): Ternary { - if (source === target) { - return Ternary.True; - } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return Ternary.False; - } - let sourceMax = source.parameters.length; - let targetMax = target.parameters.length; - let checkCount: number; - if (source.hasRestParameter && target.hasRestParameter) { - checkCount = sourceMax > targetMax ? sourceMax : targetMax; - sourceMax--; - targetMax--; - } - else if (source.hasRestParameter) { - sourceMax--; - checkCount = targetMax; - } - else if (target.hasRestParameter) { - targetMax--; - checkCount = sourceMax; - } - else { - checkCount = sourceMax < targetMax ? sourceMax : targetMax; - } - // Spec 1.0 Section 3.8.3 & 3.8.4: - // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N - source = getErasedSignature(source); - target = getErasedSignature(target); - let result = Ternary.True; - for (let i = 0; i < checkCount; i++) { - const s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - const t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); - const saveErrorInfo = errorInfo; - let related = isRelatedTo(s, t, reportErrors); - if (!related) { - related = isRelatedTo(t, s, false); - if (!related) { - if (reportErrors) { - reportError(Diagnostics.Types_of_parameters_0_and_1_are_incompatible, - source.parameters[i < sourceMax ? i : sourceMax].name, - target.parameters[i < targetMax ? i : targetMax].name); - } - return Ternary.False; - } - errorInfo = saveErrorInfo; - } - result &= related; - } - - if (source.typePredicate && target.typePredicate) { - const hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; - let hasDifferentTypes: boolean; - if (hasDifferentParameterIndex || - (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { - - if (reportErrors) { - const sourceParamText = source.typePredicate.parameterName; - const targetParamText = target.typePredicate.parameterName; - const sourceTypeText = typeToString(source.typePredicate.type); - const 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; - } - - const targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) return result; - const sourceReturnType = getReturnTypeOfSignature(source); - - return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); + return compareSignaturesRelated(source, target, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source: Type, target: Type, kind: SignatureKind): Ternary { @@ -5501,8 +6205,8 @@ namespace ts { return Ternary.False; } let result = Ternary.True; - for (let i = 0, len = sourceSignatures.length; i < len; ++i) { - const related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + for (let i = 0, len = sourceSignatures.length; i < len; i++) { + const related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); if (!related) { return Ternary.False; } @@ -5511,85 +6215,142 @@ namespace ts { return result; } - function stringIndexTypesRelatedTo(source: Type, originalSource: Type, target: Type, reportErrors: boolean): Ternary { - if (relation === identityRelation) { - return indexTypesIdenticalTo(IndexKind.String, source, target); - } - const targetType = getIndexTypeOfType(target, IndexKind.String); - if (targetType) { - if ((targetType.flags & TypeFlags.Any) && !(originalSource.flags & TypeFlags.Primitive)) { - // non-primitive assignment to any is always allowed, eg - // `var x: { [index: string]: any } = { property: 12 };` - return Ternary.True; - } - const sourceType = getIndexTypeOfType(source, IndexKind.String); - if (!sourceType) { - if (reportErrors) { - reportError(Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + function eachPropertyRelatedTo(source: Type, target: Type, kind: IndexKind, reportErrors: boolean): Ternary { + let result = Ternary.True; + for (const prop of getPropertiesOfObjectType(source)) { + if (kind === IndexKind.String || isNumericLiteralName(prop.name)) { + const related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return Ternary.False; } - return Ternary.False; + result &= related; } - const related = isRelatedTo(sourceType, targetType, reportErrors); - if (!related) { - if (reportErrors) { - reportError(Diagnostics.Index_signatures_are_incompatible); - } - return Ternary.False; - } - return related; } - return Ternary.True; + return result; } - function numberIndexTypesRelatedTo(source: Type, originalSource: Type, target: Type, reportErrors: boolean): Ternary { - if (relation === identityRelation) { - return indexTypesIdenticalTo(IndexKind.Number, source, target); + function indexInfoRelatedTo(sourceInfo: IndexInfo, targetInfo: IndexInfo, reportErrors: boolean) { + const related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(Diagnostics.Index_signatures_are_incompatible); } - const targetType = getIndexTypeOfType(target, IndexKind.Number); - if (targetType) { - if ((targetType.flags & TypeFlags.Any) && !(originalSource.flags & TypeFlags.Primitive)) { - // non-primitive assignment to any is always allowed, eg - // `var x: { [index: number]: any } = { property: 12 };` - return Ternary.True; - } - const sourceStringType = getIndexTypeOfType(source, IndexKind.String); - const sourceNumberType = getIndexTypeOfType(source, IndexKind.Number); - if (!(sourceStringType || sourceNumberType)) { - if (reportErrors) { - reportError(Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); - } - return Ternary.False; - } - let related: Ternary; - if (sourceStringType && sourceNumberType) { - // If we know for sure we're testing both string and numeric index types then only report errors from the second one - related = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors); - } - else { - related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); - } - if (!related) { - if (reportErrors) { - reportError(Diagnostics.Index_signatures_are_incompatible); - } - return Ternary.False; - } - return related; - } - return Ternary.True; + return related; } - function indexTypesIdenticalTo(indexKind: IndexKind, source: Type, target: Type): Ternary { - const targetType = getIndexTypeOfType(target, indexKind); - const sourceType = getIndexTypeOfType(source, indexKind); - if (!sourceType && !targetType) { + function indexTypesRelatedTo(source: Type, originalSource: Type, target: Type, kind: IndexKind, reportErrors: boolean) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + const targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || ((targetInfo.type.flags & TypeFlags.Any) && !(originalSource.flags & TypeFlags.Primitive))) { + // Index signature of type any permits assignment from everything but primitives return Ternary.True; } - if (sourceType && targetType) { - return isRelatedTo(sourceType, targetType); + const sourceInfo = getIndexInfoOfType(source, kind) || + kind === IndexKind.Number && getIndexInfoOfType(source, IndexKind.String); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isObjectLiteralType(source)) { + let related = Ternary.True; + if (kind === IndexKind.String) { + const sourceNumberInfo = getIndexInfoOfType(source, IndexKind.Number); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } return Ternary.False; } + + function indexTypesIdenticalTo(source: Type, target: Type, indexKind: IndexKind): Ternary { + const targetInfo = getIndexInfoOfType(target, indexKind); + const sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return Ternary.True; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return Ternary.False; + } + + function enumRelatedTo(source: Type, target: Type, reportErrors?: boolean) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & SymbolFlags.ConstEnum || + target.symbol.flags & SymbolFlags.ConstEnum) { + return Ternary.False; + } + const targetEnumType = getTypeOfSymbol(target.symbol); + for (const property of getPropertiesOfType(getTypeOfSymbol(source.symbol))) { + if (property.flags & SymbolFlags.EnumMember) { + const targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & SymbolFlags.EnumMember)) { + if (reportErrors) { + reportError(Diagnostics.Property_0_is_missing_in_type_1, + property.name, + typeToString(target, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType)); + } + return Ternary.False; + } + } + } + return Ternary.True; + } + + function constructorVisibilitiesAreCompatible(sourceSignature: Signature, targetSignature: Signature, reportErrors: boolean) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + + const sourceAccessibility = sourceSignature.declaration.flags & (NodeFlags.Private | NodeFlags.Protected); + const targetAccessibility = targetSignature.declaration.flags & (NodeFlags.Private | NodeFlags.Protected); + + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === NodeFlags.Private) { + return true; + } + + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === NodeFlags.Protected && sourceAccessibility !== NodeFlags.Private) { + return true; + } + + // Only a public signature is assignable to public signature. + if (targetAccessibility !== NodeFlags.Protected && !sourceAccessibility) { + return true; + } + + if (reportErrors) { + reportError(Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + + return false; + } + } + + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type: Type) { + if (type.flags & TypeFlags.Anonymous) { + const symbol = type.symbol; + if (symbol && symbol.flags & SymbolFlags.Class) { + const declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && declaration.flags & NodeFlags.Abstract) { + return true; + } + } + } + return false; } // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case @@ -5614,7 +6375,7 @@ namespace ts { } function isPropertyIdenticalTo(sourceProp: Symbol, targetProp: Symbol): boolean { - return compareProperties(sourceProp, targetProp, compareTypes) !== Ternary.False; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== Ternary.False; } function compareProperties(sourceProp: Symbol, targetProp: Symbol, compareTypes: (source: Type, target: Type) => Ternary): Ternary { @@ -5639,46 +6400,59 @@ namespace ts { return Ternary.False; } } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return Ternary.False; + } return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } - function compareSignatures(source: Signature, target: Signature, partialMatch: boolean, ignoreReturnTypes: boolean, compareTypes: (s: Type, t: Type) => Ternary): Ternary { + function isMatchingSignature(source: Signature, target: Signature, partialMatch: boolean) { + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters and no more overall parameters than the source signature (where a signature with a rest + // parameter is always considered to have more overall parameters than one without). + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && ( + source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source: Signature, target: Signature, partialMatch: boolean, ignoreReturnTypes: boolean, compareTypes: (s: Type, t: Type) => Ternary): Ternary { + // TODO (drosen): De-duplicate code between related functions. if (source === target) { return Ternary.True; } - if (source.parameters.length !== target.parameters.length || - source.minArgumentCount !== target.minArgumentCount || - source.hasRestParameter !== target.hasRestParameter) { - if (!partialMatch || - source.parameters.length < target.parameters.length && !source.hasRestParameter || - source.minArgumentCount > target.minArgumentCount) { - return Ternary.False; - } + if (!(isMatchingSignature(source, target, partialMatch))) { + return Ternary.False; } - let result = Ternary.True; - if (source.typeParameters && target.typeParameters) { - if (source.typeParameters.length !== target.typeParameters.length) { - return Ternary.False; - } - for (let i = 0, len = source.typeParameters.length; i < len; ++i) { - const related = compareTypes(source.typeParameters[i], target.typeParameters[i]); - if (!related) { - return Ternary.False; - } - result &= related; - } - } - else if (source.typeParameters || target.typeParameters) { + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) { return Ternary.False; } // Spec 1.0 Section 3.8.3 & 3.8.4: // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N source = getErasedSignature(source); target = getErasedSignature(target); + let result = Ternary.True; const targetLen = target.parameters.length; for (let i = 0; i < targetLen; i++) { - const s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); - const t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]); + const s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); + const t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); const related = compareTypes(s, t); if (!related) { return Ternary.False; @@ -5696,14 +6470,30 @@ namespace ts { } function isSupertypeOfEach(candidate: Type, types: Type[]): boolean { - for (const type of types) { - if (candidate !== type && !isTypeSubtypeOf(type, candidate)) return false; + for (const t of types) { + if (candidate !== t && !isTypeSubtypeOf(t, candidate)) return false; } return true; } + function getCombinedFlagsOfTypes(types: Type[]) { + let flags: TypeFlags = 0; + for (const t of types) { + flags |= t.flags; + } + return flags; + } + function getCommonSupertype(types: Type[]): Type { - return forEach(types, t => isSupertypeOfEach(t, types) ? t : undefined); + if (!strictNullChecks) { + return forEach(types, t => isSupertypeOfEach(t, types) ? t : undefined); + } + const primaryTypes = filter(types, t => !(t.flags & TypeFlags.Nullable)); + if (!primaryTypes.length) { + return getUnionType(types); + } + const supertype = forEach(primaryTypes, t => isSupertypeOfEach(t, primaryTypes) ? t : undefined); + return supertype && addNullableKind(supertype, getCombinedFlagsOfTypes(types) & TypeFlags.Nullable); } function reportNoCommonSupertypeError(types: Type[], errorLocation: Node, errorMessageChainHead: DiagnosticMessageChain): void { @@ -5752,14 +6542,20 @@ namespace ts { } function isArrayLikeType(type: Type): boolean { - // A type is array-like if it is not the undefined or null type and if it is assignable to any[] - return !(type.flags & (TypeFlags.Undefined | TypeFlags.Null)) && isTypeAssignableTo(type, anyArrayType); + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return type.flags & TypeFlags.Reference && ((type).target === globalArrayType || (type).target === globalReadonlyArrayType) || + !(type.flags & TypeFlags.Nullable) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isTupleLikeType(type: Type): boolean { return !!getPropertyOfType(type, "0"); } + function isStringLiteralType(type: Type) { + return type.flags & TypeFlags.StringLiteral; + } + /** * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. @@ -5768,6 +6564,73 @@ namespace ts { return !!(type.flags & TypeFlags.Tuple); } + function getNullableKind(type: Type): TypeFlags { + let flags = type.flags; + if (flags & TypeFlags.Union) { + for (const t of (type as UnionType).types) { + flags |= t.flags; + } + } + return flags & TypeFlags.Nullable; + } + + function getNullableTypeOfKind(kind: TypeFlags) { + return kind & TypeFlags.Null ? kind & TypeFlags.Undefined ? + getUnionType([nullType, undefinedType]) : nullType : undefinedType; + } + + function addNullableKind(type: Type, kind: TypeFlags): Type { + if ((getNullableKind(type) & kind) !== kind) { + const types = [type]; + if (kind & TypeFlags.Undefined) { + types.push(undefinedType); + } + if (kind & TypeFlags.Null) { + types.push(nullType); + } + type = getUnionType(types); + } + return type; + } + + function removeNullableKind(type: Type, kind: TypeFlags) { + if (type.flags & TypeFlags.Union && getNullableKind(type) & kind) { + let firstType: Type; + let types: Type[]; + for (const t of (type as UnionType).types) { + if (!(t.flags & kind)) { + if (!firstType) { + firstType = t; + } + else { + if (!types) { + types = [firstType]; + } + types.push(t); + } + } + } + if (firstType) { + type = types ? getUnionType(types) : firstType; + } + } + return type; + } + + function getNonNullableType(type: Type): Type { + return strictNullChecks ? removeNullableKind(type, TypeFlags.Nullable) : type; + } + + /** + * Return true if type was inferred from an object literal or written as an object type literal + * with no call or construct signatures. + */ + function isObjectLiteralType(type: Type) { + return type.symbol && (type.symbol.flags & (SymbolFlags.ObjectLiteral | SymbolFlags.TypeLiteral)) !== 0 && + getSignaturesOfType(type, SignatureKind.Call).length === 0 && + getSignaturesOfType(type, SignatureKind.Construct).length === 0; + } + function getRegularTypeOfObjectLiteral(type: Type): Type { if (type.flags & TypeFlags.FreshObjectLiteral) { let regularType = (type).regularType; @@ -5778,8 +6641,8 @@ namespace ts { regularType.properties = (type).properties; regularType.callSignatures = (type).callSignatures; regularType.constructSignatures = (type).constructSignatures; - regularType.stringIndexType = (type).stringIndexType; - regularType.numberIndexType = (type).numberIndexType; + regularType.stringIndexInfo = (type).stringIndexInfo; + regularType.numberIndexInfo = (type).numberIndexInfo; (type).regularType = regularType; } return regularType; @@ -5804,23 +6667,27 @@ namespace ts { } members[p.name] = p; }); - let stringIndexType = getIndexTypeOfType(type, IndexKind.String); - let numberIndexType = getIndexTypeOfType(type, IndexKind.Number); - if (stringIndexType) stringIndexType = getWidenedType(stringIndexType); - if (numberIndexType) numberIndexType = getWidenedType(numberIndexType); - return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); + const stringIndexInfo = getIndexInfoOfType(type, IndexKind.String); + const numberIndexInfo = getIndexInfoOfType(type, IndexKind.Number); + return createAnonymousType(type.symbol, members, emptyArray, emptyArray, + stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), + numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + } + + function getWidenedConstituentType(type: Type): Type { + return type.flags & TypeFlags.Nullable ? type : getWidenedType(type); } function getWidenedType(type: Type): Type { if (type.flags & TypeFlags.RequiresWidening) { - if (type.flags & (TypeFlags.Undefined | TypeFlags.Null)) { + if (type.flags & TypeFlags.Nullable) { return anyType; } if (type.flags & TypeFlags.ObjectLiteral) { return getWidenedTypeOfObjectLiteral(type); } if (type.flags & TypeFlags.Union) { - return getUnionType(map((type).types, getWidenedType), /*noSubtypeReduction*/ true); + return getUnionType(map((type).types, getWidenedConstituentType), /*noSubtypeReduction*/ true); } if (isArrayType(type)) { return createArrayType(getWidenedType((type).typeArguments[0])); @@ -5938,19 +6805,15 @@ namespace ts { count = sourceMax < targetMax ? sourceMax : targetMax; } for (let i = 0; i < count; i++) { - const s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - const t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + const s = i < sourceMax ? getTypeOfParameter(source.parameters[i]) : getRestTypeOfSignature(source); + const t = i < targetMax ? getTypeOfParameter(target.parameters[i]) : getRestTypeOfSignature(target); callback(s, t); } } function createInferenceContext(typeParameters: TypeParameter[], inferUnionTypes: boolean): InferenceContext { - const inferences: TypeInferences[] = []; - for (const unused of typeParameters) { - inferences.push({ - primary: undefined, secondary: undefined, isFixed: false - }); - } + const inferences = map(typeParameters, createTypeInferencesObject); + return { typeParameters, inferUnionTypes, @@ -5959,11 +6822,20 @@ namespace ts { }; } + function createTypeInferencesObject(): TypeInferences { + return { + primary: undefined, + secondary: undefined, + isFixed: false, + }; + } + function inferTypes(context: InferenceContext, source: Type, target: Type) { let sourceStack: Type[]; let targetStack: Type[]; let depth = 0; let inferiority = 0; + const visited: Map = {}; inferFromTypes(source, target); function isInProcess(source: Type, target: Type) { @@ -5976,6 +6848,28 @@ namespace ts { } function inferFromTypes(source: Type, target: Type) { + if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union || + source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) { + // Source and target are both unions or both intersections. First, find each + // target constituent type that has an identically matching source constituent + // type, and for each such target constituent type infer from the type to itself. + // When inferring from a type to itself we effectively find all type parameter + // occurrences within that type and infer themselves as their type arguments. + let matchingTypes: Type[]; + for (const t of (target).types) { + if (typeIdenticalToSomeType(t, (source).types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } if (target.flags & TypeFlags.TypeParameter) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). @@ -5986,7 +6880,6 @@ namespace ts { if (source.flags & TypeFlags.ContainsAnyFunctionType) { return; } - const typeParameters = context.typeParameters; for (let i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { @@ -6051,7 +6944,7 @@ namespace ts { } } else if (source.flags & TypeFlags.UnionOrIntersection) { - // Source is a union or intersection type, infer from each consituent type + // Source is a union or intersection type, infer from each constituent type const sourceTypes = (source).types; for (const sourceType of sourceTypes) { inferFromTypes(sourceType, target); @@ -6059,9 +6952,12 @@ namespace ts { } else { source = getApparentType(source); - if (source.flags & TypeFlags.ObjectType && (target.flags & (TypeFlags.Reference | TypeFlags.Tuple) || - (target.flags & TypeFlags.Anonymous) && target.symbol && target.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class))) { - // 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 (source.flags & TypeFlags.ObjectType && ( + target.flags & TypeFlags.Reference && (target).typeArguments || + target.flags & TypeFlags.Tuple || + target.flags & TypeFlags.Anonymous && target.symbol && target.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class))) { + // If source is an object type, and target is a type reference with type arguments, a tuple type, + // the type of a method, or a type literal, infer from members if (isInProcess(source, target)) { return; } @@ -6069,6 +6965,12 @@ namespace ts { return; } + const key = source.id + "," + target.id; + if (hasProperty(visited, key)) { + return; + } + visited[key] = true; + if (depth === 0) { sourceStack = []; targetStack = []; @@ -6079,9 +6981,7 @@ namespace ts { 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); + inferFromIndexTypes(source, target); depth--; } } @@ -6110,30 +7010,59 @@ namespace ts { function inferFromSignature(source: Signature, target: Signature) { forEachMatchingParameterType(source, target, inferFromTypes); - 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); - } + + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); } } - function inferFromIndexTypes(source: Type, target: Type, sourceKind: IndexKind, targetKind: IndexKind) { - const targetIndexType = getIndexTypeOfType(target, targetKind); - if (targetIndexType) { - const sourceIndexType = getIndexTypeOfType(source, sourceKind); + function inferFromIndexTypes(source: Type, target: Type) { + const targetStringIndexType = getIndexTypeOfType(target, IndexKind.String); + if (targetStringIndexType) { + const sourceIndexType = getIndexTypeOfType(source, IndexKind.String) || + getImplicitIndexTypeOfType(source, IndexKind.String); if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetIndexType); + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + const targetNumberIndexType = getIndexTypeOfType(target, IndexKind.Number); + if (targetNumberIndexType) { + const sourceIndexType = getIndexTypeOfType(source, IndexKind.Number) || + getIndexTypeOfType(source, IndexKind.String) || + getImplicitIndexTypeOfType(source, IndexKind.Number); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); } } } } + function typeIdenticalToSomeType(type: Type, types: Type[]): boolean { + for (const t of types) { + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type: UnionOrIntersectionType, typesToRemove: Type[]) { + const reducedTypes: Type[] = []; + for (const t of type.types) { + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & TypeFlags.Union ? getUnionType(reducedTypes, /*noSubtypeReduction*/ true) : getIntersectionType(reducedTypes); + } + function getInferenceCandidates(context: InferenceContext, index: number): Type[] { const inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; @@ -6158,11 +7087,17 @@ namespace ts { inferredType = emptyObjectType; inferenceSucceeded = true; } + context.inferredTypes[index] = inferredType; // Only do the constraint check if inference succeeded (to prevent cascading errors) if (inferenceSucceeded) { const constraint = getConstraintOfTypeParameter(context.typeParameters[index]); - inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + if (constraint) { + const instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + context.inferredTypes[index] = inferredType = instantiatedConstraint; + } + } } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { // If inference failed, it is necessary to record the index of the failed type parameter (the one we are on). @@ -6170,7 +7105,6 @@ namespace ts { // So if this failure is on preceding type parameter, this type parameter is the new failure index. context.failedTypeParameterIndex = index; } - context.inferredTypes[index] = inferredType; } return inferredType; } @@ -6179,20 +7113,27 @@ namespace ts { for (let i = 0; i < context.inferredTypes.length; i++) { getInferredType(context, i); } - return context.inferredTypes; } - function hasAncestor(node: Node, kind: SyntaxKind): boolean { - return getAncestor(node, kind) !== undefined; - } - // EXPRESSION TYPE CHECKING + function createTransientIdentifier(symbol: Symbol, location: Node): Identifier { + const result = createNode(SyntaxKind.Identifier); + result.text = symbol.name; + result.resolvedSymbol = symbol; + result.parent = location; + result.id = -1; + return result; + } + function getResolvedSymbol(node: Identifier): Symbol { + if (node.id === -1) { + return (node).resolvedSymbol; + } const links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = (!nodeIsMissing(node) && resolveName(node, node.text, SymbolFlags.Value | SymbolFlags.ExportValue, Diagnostics.Cannot_find_name_0, node)) || unknownSymbol; + links.resolvedSymbol = !nodeIsMissing(node) && resolveName(node, node.text, SymbolFlags.Value | SymbolFlags.ExportValue, Diagnostics.Cannot_find_name_0, node) || unknownSymbol; } return links.resolvedSymbol; } @@ -6216,82 +7157,74 @@ namespace ts { Debug.fail("should not get here"); } - // For a union type, remove all constituent types that are of the given type kind (when isOfTypeKind is true) - // or not of the given type kind (when isOfTypeKind is false) - function removeTypesFromUnionType(type: Type, typeKind: TypeFlags, isOfTypeKind: boolean, allowEmptyUnionResult: boolean): Type { - if (type.flags & TypeFlags.Union) { - const types = (type).types; - if (forEach(types, t => !!(t.flags & typeKind) === isOfTypeKind)) { - // Above we checked if we have anything to remove, now use the opposite test to do the removal - const narrowedType = getUnionType(filter(types, t => !(t.flags & typeKind) === isOfTypeKind)); - if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { - return narrowedType; - } - } + // Return the assignment key for a "dotted name" (i.e. a sequence of identifiers + // separated by dots). The key consists of the id of the symbol referenced by the + // leftmost identifier followed by zero or more property names separated by dots. + // The result is undefined if the reference isn't a dotted name. + function getAssignmentKey(node: Node): string { + if (node.kind === SyntaxKind.Identifier) { + const symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? "" + getSymbolId(symbol) : undefined; } - else if (allowEmptyUnionResult && !!(type.flags & typeKind) === isOfTypeKind) { - // Use getUnionType(emptyArray) instead of emptyObjectType in case the way empty union types - // are represented ever changes. - return getUnionType(emptyArray); + if (node.kind === SyntaxKind.ThisKeyword) { + return "0"; } - return type; + if (node.kind === SyntaxKind.PropertyAccessExpression) { + const key = getAssignmentKey((node).expression); + return key && key + "." + (node).name.text; + } + return undefined; } function hasInitializer(node: VariableLikeDeclaration): boolean { return !!(node.initializer || isBindingPattern(node.parent) && hasInitializer(node.parent.parent)); } - // Check if a given variable is assigned within a given syntax node - function isVariableAssignedWithin(symbol: Symbol, node: Node): boolean { - const links = getNodeLinks(node); - if (links.assignmentChecks) { - const cachedResult = links.assignmentChecks[symbol.id]; - if (cachedResult !== undefined) { - return cachedResult; - } - } - else { - links.assignmentChecks = {}; - } - return links.assignmentChecks[symbol.id] = isAssignedIn(node); + // For a given node compute a map of which dotted names are assigned within + // the node. + function getAssignmentMap(node: Node): Map { + const assignmentMap: Map = {}; + visit(node); + return assignmentMap; - function isAssignedInBinaryExpression(node: BinaryExpression) { - if (node.operatorToken.kind >= SyntaxKind.FirstAssignment && node.operatorToken.kind <= SyntaxKind.LastAssignment) { - let n = node.left; - while (n.kind === SyntaxKind.ParenthesizedExpression) { - n = (n).expression; - } - if (n.kind === SyntaxKind.Identifier && getResolvedSymbol(n) === symbol) { - return true; + function visitReference(node: Identifier | PropertyAccessExpression) { + if (isAssignmentTarget(node) || isCompoundAssignmentTarget(node)) { + const key = getAssignmentKey(node); + if (key) { + assignmentMap[key] = true; } } - return forEachChild(node, isAssignedIn); + forEachChild(node, visit); } - function isAssignedInVariableDeclaration(node: VariableLikeDeclaration) { - if (!isBindingPattern(node.name) && getSymbolOfNode(node) === symbol && hasInitializer(node)) { - return true; + function visitVariableDeclaration(node: VariableLikeDeclaration) { + if (!isBindingPattern(node.name) && hasInitializer(node)) { + assignmentMap[getSymbolId(getSymbolOfNode(node))] = true; } - return forEachChild(node, isAssignedIn); + forEachChild(node, visit); } - function isAssignedIn(node: Node): boolean { + function visit(node: Node) { switch (node.kind) { - case SyntaxKind.BinaryExpression: - return isAssignedInBinaryExpression(node); + case SyntaxKind.Identifier: + case SyntaxKind.PropertyAccessExpression: + visitReference(node); + break; case SyntaxKind.VariableDeclaration: case SyntaxKind.BindingElement: - return isAssignedInVariableDeclaration(node); + visitVariableDeclaration(node); + break; + case SyntaxKind.BinaryExpression: case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.ObjectLiteralExpression: - case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: case SyntaxKind.TypeAssertionExpression: case SyntaxKind.AsExpression: + case SyntaxKind.NonNullExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.DeleteExpression: @@ -6314,6 +7247,7 @@ namespace ts { case SyntaxKind.ReturnStatement: case SyntaxKind.WithStatement: case SyntaxKind.SwitchStatement: + case SyntaxKind.CaseBlock: case SyntaxKind.CaseClause: case SyntaxKind.DefaultClause: case SyntaxKind.LabeledStatement: @@ -6326,105 +7260,238 @@ namespace ts { case SyntaxKind.JsxSpreadAttribute: case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxExpression: - return forEachChild(node, isAssignedIn); + forEachChild(node, visit); + break; } - return false; } } - // Get the narrowed type of a given symbol at a given location - 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) { - if (isTypeAny(type) || type.flags & (TypeFlags.ObjectType | TypeFlags.Union | TypeFlags.TypeParameter)) { - loop: while (node.parent) { - const 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); - } - 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; - } - } + function isReferenceAssignedWithin(reference: Node, node: Node): boolean { + if (reference.kind !== SyntaxKind.ThisKeyword) { + const key = getAssignmentKey(reference); + if (key) { + const links = getNodeLinks(node); + return (links.assignmentMap || (links.assignmentMap = getAssignmentMap(node)))[key]; } } + return false; + } + + function isAnyPartOfReferenceAssignedWithin(reference: Node, node: Node) { + while (true) { + if (isReferenceAssignedWithin(reference, node)) { + return true; + } + if (reference.kind !== SyntaxKind.PropertyAccessExpression) { + return false; + } + reference = (reference).expression; + } + } + + function isNullOrUndefinedLiteral(node: Expression) { + return node.kind === SyntaxKind.NullKeyword || + node.kind === SyntaxKind.Identifier && getResolvedSymbol(node) === undefinedSymbol; + } + + function getLeftmostIdentifierOrThis(node: Node): Node { + switch (node.kind) { + case SyntaxKind.Identifier: + case SyntaxKind.ThisKeyword: + return node; + case SyntaxKind.PropertyAccessExpression: + return getLeftmostIdentifierOrThis((node).expression); + } + return undefined; + } + + function isMatchingReference(source: Node, target: Node): boolean { + if (source.kind === target.kind) { + switch (source.kind) { + case SyntaxKind.Identifier: + return getResolvedSymbol(source) === getResolvedSymbol(target); + case SyntaxKind.ThisKeyword: + return true; + case SyntaxKind.PropertyAccessExpression: + return (source).name.text === (target).name.text && + isMatchingReference((source).expression, (target).expression); + } + } + return false; + } + + // Get the narrowed type of a given symbol at a given location + function getNarrowedTypeOfReference(type: Type, reference: Node) { + if (!(type.flags & (TypeFlags.Any | TypeFlags.ObjectType | TypeFlags.Union | TypeFlags.TypeParameter))) { + return type; + } + const leftmostNode = getLeftmostIdentifierOrThis(reference); + if (!leftmostNode) { + return type; + } + let top: Node; + if (leftmostNode.kind === SyntaxKind.Identifier) { + const leftmostSymbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(leftmostNode)); + if (!leftmostSymbol) { + return type; + } + const declaration = leftmostSymbol.valueDeclaration; + if (!declaration || declaration.kind !== SyntaxKind.VariableDeclaration && declaration.kind !== SyntaxKind.Parameter && declaration.kind !== SyntaxKind.BindingElement) { + return type; + } + top = getDeclarationContainer(declaration); + } + const originalType = type; + const nodeStack: { node: Node, child: Node }[] = []; + let node: Node = reference; + loop: while (node.parent) { + const child = node; + node = node.parent; + switch (node.kind) { + case SyntaxKind.IfStatement: + case SyntaxKind.ConditionalExpression: + case SyntaxKind.BinaryExpression: + nodeStack.push({node, child}); + break; + case SyntaxKind.SourceFile: + case SyntaxKind.ModuleDeclaration: + break loop; + default: + if (node === top || isFunctionLikeKind(node.kind)) { + break loop; + } + break; + } + } + + let nodes: { node: Node, child: Node }; + while (nodes = nodeStack.pop()) { + const {node, child} = nodes; + switch (node.kind) { + case SyntaxKind.IfStatement: + // In a branch of an if statement, narrow based on controlling expression + if (child !== (node).expression) { + type = 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) { + type = 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) { + type = narrowType(type, (node).left, /*assumeTrue*/ true); + } + else if ((node).operatorToken.kind === SyntaxKind.BarBarToken) { + type = narrowType(type, (node).left, /*assumeTrue*/ false); + } + } + break; + default: + Debug.fail("Unreachable!"); + } + + // Use original type if construct contains assignments to variable + if (type !== originalType && isAnyPartOfReferenceAssignedWithin(reference, node)) { + type = originalType; + } + } + + // Preserve old top-level behavior - if the branch is really an empty set, revert to prior type + if (type === emptyUnionType) { + type = originalType; + } return type; - function narrowTypeByEquality(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { - // Check that we have 'typeof ' on the left and string literal on the right - if (expr.left.kind !== SyntaxKind.TypeOfExpression || expr.right.kind !== SyntaxKind.StringLiteral) { - return type; + function narrowTypeByTruthiness(type: Type, expr: Expression, assumeTrue: boolean): Type { + return strictNullChecks && assumeTrue && isMatchingReference(expr, reference) ? getNonNullableType(type) : type; + } + + function narrowTypeByBinaryExpression(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { + switch (expr.operatorToken.kind) { + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsEqualsToken: + case SyntaxKind.ExclamationEqualsEqualsToken: + if (isNullOrUndefinedLiteral(expr.right)) { + return narrowTypeByNullCheck(type, expr, assumeTrue); + } + if (expr.left.kind === SyntaxKind.TypeOfExpression && expr.right.kind === SyntaxKind.StringLiteral) { + return narrowTypeByTypeof(type, expr, assumeTrue); + } + break; + case SyntaxKind.AmpersandAmpersandToken: + return narrowTypeByAnd(type, expr, assumeTrue); + case SyntaxKind.BarBarToken: + return narrowTypeByOr(type, expr, assumeTrue); + case SyntaxKind.InstanceOfKeyword: + return narrowTypeByInstanceof(type, expr, assumeTrue); } - const left = expr.left; - const right = expr.right; - if (left.expression.kind !== SyntaxKind.Identifier || getResolvedSymbol(left.expression) !== symbol) { - return type; - } - const typeInfo = primitiveTypeInfo[right.text]; - if (expr.operatorToken.kind === SyntaxKind.ExclamationEqualsEqualsToken) { + return type; + } + + function narrowTypeByNullCheck(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { + // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' on the right + const operator = expr.operatorToken.kind; + if (operator === SyntaxKind.ExclamationEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) { assumeTrue = !assumeTrue; } + if (!strictNullChecks || !isMatchingReference(expr.left, reference)) { + return type; + } + const doubleEquals = operator === SyntaxKind.EqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsToken; + const exprNullableKind = doubleEquals ? TypeFlags.Nullable : + expr.right.kind === SyntaxKind.NullKeyword ? TypeFlags.Null : TypeFlags.Undefined; if (assumeTrue) { - // Assumed result is true. If check was not for a primitive type, remove all primitive types - if (!typeInfo) { - return removeTypesFromUnionType(type, /*typeKind*/ TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.Boolean | TypeFlags.ESSymbol, - /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); - } - // Check was for a primitive type, return that primitive type if it is a subtype - if (isTypeSubtypeOf(typeInfo.type, type)) { - return typeInfo.type; - } - // Otherwise, remove all types that aren't of the primitive type kind. This can happen when the type is - // union of enum types and other types. - return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ false, /*allowEmptyUnionResult*/ false); + const nullableKind = getNullableKind(type) & exprNullableKind; + return nullableKind ? getNullableTypeOfKind(nullableKind) : type; + } + return removeNullableKind(type, exprNullableKind); + } + + function narrowTypeByTypeof(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' on the left + // and string literal on the right + const left = expr.left; + const right = expr.right; + if (!isMatchingReference(left.expression, reference)) { + return type; + } + if (expr.operatorToken.kind === SyntaxKind.ExclamationEqualsToken || + expr.operatorToken.kind === SyntaxKind.ExclamationEqualsEqualsToken) { + assumeTrue = !assumeTrue; + } + const typeInfo = primitiveTypeInfo[right.text]; + // Don't narrow `undefined` + if (typeInfo && typeInfo.type === undefinedType) { + return type; + } + let flags: TypeFlags; + if (typeInfo) { + flags = typeInfo.flags; } else { - // Assumed result is false. If check was for a primitive type, remove that primitive type - if (typeInfo) { - return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); + assumeTrue = !assumeTrue; + flags = TypeFlags.NumberLike | TypeFlags.StringLike | TypeFlags.ESSymbol | TypeFlags.Boolean; + } + // At this point we can bail if it's not a union + if (!(type.flags & TypeFlags.Union)) { + // If we're on the true branch and the type is a subtype, we should return the primitive type + if (assumeTrue && typeInfo && isTypeSubtypeOf(typeInfo.type, type)) { + return typeInfo.type; } - // Otherwise we don't have enough information to do anything. - return type; + // If the active non-union type would be removed from a union by this type guard, return an empty union + return filterUnion(type) ? type : emptyUnionType; + } + return getUnionType(filter((type as UnionType).types, filterUnion), /*noSubtypeReduction*/ true); + + function filterUnion(type: Type) { + return assumeTrue === !!(type.flags & flags); } } @@ -6438,7 +7505,7 @@ namespace ts { // and the second operand was false. We narrow with those assumptions and union the two resulting types. return getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ false), - narrowType(narrowType(type, expr.left, /*assumeTrue*/ true), expr.right, /*assumeTrue*/ false) + narrowType(type, expr.right, /*assumeTrue*/ false) ]); } } @@ -6449,7 +7516,7 @@ namespace ts { // and the second operand was true. We narrow with those assumptions and union the two resulting types. return getUnionType([ narrowType(type, expr.left, /*assumeTrue*/ true), - narrowType(narrowType(type, expr.left, /*assumeTrue*/ false), expr.right, /*assumeTrue*/ true) + narrowType(type, expr.right, /*assumeTrue*/ true) ]); } else { @@ -6460,9 +7527,10 @@ namespace 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 (isTypeAny(type) || !assumeTrue || expr.left.kind !== SyntaxKind.Identifier || getResolvedSymbol(expr.left) !== symbol) { + if (isTypeAny(type) || !isMatchingReference(expr.left, reference)) { return type; } + // Check that right operand is a function type with a prototype property const rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { @@ -6494,13 +7562,20 @@ namespace ts { } if (targetType) { - return getNarrowedType(type, targetType); + return getNarrowedType(type, targetType, assumeTrue); } return type; } - function getNarrowedType(originalType: Type, narrowedTypeCandidate: Type) { + function getNarrowedType(originalType: Type, narrowedTypeCandidate: Type, assumeTrue: boolean) { + if (!assumeTrue) { + if (originalType.flags & TypeFlags.Union) { + return getUnionType(filter((originalType).types, t => !isTypeSubtypeOf(t, narrowedTypeCandidate))); + } + return originalType; + } + // If the current type is a union type, remove all constituents that aren't assignable to target. If that produces // 0 candidates, fall back to the assignability check if (originalType.flags & TypeFlags.Union) { @@ -6510,7 +7585,8 @@ namespace ts { } } - if (isTypeAssignableTo(narrowedTypeCandidate, originalType)) { + const targetType = originalType.flags & TypeFlags.TypeParameter ? getApparentType(originalType) : originalType; + if (isTypeAssignableTo(narrowedTypeCandidate, targetType)) { // Narrow to the target type if it's assignable to the current type return narrowedTypeCandidate; } @@ -6518,23 +7594,30 @@ namespace ts { return originalType; } - function narrowTypeByTypePredicate(type: Type, expr: CallExpression, assumeTrue: boolean): Type { + function narrowTypeByTypePredicate(type: Type, callExpression: CallExpression, assumeTrue: boolean): Type { if (type.flags & TypeFlags.Any) { return type; } - const 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))); + const signature = getResolvedSignature(callExpression); + const predicate = signature.typePredicate; + if (!predicate) { + return type; + } + if (isIdentifierTypePredicate(predicate)) { + const predicateArgument = callExpression.arguments[predicate.parameterIndex]; + if (predicateArgument && isMatchingReference(predicateArgument, reference)) { + return getNarrowedType(type, predicate.type, assumeTrue); + } + } + else { + const invokedExpression = skipParenthesizedNodes(callExpression.expression); + if (invokedExpression.kind === SyntaxKind.ElementAccessExpression || invokedExpression.kind === SyntaxKind.PropertyAccessExpression) { + const accessExpression = invokedExpression as ElementAccessExpression | PropertyAccessExpression; + const possibleReference= skipParenthesizedNodes(accessExpression.expression); + if (isMatchingReference(possibleReference, reference)) { + return getNarrowedType(type, predicate.type, assumeTrue); } - return type; } - return getNarrowedType(type, signature.typePredicate.type); } return type; } @@ -6543,25 +7626,16 @@ namespace ts { // 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.Identifier: + case SyntaxKind.ThisKeyword: + case SyntaxKind.PropertyAccessExpression: + return narrowTypeByTruthiness(type, expr, assumeTrue); case SyntaxKind.CallExpression: return narrowTypeByTypePredicate(type, expr, assumeTrue); case SyntaxKind.ParenthesizedExpression: return narrowType(type, (expr).expression, assumeTrue); case SyntaxKind.BinaryExpression: - const operator = (expr).operatorToken.kind; - if (operator === SyntaxKind.EqualsEqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) { - return narrowTypeByEquality(type, expr, assumeTrue); - } - else if (operator === SyntaxKind.AmpersandAmpersandToken) { - return narrowTypeByAnd(type, expr, assumeTrue); - } - else if (operator === SyntaxKind.BarBarToken) { - return narrowTypeByOr(type, expr, assumeTrue); - } - else if (operator === SyntaxKind.InstanceOfKeyword) { - return narrowTypeByInstanceof(type, expr, assumeTrue); - } - break; + return narrowTypeByBinaryExpression(type, expr, assumeTrue); case SyntaxKind.PrefixUnaryExpression: if ((expr).operator === SyntaxKind.ExclamationToken) { return narrowType(type, (expr).operand, !assumeTrue); @@ -6572,6 +7646,129 @@ namespace ts { } } + function getTypeOfSymbolAtLocation(symbol: Symbol, location: Node) { + // The language service will always care about the narrowed type of a symbol, because that is + // the type the language says the symbol should have. + const type = getTypeOfSymbol(symbol); + if (location.kind === SyntaxKind.Identifier) { + if (isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + // If location is an identifier or property access that references the given + // symbol, use the location as the reference with respect to which we narrow. + if (isExpression(location)) { + checkExpression(location); + if (getNodeLinks(location).resolvedSymbol === symbol) { + return getNarrowedTypeOfReference(type, location); + } + } + } + // The location isn't a reference to the given symbol, meaning we're being asked + // a hypothetical question of what type the symbol would have if there was a reference + // to it at the given location. To answer that question we manufacture a transient + // identifier at the location and narrow with respect to that identifier. + return getNarrowedTypeOfReference(type, createTransientIdentifier(symbol, location)); + } + + function skipParenthesizedNodes(expression: Expression): Expression { + while (expression.kind === SyntaxKind.ParenthesizedExpression) { + expression = (expression as ParenthesizedExpression).expression; + } + return expression; + } + + function findFirstAssignment(symbol: Symbol, container: Node): Node { + return visit(isFunctionLike(container) ? (container).body : container); + + function visit(node: Node): Node { + switch (node.kind) { + case SyntaxKind.Identifier: + const assignment = getAssignmentRoot(node); + return assignment && getResolvedSymbol(node) === symbol ? assignment : undefined; + case SyntaxKind.BinaryExpression: + case SyntaxKind.VariableDeclaration: + case SyntaxKind.BindingElement: + case SyntaxKind.ObjectBindingPattern: + case SyntaxKind.ArrayBindingPattern: + case SyntaxKind.ArrayLiteralExpression: + case SyntaxKind.ObjectLiteralExpression: + case SyntaxKind.PropertyAccessExpression: + case SyntaxKind.ElementAccessExpression: + case SyntaxKind.CallExpression: + case SyntaxKind.NewExpression: + case SyntaxKind.TypeAssertionExpression: + case SyntaxKind.AsExpression: + case SyntaxKind.NonNullExpression: + case SyntaxKind.ParenthesizedExpression: + case SyntaxKind.PrefixUnaryExpression: + case SyntaxKind.DeleteExpression: + case SyntaxKind.AwaitExpression: + case SyntaxKind.TypeOfExpression: + case SyntaxKind.VoidExpression: + case SyntaxKind.PostfixUnaryExpression: + case SyntaxKind.YieldExpression: + case SyntaxKind.ConditionalExpression: + case SyntaxKind.SpreadElementExpression: + case SyntaxKind.VariableStatement: + case SyntaxKind.ExpressionStatement: + case SyntaxKind.IfStatement: + case SyntaxKind.DoStatement: + case SyntaxKind.WhileStatement: + case SyntaxKind.ForStatement: + case SyntaxKind.ForInStatement: + case SyntaxKind.ForOfStatement: + case SyntaxKind.ReturnStatement: + case SyntaxKind.WithStatement: + case SyntaxKind.SwitchStatement: + case SyntaxKind.CaseBlock: + case SyntaxKind.CaseClause: + case SyntaxKind.DefaultClause: + case SyntaxKind.LabeledStatement: + case SyntaxKind.ThrowStatement: + case SyntaxKind.TryStatement: + case SyntaxKind.CatchClause: + case SyntaxKind.JsxElement: + case SyntaxKind.JsxSelfClosingElement: + case SyntaxKind.JsxAttribute: + case SyntaxKind.JsxSpreadAttribute: + case SyntaxKind.JsxOpeningElement: + case SyntaxKind.JsxExpression: + case SyntaxKind.Block: + case SyntaxKind.SourceFile: + return forEachChild(node, visit); + } + return undefined; + } + } + + function checkVariableAssignedBefore(symbol: Symbol, reference: Node) { + if (!(symbol.flags & SymbolFlags.Variable)) { + return; + } + const declaration = symbol.valueDeclaration; + if (!declaration || declaration.kind !== SyntaxKind.VariableDeclaration || (declaration).initializer || isInAmbientContext(declaration)) { + return; + } + const parentParentKind = declaration.parent.parent.kind; + if (parentParentKind === SyntaxKind.ForOfStatement || parentParentKind === SyntaxKind.ForInStatement) { + return; + } + const declarationContainer = getContainingFunction(declaration) || getSourceFileOfNode(declaration); + const referenceContainer = getContainingFunction(reference) || getSourceFileOfNode(reference); + if (declarationContainer !== referenceContainer) { + return; + } + const links = getSymbolLinks(symbol); + if (!links.firstAssignmentChecked) { + links.firstAssignmentChecked = true; + links.firstAssignment = findFirstAssignment(symbol, declarationContainer); + } + if (links.firstAssignment && links.firstAssignment.end <= reference.pos) { + return; + } + error(reference, Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + } + function checkIdentifier(node: Identifier): Type { const symbol = getResolvedSymbol(node); @@ -6589,9 +7786,8 @@ namespace ts { } } - if (node.parserContextFlags & ParserContextFlags.Await) { + if (node.flags & NodeFlags.AwaitContext) { getNodeLinks(container).flags |= NodeCheckFlags.CaptureArguments; - getNodeLinks(node).flags |= NodeCheckFlags.LexicalArguments; } } @@ -6599,11 +7795,36 @@ namespace ts { markAliasSymbolAsReferenced(symbol); } + const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (languageVersion === ScriptTarget.ES6 + && localOrExportSymbol.flags & SymbolFlags.Class + && localOrExportSymbol.valueDeclaration.kind === SyntaxKind.ClassDeclaration + && nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { + let container = getContainingClass(node); + while (container !== undefined) { + if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { + getNodeLinks(container).flags |= NodeCheckFlags.ClassWithBodyScopedClassBinding; + getNodeLinks(node).flags |= NodeCheckFlags.BodyScopedClassBinding; + break; + } + + container = getContainingClass(container); + } + } + checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); - checkBlockScopedBindingCapturedInLoop(node, symbol); + checkNestedBlockScopedBinding(node, symbol); - return getNarrowedTypeOfSymbol(getExportSymbolOfValueSymbolIfExported(symbol), node); + const type = getTypeOfSymbol(localOrExportSymbol); + if (strictNullChecks && !isAssignmentTarget(node) && !(type.flags & TypeFlags.Any) && !(getNullableKind(type) & TypeFlags.Undefined)) { + checkVariableAssignedBefore(symbol, node); + } + return getNarrowedTypeOfReference(type, node); } function isInsideFunction(node: Node, threshold: Node): boolean { @@ -6618,7 +7839,7 @@ namespace ts { return false; } - function checkBlockScopedBindingCapturedInLoop(node: Identifier, symbol: Symbol): void { + function checkNestedBlockScopedBinding(node: Identifier, symbol: Symbol): void { if (languageVersion >= ScriptTarget.ES6 || (symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.Class)) === 0 || symbol.valueDeclaration.parent.kind === SyntaxKind.CatchClause) { @@ -6630,40 +7851,74 @@ namespace ts { // 2. walk from the declaration up to the boundary of lexical environment and check // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) - let container: Node; - if (symbol.flags & SymbolFlags.Class) { - // get parent of class declaration - container = getClassLikeDeclarationOfSymbol(symbol).parent; - } - else { - // nesting structure: - // (variable declaration or binding element) -> variable declaration list -> container - container = symbol.valueDeclaration; - while (container.kind !== SyntaxKind.VariableDeclarationList) { - container = container.parent; - } - // get the parent of variable declaration list - container = container.parent; - if (container.kind === SyntaxKind.VariableStatement) { - // if parent is variable statement - get its parent - container = container.parent; - } - } - - const inFunction = isInsideFunction(node.parent, container); - + const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); + const usedInFunction = isInsideFunction(node.parent, container); let current = container; + + let containedInIterationStatement = false; while (current && !nodeStartsNewLexicalEnvironment(current)) { if (isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - if (inFunction) { - getNodeLinks(current).flags |= NodeCheckFlags.LoopWithBlockScopedBindingCapturedInFunction; - } - // mark value declaration so during emit they can have a special handling - getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.BlockScopedBindingInLoop; + containedInIterationStatement = true; break; } current = current.parent; } + + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + getNodeLinks(current).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding; + } + + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === SyntaxKind.ForStatement && + getAncestor(symbol.valueDeclaration, SyntaxKind.VariableDeclarationList).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.NeedsLoopOutParameter; + } + + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.BlockScopedBindingInLoop; + } + + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.CapturedBlockScopedBinding; + } + } + + function isAssignedInBodyOfForStatement(node: Identifier, container: ForStatement): boolean { + let current: Node = node; + // skip parenthesized nodes + while (current.parent.kind === SyntaxKind.ParenthesizedExpression) { + current = current.parent; + } + + // check if node is used as LHS in some assignment expression + let isAssigned = false; + if (isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === SyntaxKind.PrefixUnaryExpression || current.parent.kind === SyntaxKind.PostfixUnaryExpression)) { + const expr = current.parent; + isAssigned = expr.operator === SyntaxKind.PlusPlusToken || expr.operator === SyntaxKind.MinusMinusToken; + } + + if (!isAssigned) { + return false; + } + + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + while (current !== container) { + if (current === container.statement) { + return true; + } + else { + current = current.parent; + } + } + return false; } function captureLexicalThis(node: Node, container: Node): void { @@ -6677,12 +7932,75 @@ namespace ts { } } + function findFirstSuperCall(n: Node): Node { + if (isSuperCallExpression(n)) { + return n; + } + else if (isFunctionLike(n)) { + return undefined; + } + return forEachChild(n, findFirstSuperCall); + } + + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor: ConstructorDeclaration): ExpressionStatement { + const links = getNodeLinks(constructor); + + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl: ClassDeclaration): boolean { + const classSymbol = getSymbolOfNode(classDecl); + const classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + const baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + + return baseConstructorType === nullType; + } + function checkThisExpression(node: Node): Type { // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. let container = getThisContainer(node, /* includeArrowFunctions */ true); let needToCaptureLexicalThis = false; + if (container.kind === SyntaxKind.Constructor) { + const containingClassDecl = container.parent; + const baseTypeNode = getClassExtendsHeritageClauseElement(containingClassDecl); + + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + const superCall = getSuperCallInConstructor(container); + + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + } + } + // Now skip arrow functions to get the "real" owner of 'this'. if (container.kind === SyntaxKind.ArrowFunction) { container = getThisContainer(container, /* includeArrowFunctions */ false); @@ -6724,11 +8042,46 @@ namespace ts { if (isClassLike(container.parent)) { const symbol = getSymbolOfNode(container.parent); - return container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : (getDeclaredTypeOfSymbol(symbol)).thisType; + const type = container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : (getDeclaredTypeOfSymbol(symbol)).thisType; + return getNarrowedTypeOfReference(type, node); } + + if (isInJavaScriptFile(node)) { + const type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + + // If this is a function in a JS file, it might be a class method. Check if it's the RHS + // of a x.prototype.y = function [name]() { .... } + if (container.kind === SyntaxKind.FunctionExpression) { + if (getSpecialPropertyAssignmentKind(container.parent) === SpecialPropertyAssignmentKind.PrototypeProperty) { + // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') + const className = (((container.parent as BinaryExpression) // x.prototype.y = f + .left as PropertyAccessExpression) // x.prototype.y + .expression as PropertyAccessExpression) // x.prototype + .expression; // x + const classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & SymbolFlags.Function)) { + return getInferredClassType(classSymbol); + } + } + } + } + return anyType; } + function getTypeForThisExpressionFromJSDoc(node: Node) { + const typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === SyntaxKind.JSDocFunctionType) { + const jsDocFunctionType = typeTag.typeExpression.type; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === SyntaxKind.JSDocThisType) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + } + function isInConstructorArgumentInitializer(node: Node, constructorDecl: Node): boolean { for (let n = node; n && n !== constructorDecl; n = n.parent) { if (n.kind === SyntaxKind.Parameter) { @@ -6740,17 +8093,14 @@ namespace ts { function checkSuperExpression(node: Node): Type { const isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent).expression === node; - const classDeclaration = getContainingClass(node); - const classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - const baseClassType = classType && getBaseTypes(classType)[0]; - let container = getSuperContainer(node, /*includeFunctions*/ true); + let container = getSuperContainer(node, /*stopOnFunctions*/ true); let needToCaptureLexicalThis = false; if (!isCallExpression) { // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting while (container && container.kind === SyntaxKind.ArrowFunction) { - container = getSuperContainer(container, /*includeFunctions*/ true); + container = getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < ScriptTarget.ES6; } } @@ -6758,43 +8108,131 @@ namespace ts { const canUseSuperExpression = isLegalUsageOfSuperExpression(container); let nodeCheckFlag: NodeCheckFlags = 0; - // always set NodeCheckFlags for 'super' expression node - if (canUseSuperExpression) { - if ((container.flags & NodeFlags.Static) || isCallExpression) { - nodeCheckFlag = NodeCheckFlags.SuperStatic; - } - else { - nodeCheckFlag = NodeCheckFlags.SuperInstance; - } - - getNodeLinks(node).flags |= nodeCheckFlag; - - if (needToCaptureLexicalThis) { - // call expressions are allowed only in constructors so they should always capture correct 'this' - // super property access expressions can also appear in arrow functions - - // in this case they should also use correct lexical this - captureLexicalThis(node.parent, container); - } - } - - if (!baseClassType) { - if (!classDeclaration || !getClassExtendsHeritageClauseElement(classDeclaration)) { - error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } - if (!canUseSuperExpression) { - if (container && container.kind === SyntaxKind.ComputedPropertyName) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + let current = node; + while (current && current !== container && current.kind !== SyntaxKind.ComputedPropertyName) { + current = current.parent; + } + if (current && current.kind === SyntaxKind.ComputedPropertyName) { error(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } + else if (!container || !container.parent || !(isClassLike(container.parent) || container.parent.kind === SyntaxKind.ObjectLiteralExpression)) { + error(node, Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } else { error(node, Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } + return unknownType; + } + if ((container.flags & NodeFlags.Static) || isCallExpression) { + nodeCheckFlag = NodeCheckFlags.SuperStatic; + } + else { + nodeCheckFlag = NodeCheckFlags.SuperInstance; + } + + getNodeLinks(node).flags |= nodeCheckFlag; + + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = name => super[name]; + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super("asyncMethod").call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + // return __awaiter(this, arguments, Promise, function *() { + // [_super("a").value, _super("b").value] = yield ar; + // }); + // } + // ... + // + // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. + // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment + // while a property access can. + if (container.kind === SyntaxKind.MethodDeclaration && container.flags & NodeFlags.Async) { + if (isSuperPropertyOrElementAccess(node.parent) && isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= NodeCheckFlags.AsyncMethodWithSuperBinding; + } + else { + getNodeLinks(container).flags |= NodeCheckFlags.AsyncMethodWithSuper; + } + } + + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + + if (container.parent.kind === SyntaxKind.ObjectLiteralExpression) { + if (languageVersion < ScriptTarget.ES6) { + error(node, Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + + // at this point the only legal case for parent is ClassLikeDeclaration + const classLikeDeclaration = container.parent; + const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + const baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } return unknownType; } @@ -6824,8 +8262,8 @@ namespace ts { // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor - // topmost container must be something that is directly nested in the class declaration - if (container && isClassLike(container.parent)) { + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (isClassLike(container.parent) || container.parent.kind === SyntaxKind.ObjectLiteralExpression) { if (container.flags & NodeFlags.Static) { return container.kind === SyntaxKind.MethodDeclaration || container.kind === SyntaxKind.MethodSignature || @@ -6875,11 +8313,14 @@ namespace ts { return undefined; } - // In a variable, parameter or property declaration with a type annotation, the contextual type of an initializer - // expression is the type of the variable, parameter or property. Otherwise, in a parameter declaration of a - // contextually typed function expression, the contextual type of an initializer expression is the contextual type - // of the parameter. Otherwise, in a variable or parameter declaration with a binding pattern name, the contextual - // type of an initializer expression is the type implied by the binding pattern. + // In a variable, parameter or property declaration with a type annotation, + // the contextual type of an initializer expression is the type of the variable, parameter or property. + // Otherwise, in a parameter declaration of a contextually typed function expression, + // the contextual type of an initializer expression is the contextual type of the parameter. + // Otherwise, in a variable or parameter declaration with a binding pattern name, + // the contextual type of an initializer expression is the type implied by the binding pattern. + // Otherwise, in a binding pattern inside a variable or parameter declaration, + // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. function getContextualTypeForInitializerExpression(node: Expression): Type { const declaration = node.parent; if (node === declaration.initializer) { @@ -6895,6 +8336,18 @@ namespace ts { if (isBindingPattern(declaration.name)) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true); } + if (isBindingPattern(declaration.parent)) { + const parentDeclaration = declaration.parent.parent; + const name = declaration.propertyName || declaration.name; + if (isVariableLike(parentDeclaration) && + parentDeclaration.type && + !isBindingPattern(name)) { + const text = getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); + } + } + } } return undefined; } @@ -6990,6 +8443,12 @@ namespace ts { } return type; } + else if (operator === SyntaxKind.AmpersandAmpersandToken || operator === SyntaxKind.CommaToken) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } + return undefined; } @@ -7031,16 +8490,15 @@ namespace ts { return applyToContextualType(type, t => getIndexTypeOfStructuredType(t, kind)); } + function contextualTypeIsStringLiteralType(type: Type): boolean { + return !!(type.flags & TypeFlags.Union ? forEach((type).types, isStringLiteralType) : isStringLiteralType(type)); + } + // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type: Type): boolean { return !!(type.flags & TypeFlags.Union ? forEach((type).types, isTupleLikeType) : isTupleLikeType(type)); } - // Return true if the given contextual type provides an index signature of the given kind - function contextualTypeHasIndexSignature(type: Type, kind: IndexKind): boolean { - return !!(type.flags & TypeFlags.Union ? forEach((type).types, t => getIndexTypeOfStructuredType(t, kind)) : getIndexTypeOfStructuredType(type, kind)); - } - // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -7056,7 +8514,7 @@ namespace ts { function getContextualTypeForObjectLiteralElement(element: ObjectLiteralElement) { const objectLiteral = element.parent; - const type = getContextualType(objectLiteral); + const type = getApparentTypeOfContextualType(objectLiteral); if (type) { if (!hasDynamicName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name @@ -7082,7 +8540,7 @@ namespace ts { // type of T. function getContextualTypeForElementExpression(node: Expression): Type { const arrayLiteral = node.parent; - const type = getContextualType(arrayLiteral); + const type = getApparentTypeOfContextualType(arrayLiteral); if (type) { const index = indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) @@ -7098,34 +8556,49 @@ namespace ts { return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForJsxExpression(expr: JsxExpression | JsxSpreadAttribute): Type { - // Contextual type only applies to JSX expressions that are in attribute assignments (not in 'Children' positions) - if (expr.parent.kind === SyntaxKind.JsxAttribute) { - const attrib = expr.parent; - const attrsType = getJsxElementAttributesType(attrib.parent); + function getContextualTypeForJsxAttribute(attribute: JsxAttribute | JsxSpreadAttribute) { + const kind = attribute.kind; + const jsxElement = attribute.parent as JsxOpeningLikeElement; + const attrsType = getJsxElementAttributesType(jsxElement); + + if (attribute.kind === SyntaxKind.JsxAttribute) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } - else { - return getTypeOfPropertyOfType(attrsType, attrib.name.text); - } + return getTypeOfPropertyOfType(attrsType, (attribute as JsxAttribute).name.text); + } + else if (attribute.kind === SyntaxKind.JsxSpreadAttribute) { + return attrsType; } - if (expr.kind === SyntaxKind.JsxSpreadAttribute) { - return getJsxElementAttributesType(expr.parent); - } - - return undefined; + Debug.fail(`Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[${kind}]`); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. - function getContextualType(node: Expression): Type { - const type = getContextualTypeWorker(node); + function getApparentTypeOfContextualType(node: Expression): Type { + const type = getContextualType(node); return type && getApparentType(type); } - function getContextualTypeWorker(node: Expression): Type { + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node: Expression): Type { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; @@ -7166,8 +8639,10 @@ namespace ts { case SyntaxKind.ParenthesizedExpression: return getContextualType(parent); case SyntaxKind.JsxExpression: + return getContextualType(parent); + case SyntaxKind.JsxAttribute: case SyntaxKind.JsxSpreadAttribute: - return getContextualTypeForJsxExpression(parent); + return getContextualTypeForJsxAttribute(parent); } return undefined; } @@ -7204,7 +8679,7 @@ namespace ts { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); const type = isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) - : getContextualType(node); + : getApparentTypeOfContextualType(node); if (!type) { return undefined; } @@ -7220,7 +8695,7 @@ namespace ts { // This signature will contribute to contextual union signature signatureList = [signature]; } - else if (!compareSignatures(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypes)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { // Signatures aren't identical, do not use return undefined; } @@ -7261,19 +8736,40 @@ namespace ts { return mapper && mapper.context; } + // Return the root assignment node of an assignment target + function getAssignmentRoot(node: Node): Node { + while (node.parent.kind === SyntaxKind.ParenthesizedExpression) { + node = node.parent; + } + while (true) { + if (node.parent.kind === SyntaxKind.PropertyAssignment) { + node = node.parent.parent; + } + else if (node.parent.kind === SyntaxKind.ArrayLiteralExpression) { + node = node.parent; + } + else { + break; + } + } + const parent = node.parent; + return parent.kind === SyntaxKind.BinaryExpression && + (parent).operatorToken.kind === SyntaxKind.EqualsToken && + (parent).left === node ? parent : undefined; + } + // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. function isAssignmentTarget(node: Node): boolean { + return !!getAssignmentRoot(node); + } + + function isCompoundAssignmentTarget(node: Node) { const parent = node.parent; - if (parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.EqualsToken && (parent).left === node) { - return true; - } - if (parent.kind === SyntaxKind.PropertyAssignment) { - return isAssignmentTarget(parent.parent); - } - if (parent.kind === SyntaxKind.ArrayLiteralExpression) { - return isAssignmentTarget(parent); + if (parent.kind === SyntaxKind.BinaryExpression && (parent).left === node) { + const operator = (parent).operatorToken.kind; + return operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment; } return false; } @@ -7334,7 +8830,7 @@ namespace ts { type.pattern = node; return type; } - const contextualType = getContextualType(node); + const contextualType = getApparentTypeOfContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { const pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting @@ -7359,7 +8855,7 @@ namespace ts { } } } - return createArrayType(elementTypes.length ? getUnionType(elementTypes) : undefinedType); + return createArrayType(elementTypes.length ? getUnionType(elementTypes) : emptyArrayElementType); } function isNumericName(name: DeclarationName): boolean { @@ -7373,7 +8869,7 @@ namespace ts { } function isTypeAnyOrAllConstituentTypesHaveKind(type: Type, kind: TypeFlags): boolean { - return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); + return isTypeAny(type) || isTypeOfKind(type, kind); } function isNumericLiteralName(name: string) { @@ -7419,6 +8915,17 @@ namespace ts { return links.resolvedType; } + function getObjectLiteralIndexInfo(node: ObjectLiteralExpression, properties: Symbol[], kind: IndexKind): IndexInfo { + const propTypes: Type[] = []; + for (let i = 0; i < properties.length; i++) { + if (kind === IndexKind.String || isNumericName(node.properties[i].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + const unionType = propTypes.length ? getUnionType(propTypes) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); + } + function checkObjectLiteral(node: ObjectLiteralExpression, contextualMapper?: TypeMapper): Type { const inDestructuringPattern = isAssignmentTarget(node); // Grammar checking @@ -7426,10 +8933,13 @@ namespace ts { const propertiesTable: SymbolTable = {}; const propertiesArray: Symbol[] = []; - const contextualType = getContextualType(node); + const contextualType = getApparentTypeOfContextualType(node); const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression); let typeFlags: TypeFlags = 0; + let patternWithComputedProperties = false; + let hasComputedStringProperty = false; + let hasComputedNumberProperty = false; for (const memberDecl of node.properties) { let member = memberDecl.symbol; @@ -7458,8 +8968,11 @@ namespace ts { if (isOptional) { prop.flags |= SymbolFlags.Optional; } + if (hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } } - else if (contextualTypeHasPattern) { + else if (contextualTypeHasPattern && !(contextualType.flags & TypeFlags.ObjectLiteralPatternWithComputedProperties)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. const impliedProp = getPropertyOfType(contextualType, member.name); @@ -7491,7 +9004,15 @@ namespace ts { checkAccessorDeclaration(memberDecl); } - if (!hasDynamicName(memberDecl)) { + if (hasDynamicName(memberDecl)) { + if (isNumericName(memberDecl.name)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + } + else { propertiesTable[member.name] = member; } propertiesArray.push(member); @@ -7512,38 +9033,15 @@ namespace ts { } } - const stringIndexType = getIndexType(IndexKind.String); - const numberIndexType = getIndexType(IndexKind.Number); - const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + const stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, IndexKind.String) : undefined; + const numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, IndexKind.Number) : undefined; + const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshObjectLiteral; - result.flags |= TypeFlags.ObjectLiteral | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags); + result.flags |= TypeFlags.ObjectLiteral | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags) | (patternWithComputedProperties ? TypeFlags.ObjectLiteralPatternWithComputedProperties : 0); if (inDestructuringPattern) { result.pattern = node; } return result; - - function getIndexType(kind: IndexKind) { - if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { - const propTypes: Type[] = []; - for (let i = 0; i < propertiesArray.length; i++) { - const propertyDecl = node.properties[i]; - if (kind === IndexKind.String || isNumericName(propertyDecl.name)) { - // Do not call getSymbolOfNode(propertyDecl), as that will get the - // original symbol for the node. We actually want to get the symbol - // created by checkObjectLiteral, since that will be appropriately - // contextually typed and resolved. - const type = getTypeOfSymbol(propertiesArray[i]); - if (!contains(propTypes, type)) { - propTypes.push(type); - } - } - } - const result = propTypes.length ? getUnionType(propTypes) : undefinedType; - typeFlags |= result.flags; - return result; - } - return undefined; - } } function checkJsxSelfClosingElement(node: JsxSelfClosingElement) { @@ -7551,30 +9049,16 @@ namespace ts { return jsxElementType || anyType; } - function tagNamesAreEquivalent(lhs: EntityName, rhs: EntityName): boolean { - if (lhs.kind !== rhs.kind) { - return false; - } - - if (lhs.kind === SyntaxKind.Identifier) { - return (lhs).text === (rhs).text; - } - - return (lhs).right.text === (rhs).right.text && - tagNamesAreEquivalent((lhs).left, (rhs).left); - } - function checkJsxElement(node: JsxElement) { // Check attributes checkJsxOpeningLikeElement(node.openingElement); - // Check that the closing tag matches - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - error(node.closingElement, Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, getTextOfNode(node.openingElement.tagName)); + // Perform resolution on the closing tag so that rename/go to definition/etc work + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); } else { - // Perform resolution on the closing tag so that rename/go to definition/etc work - getJsxElementTagSymbol(node.closingElement); + checkExpression(node.closingElement.tagName); } // Check children @@ -7678,85 +9162,50 @@ namespace ts { return type; } - /// Returns the type JSX.IntrinsicElements. May return `unknownType` if that type is not present. - function getJsxIntrinsicElementsType() { - if (!jsxIntrinsicElementsType) { - jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType; + function getJsxType(name: string) { + if (jsxTypes[name] === undefined) { + return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType; } - return jsxIntrinsicElementsType; + return jsxTypes[name]; } - /// Given a JSX opening element or self-closing element, return the symbol of the property that the tag name points to if - /// this is an intrinsic tag. This might be a named - /// property of the IntrinsicElements interface, or its string indexer. - /// If this is a class-based tag (otherwise returns undefined), returns the symbol of the class - /// type or factory function. - /// Otherwise, returns unknownSymbol. - function getJsxElementTagSymbol(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - const flags: JsxFlags = JsxFlags.UnknownElement; + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { const links = getNodeLinks(node); if (!links.resolvedSymbol) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - links.resolvedSymbol = lookupIntrinsicTag(node); - } - else { - links.resolvedSymbol = lookupClassTag(node); - } - } - return links.resolvedSymbol; - - function lookupIntrinsicTag(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - const intrinsicElementsType = getJsxIntrinsicElementsType(); + const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { // Property case const intrinsicProp = getPropertyOfType(intrinsicElementsType, (node.tagName).text); if (intrinsicProp) { links.jsxFlags |= JsxFlags.IntrinsicNamedElement; - return intrinsicProp; + return links.resolvedSymbol = intrinsicProp; } // Intrinsic string indexer case const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); if (indexSignatureType) { links.jsxFlags |= JsxFlags.IntrinsicIndexedElement; - return intrinsicElementsType.symbol; + return links.resolvedSymbol = intrinsicElementsType.symbol; } // Wasn't found error(node, Diagnostics.Property_0_does_not_exist_on_type_1, (node.tagName).text, "JSX." + JsxNames.IntrinsicElements); - return unknownSymbol; + return links.resolvedSymbol = unknownSymbol; } else { if (compilerOptions.noImplicitAny) { error(node, Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); } + return links.resolvedSymbol = unknownSymbol; } } - - function lookupClassTag(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - const valueSymbol: Symbol = resolveJsxTagName(node); - - // Look up the value in the current scope - if (valueSymbol && valueSymbol !== unknownSymbol) { - links.jsxFlags |= JsxFlags.ClassElement; - if (valueSymbol.flags & SymbolFlags.Alias) { - markAliasSymbolAsReferenced(valueSymbol); - } - } - - return valueSymbol || unknownSymbol; - } - - function resolveJsxTagName(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - if (node.tagName.kind === SyntaxKind.Identifier) { - const tag = node.tagName; - const sym = getResolvedSymbol(tag); - return sym.exportSymbol || sym; - } - else { - return checkQualifiedName(node.tagName).symbol; - } - } + return links.resolvedSymbol; } /** @@ -7765,17 +9214,8 @@ namespace ts { * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node: JsxOpeningLikeElement) { - // There is no such thing as an instance type for a non-class element. This - // line shouldn't be hit. - Debug.assert(!!(getNodeLinks(node).jsxFlags & JsxFlags.ClassElement), "Should not call getJsxElementInstanceType on non-class Element"); + const valueType = checkExpression(node.tagName); - const classSymbol = getJsxElementTagSymbol(node); - if (classSymbol === unknownSymbol) { - // Couldn't find the class instance type. Error has already been issued - return anyType; - } - - const valueType = getTypeOfSymbol(classSymbol); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -7794,22 +9234,14 @@ namespace ts { } } - const returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); - - // Issue an error if this return type isn't assignable to JSX.ElementClass - const elemClassType = getJsxGlobalElementClassType(); - if (elemClassType) { - checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - - return returnType; + return getUnionType(signatures.map(getReturnTypeOfSignature)); } /// e.g. "props" for React.d.ts, - /// or 'undefined' if ElementAttributesPropery doesn't exist (which means all + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all /// non-intrinsic elements' attributes type is 'any'), /// or '' if it has 0 properties (which means every - /// non-instrinsic elements' attributes type is the element instance type) + /// non-intrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { // JSX const jsxNamespace = getGlobalSymbol(JsxNames.JSX, SymbolFlags.Namespace, /*diagnosticMessage*/undefined); @@ -7817,7 +9249,7 @@ namespace ts { const attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, SymbolFlags.Type); // JSX.ElementAttributesProperty [type] const attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); - // The properites of JSX.ElementAttributesProperty + // The properties of JSX.ElementAttributesProperty const attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { @@ -7849,11 +9281,46 @@ namespace ts { function getJsxElementAttributesType(node: JsxOpeningLikeElement): Type { const links = getNodeLinks(node); if (!links.resolvedJsxType) { - const sym = getJsxElementTagSymbol(node); - - if (links.jsxFlags & JsxFlags.ClassElement) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + const symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & JsxFlags.IntrinsicNamedElement) { + return links.resolvedJsxType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & JsxFlags.IntrinsicIndexedElement) { + return links.resolvedJsxType = getIndexInfoOfSymbol(symbol, IndexKind.String).type; + } + } + else { + // Get the element instance type (the result of newing or invoking this tag) const elemInstanceType = getJsxElementInstanceType(node); + const elemClassType = getJsxGlobalElementClassType(); + + if (!elemClassType || !isTypeAssignableTo(elemInstanceType, elemClassType)) { + // Is this is a stateless function component? See if its single signature's return type is + // assignable to the JSX Element Type + if (jsxElementType) { + const elemType = checkExpression(node.tagName); + const callSignatures = elemType && getSignaturesOfType(elemType, SignatureKind.Call); + const callSignature = callSignatures && callSignatures.length > 0 && callSignatures[0]; + const callReturnType = callSignature && getReturnTypeOfSignature(callSignature); + let paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) { + // Intersect in JSX.IntrinsicAttributes if it exists + const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return links.resolvedJsxType = paramType; + } + } + } + + // Issue an error if this return type isn't assignable to JSX.ElementClass + if (elemClassType) { + checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } @@ -7875,27 +9342,41 @@ namespace ts { return links.resolvedJsxType = emptyObjectType; } else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + // Props is of type 'any' or unknown return links.resolvedJsxType = attributesType; } - else if (!(attributesType.flags & TypeFlags.ObjectType)) { - error(node.tagName, Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType)); + else if (attributesType.flags & TypeFlags.Union) { + // Props cannot be a union type + error(node.tagName, Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return links.resolvedJsxType = anyType; } else { - return links.resolvedJsxType = attributesType; + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + let apparentAttributesType = attributesType; + const intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + const typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + + const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + + return links.resolvedJsxType = apparentAttributesType; } } } - else if (links.jsxFlags & JsxFlags.IntrinsicNamedElement) { - return links.resolvedJsxType = getTypeOfSymbol(sym); - } - else if (links.jsxFlags & JsxFlags.IntrinsicIndexedElement) { - return links.resolvedJsxType = getIndexTypeOfSymbol(sym, IndexKind.String); - } - else { - // Resolution failed, so we don't know - return links.resolvedJsxType = anyType; - } + + return links.resolvedJsxType = unknownType; } return links.resolvedJsxType; @@ -7921,7 +9402,7 @@ namespace ts { /// Returns all the properties of the Jsx.IntrinsicElements interface function getJsxIntrinsicTagNames(): Symbol[] { - const intrinsics = getJsxIntrinsicElementsType(); + const intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } @@ -7942,14 +9423,13 @@ namespace ts { checkGrammarJsxElement(node); checkJsxPreconditions(node); - // If we're compiling under --jsx react, the symbol 'React' should - // be marked as 'used' so we don't incorrectly elide its import. And if there - // is no 'React' symbol in scope, we should issue an error. - if (compilerOptions.jsx === JsxEmit.React) { - const reactSym = resolveName(node.tagName, "React", SymbolFlags.Value, Diagnostics.Cannot_find_name_0, "React"); - if (reactSym) { - getSymbolLinks(reactSym).referenced = true; - } + // The reactNamespace symbol should be marked as 'used' so we don't incorrectly elide its import. And if there + // is no reactNamespace symbol in scope when targeting React emit, we should issue an error. + const reactRefErr = compilerOptions.jsx === JsxEmit.React ? Diagnostics.Cannot_find_name_0 : undefined; + const reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + const reactSym = resolveName(node.tagName, reactNamespace, SymbolFlags.Value, reactRefErr, reactNamespace); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; } const targetAttributesType = getJsxElementAttributesType(node); @@ -8013,15 +9493,13 @@ namespace ts { * @param type The type of left. * @param prop The symbol for the right hand side of the property access. */ - function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean { + function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName | VariableLikeDeclaration, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean { const flags = getDeclarationFlagsFromSymbol(prop); - const declaringClass = getDeclaredTypeOfSymbol(prop.parent); - + const declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); + const errorNode = node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.VariableDeclaration ? + (node).name : + (node).right; if (left.kind === SyntaxKind.SuperKeyword) { - const errorNode = node.kind === SyntaxKind.PropertyAccessExpression ? - (node).name : - (node).right; - // 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, @@ -8029,7 +9507,7 @@ namespace ts { // - 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 (getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) { + if (languageVersion < ScriptTarget.ES6 && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. @@ -8054,15 +9532,12 @@ namespace ts { } // Property is known to be private or protected at this point - // Get the declaring and enclosing class instance types - const enclosingClassDeclaration = getContainingClass(node); - const enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; - - // Private property is accessible if declaring and enclosing class are the same + // Private property is accessible if the property is within the declaring class if (flags & NodeFlags.Private) { - if (declaringClass !== enclosingClass) { - error(node, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); + const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; } return true; @@ -8074,9 +9549,16 @@ namespace ts { if (left.kind === SyntaxKind.SuperKeyword) { return true; } - // A protected property is accessible in the declaring class and classes derived from it - if (!enclosingClass || !hasBaseType(enclosingClass, declaringClass)) { - error(node, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); + + // Get the enclosing class that has the declaring class as its base type + const enclosingClass = forEachEnclosingClass(node, enclosingDeclaration => { + const enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return hasBaseType(enclosingClass, declaringClass) ? enclosingClass : undefined; + }); + + // A protected property is accessible if the property is within the declaring class or classes derived from it + if (!enclosingClass) { + error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); return false; } // No further restrictions for static properties @@ -8091,12 +9573,21 @@ namespace ts { // TODO: why is the first part of this check here? if (!(getTargetType(type).flags & (TypeFlags.Class | TypeFlags.Interface) && hasBaseType(type, enclosingClass))) { - error(node, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; } return true; } + function checkNonNullExpression(node: Expression | QualifiedName) { + const type = checkExpression(node); + if (strictNullChecks && getNullableKind(type)) { + error(node, Diagnostics.Object_is_possibly_null_or_undefined); + return getNonNullableType(type); + } + return type; + } + function checkPropertyAccessExpression(node: PropertyAccessExpression) { return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); } @@ -8106,7 +9597,7 @@ namespace ts { } function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { - const type = checkExpression(left); + const type = checkNonNullExpression(left); if (isTypeAny(type)) { return type; } @@ -8129,7 +9620,10 @@ namespace ts { if (prop.parent && prop.parent.flags & SymbolFlags.Class) { checkClassPropertyAccess(node, left, apparentType, prop); } - return getTypeOfSymbol(prop); + + const propType = getTypeOfSymbol(prop); + return node.kind === SyntaxKind.PropertyAccessExpression && prop.flags & SymbolFlags.Property ? + getNarrowedTypeOfReference(propType, node) : propType; } function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean { @@ -8147,10 +9641,60 @@ namespace ts { return true; } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node: ForInStatement): Symbol { + const initializer = node.initializer; + if (initializer.kind === SyntaxKind.VariableDeclarationList) { + const variable = (initializer).declarations[0]; + if (variable && !isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === SyntaxKind.Identifier) { + return getResolvedSymbol(initializer); + } + return undefined; + } + + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type: Type) { + return getIndexTypeOfType(type, IndexKind.Number) && !getIndexTypeOfType(type, IndexKind.String); + } + + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr: Expression) { + const e = skipParenthesizedNodes(expr); + if (e.kind === SyntaxKind.Identifier) { + const symbol = getResolvedSymbol(e); + if (symbol.flags & SymbolFlags.Variable) { + let child: Node = expr; + let node = expr.parent; + while (node) { + if (node.kind === SyntaxKind.ForInStatement && + child === (node).statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(checkExpression((node).expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node: ElementAccessExpression): Type { // Grammar checking if (!node.argumentExpression) { - const sourceFile = getSourceFile(node); + const sourceFile = getSourceFileOfNode(node); if (node.parent.kind === SyntaxKind.NewExpression && (node.parent).expression === node) { const start = skipTrivia(sourceFile.text, node.expression.end); const end = node.end; @@ -8164,7 +9708,7 @@ namespace ts { } // Obtain base constraint such that we can bail out if the constraint is an unknown type - const objectType = getApparentType(checkExpression(node.expression)); + const objectType = getApparentType(checkNonNullExpression(node.expression)); const indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; if (objectType === unknownType) { @@ -8207,22 +9751,26 @@ namespace ts { if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbol)) { // Try to use a number indexer. - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.NumberLike)) { - const numberIndexType = getIndexTypeOfType(objectType, IndexKind.Number); - if (numberIndexType) { - return numberIndexType; + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.NumberLike) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { + const numberIndexInfo = getIndexInfoOfType(objectType, IndexKind.Number); + if (numberIndexInfo) { + getNodeLinks(node).resolvedIndexInfo = numberIndexInfo; + return numberIndexInfo.type; } } // Try to use string indexing. - const stringIndexType = getIndexTypeOfType(objectType, IndexKind.String); - if (stringIndexType) { - return stringIndexType; + const stringIndexInfo = getIndexInfoOfType(objectType, IndexKind.String); + if (stringIndexInfo) { + getNodeLinks(node).resolvedIndexInfo = stringIndexInfo; + return stringIndexInfo.type; } // Fall back to any. if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { - error(node, Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); + error(node, getIndexTypeOfType(objectType, IndexKind.Number) ? + Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : + Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } return anyType; @@ -8474,7 +10022,7 @@ namespace ts { if (type.flags & TypeFlags.ObjectType) { const resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && - resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) { + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { return resolved.callSignatures[0]; } } @@ -8493,7 +10041,7 @@ namespace ts { function inferTypeArguments(node: CallLikeExpression, signature: Signature, args: Expression[], excludeArgument: boolean[], context: InferenceContext): void { const typeParameters = signature.typeParameters; - const inferenceMapper = createInferenceMapper(context); + const inferenceMapper = getInferenceMapper(context); // Clear out all the inference results from the last time inferTypeArguments was called on this context for (let i = 0; i < typeParameters.length; i++) { @@ -8547,7 +10095,7 @@ namespace ts { // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. if (excludeArgument) { for (let i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exlusion value is always undefined + // No need to check for omitted args and template expressions, their exclusion value is always undefined if (excludeArgument[i] === false) { const arg = args[i]; const paramType = getTypeAtPosition(signature, i); @@ -8559,14 +10107,11 @@ namespace ts { getInferredTypes(context); } - function checkTypeArguments(signature: Signature, typeArguments: TypeNode[], typeArgumentResultTypes: Type[], reportErrors: boolean, headMessage?: DiagnosticMessage): boolean { + function checkTypeArguments(signature: Signature, typeArgumentNodes: TypeNode[], typeArgumentTypes: Type[], reportErrors: boolean, headMessage?: DiagnosticMessage): boolean { const typeParameters = signature.typeParameters; let typeArgumentsAreAssignable = true; + let mapper: TypeMapper; for (let i = 0; i < typeParameters.length; i++) { - const typeArgNode = typeArguments[i]; - const typeArgument = getTypeFromTypeNode(typeArgNode); - // Do not push on this array! It has a preallocated length - typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable /* so far */) { const constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { @@ -8576,17 +10121,19 @@ namespace ts { errorInfo = chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); typeArgumentHeadMessage = headMessage; } - + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + const typeArgument = typeArgumentTypes[i]; typeArgumentsAreAssignable = checkTypeAssignableTo( typeArgument, - constraint, - reportErrors ? typeArgNode : undefined, + getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), + reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); } } } - return typeArgumentsAreAssignable; } @@ -8604,7 +10151,7 @@ namespace ts { // for the argument. In that case, we should check the argument. if (argType === undefined) { argType = arg.kind === SyntaxKind.StringLiteral && !reportErrors - ? getStringLiteralType(arg) + ? getStringLiteralTypeForText((arg).text) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } @@ -8799,11 +10346,11 @@ namespace ts { case SyntaxKind.Identifier: case SyntaxKind.NumericLiteral: case SyntaxKind.StringLiteral: - return getStringLiteralType(element.name); + return getStringLiteralTypeForText((element.name).text); case SyntaxKind.ComputedPropertyName: const nameType = checkComputedPropertyName(element.name); - if (allConstituentTypesHaveKind(nameType, TypeFlags.ESSymbol)) { + if (isTypeOfKind(nameType, TypeFlags.ESSymbol)) { return nameType; } else { @@ -8829,7 +10376,7 @@ namespace ts { */ function getEffectiveDecoratorThirdArgumentType(node: Node) { // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a paramter decorator + // or its `parameterIndex` for a parameter decorator if (node.kind === SyntaxKind.ClassDeclaration) { Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; @@ -9042,7 +10589,8 @@ namespace ts { } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, (node).typeArguments, [], /*reportErrors*/ true, headMessage); + const typeArguments = (node).typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments, map(typeArguments, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -9109,7 +10657,7 @@ namespace ts { if (candidate.typeParameters) { let typeArgumentTypes: Type[]; if (typeArguments) { - typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentTypes = map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -9167,13 +10715,15 @@ namespace ts { // 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. const baseTypeNode = getClassExtendsHeritageClauseElement(getContainingClass(node)); - const baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); - return resolveCall(node, baseConstructors, candidatesOutArray); + if (baseTypeNode) { + const baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); + } } return resolveUntypedCall(node); } - const funcType = checkExpression(node.expression); + const funcType = checkNonNullExpression(node.expression); const apparentType = getApparentType(funcType); if (apparentType === unknownType) { @@ -9196,7 +10746,7 @@ namespace ts { // We exclude union types because we may have a union of function types that happen to have // no common signatures. 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 + // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== unknownType && node.typeArguments) { error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); @@ -9226,7 +10776,7 @@ namespace ts { } } - let expressionType = checkExpression(node.expression); + let expressionType = checkNonNullExpression(node.expression); // If expressionType's apparent type(section 3.8.1) is an object type with one or // more construct signatures, the expression is processed in the same manner as a @@ -9265,6 +10815,9 @@ namespace ts { // that the user will not add any. const constructSignatures = getSignaturesOfType(expressionType, SignatureKind.Construct); if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } return resolveCall(node, constructSignatures, candidatesOutArray); } @@ -9285,6 +10838,36 @@ namespace ts { return resolveErrorCall(node); } + function isConstructorAccessible(node: NewExpression, signature: Signature) { + if (!signature || !signature.declaration) { + return true; + } + + const declaration = signature.declaration; + const flags = declaration.flags; + + // Public constructor is accessible. + if (!(flags & (NodeFlags.Private | NodeFlags.Protected))) { + return true; + } + + const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + const declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + + // A private or protected constructor can only be instantiated within it's own class + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + if (flags & NodeFlags.Private) { + error(node, Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (flags & NodeFlags.Protected) { + error(node, Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + + return true; + } + function resolveTaggedTemplateExpression(node: TaggedTemplateExpression, candidatesOutArray: Signature[]): Signature { const tagType = checkExpression(node.tag); const apparentType = getApparentType(tagType); @@ -9387,6 +10970,14 @@ namespace ts { return links.resolvedSignature; } + function getInferredClassType(symbol: Symbol) { + const links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } + /** * Syntactically and semantically checks a call or new expression. * @param node The call/new expression to be checked. @@ -9397,24 +10988,39 @@ namespace ts { checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); const signature = getResolvedSignature(node); + if (node.expression.kind === SyntaxKind.SuperKeyword) { return voidType; } + if (node.kind === SyntaxKind.NewExpression) { const declaration = signature.declaration; if (declaration && declaration.kind !== SyntaxKind.Constructor && declaration.kind !== SyntaxKind.ConstructSignature && - declaration.kind !== SyntaxKind.ConstructorType) { + declaration.kind !== SyntaxKind.ConstructorType && + !isJSDocConstructSignature(declaration)) { - // When resolved signature is a call signature (and not a construct signature) the result type is any - if (compilerOptions.noImplicitAny) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + const funcSymbol = checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & SymbolFlags.Function)) { + return getInferredClassType(funcSymbol); + } + else if (compilerOptions.noImplicitAny) { error(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; } } + + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (isInJavaScriptFile(node) && isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + return getReturnTypeOfSignature(signature); } @@ -9427,7 +11033,6 @@ namespace ts { const targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { const widenedType = getWidenedType(exprType); - if (!isTypeComparableTo(targetType, widenedType)) { checkTypeComparableTo(exprType, targetType, node, Diagnostics.Type_0_cannot_be_converted_to_type_1); } @@ -9435,10 +11040,25 @@ namespace ts { return targetType; } + function checkNonNullAssertion(node: NonNullExpression) { + return getNonNullableType(checkExpression(node.expression)); + } + + function getTypeOfParameter(symbol: Symbol) { + const type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + const declaration = symbol.valueDeclaration; + if (declaration && (declaration).initializer) { + return addNullableKind(type, TypeFlags.Undefined); + } + } + return type; + } + function getTypeAtPosition(signature: Signature, pos: number): Type { return signature.hasRestParameter ? - pos < signature.parameters.length - 1 ? getTypeOfSymbol(signature.parameters[pos]) : getRestTypeOfSignature(signature) : - pos < signature.parameters.length ? getTypeOfSymbol(signature.parameters[pos]) : anyType; + pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : + pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; } function assignContextualParameterTypes(signature: Signature, context: Signature, mapper: TypeMapper) { @@ -9510,6 +11130,15 @@ namespace ts { } } + function getReturnTypeFromJSDocComment(func: SignatureDeclaration | FunctionDeclaration): Type { + const returnTag = getJSDocReturnTag(func); + if (returnTag && returnTag.typeExpression) { + return getTypeFromTypeNode(returnTag.typeExpression.type); + } + + return undefined; + } + function createPromiseType(promisedType: Type): Type { // creates a `Promise` type where `T` is the promisedType argument const globalPromiseType = getGlobalPromiseType(); @@ -9555,7 +11184,8 @@ namespace ts { } } else { - types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper, isAsync); + const hasImplicitReturn = !!(func.flags & NodeFlags.HasImplicitReturn); + types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper, isAsync, hasImplicitReturn); if (types.length === 0) { if (isAsync) { // For an async function, the return type will not be void, but rather a Promise for void. @@ -9582,7 +11212,8 @@ namespace ts { } else { error(func, Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience + return getUnionType(types); } } @@ -9634,9 +11265,9 @@ namespace ts { return aggregatedTypes; } - function checkAndAggregateReturnExpressionTypes(body: Block, contextualMapper?: TypeMapper, isAsync?: boolean): Type[] { + function checkAndAggregateReturnExpressionTypes(body: Block, contextualMapper: TypeMapper, isAsync: boolean, hasImplicitReturn: boolean): Type[] { const aggregatedTypes: Type[] = []; - + let hasOmittedExpressions = false; forEachReturnStatement(body, returnStatement => { const expr = returnStatement.expression; if (expr) { @@ -9648,45 +11279,73 @@ namespace ts { // the native Promise type by the caller. type = checkAwaitedType(type, body.parent, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (!contains(aggregatedTypes, type)) { aggregatedTypes.push(type); } } + else { + hasOmittedExpressions = true; + } }); - + if (strictNullChecks && aggregatedTypes.length && (hasOmittedExpressions || hasImplicitReturn)) { + if (!contains(aggregatedTypes, undefinedType)) { + aggregatedTypes.push(undefinedType); + } + } return aggregatedTypes; } - // TypeScript Specification 1.0 (6.3) - July 2014 - // An explicitly typed function whose return type isn't the Void or the Any type - // must have at least one return statement somewhere in its body. - // An exception to this rule is if the function implementation consists of a single 'throw' statement. + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func: FunctionLikeDeclaration, returnType: Type): void { if (!produceDiagnostics) { return; } - // Functions that return 'void' or 'any' don't need any return expressions. - if (returnType === voidType || isTypeAny(returnType)) { + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, TypeFlags.Any | TypeFlags.Void)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - // also if HasImplicitReturnValue flags is not set this means that all codepaths in function body end with return of throw + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw if (nodeIsMissing(func.body) || func.body.kind !== SyntaxKind.Block || !(func.flags & NodeFlags.HasImplicitReturn)) { return; } - if (func.flags & NodeFlags.HasExplicitReturn) { - if (compilerOptions.noImplicitReturns) { - error(func.type, Diagnostics.Not_all_code_paths_return_a_value); - } - } - else { - // This function does not conform to the specification. + const hasExplicitReturn = func.flags & NodeFlags.HasExplicitReturn; + + if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present error(func.type, Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(func.type, Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + if (!hasExplicitReturn) { + return; + } + const inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(func.type || func, Diagnostics.Not_all_code_paths_return_a_value); + } } function checkFunctionExpressionOrObjectLiteralMethod(node: FunctionExpression | MethodDeclaration, contextualMapper?: TypeMapper): Type { @@ -9700,14 +11359,10 @@ namespace ts { // The identityMapper object is used to indicate that function expressions are wildcards if (contextualMapper === identityMapper && isContextSensitive(node)) { + checkNodeDeferred(node); return anyFunctionType; } - const isAsync = isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } - const links = getNodeLinks(node); const type = getTypeOfSymbol(node.symbol); const contextSensitive = isContextSensitive(node); @@ -9739,6 +11394,7 @@ namespace ts { if (!contextChecked) { checkSignatureDeclaration(node); + checkNodeDeferred(node); } } } @@ -9751,22 +11407,14 @@ namespace ts { return type; } - function checkFunctionExpressionOrObjectLiteralMethodBody(node: FunctionExpression | MethodDeclaration) { + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node: ArrowFunction | FunctionExpression | MethodDeclaration) { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); const isAsync = isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } - - const returnType = node.type && getTypeFromTypeNode(node.type); - let promisedType: Type; - if (returnType && isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - - if (returnType && !node.asteriskToken) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + const returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + if (!node.asteriskToken) { + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { @@ -9789,17 +11437,15 @@ namespace ts { // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. const exprType = checkExpression(node.body); - if (returnType) { + if (returnOrPromisedType) { if (isAsync) { const awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); - checkTypeAssignableTo(awaitedType, promisedType, node.body); + checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } else { - checkTypeAssignableTo(exprType, returnType, node.body); + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } - - checkFunctionAndClassExpressionBodies(node.body); } } } @@ -9812,81 +11458,78 @@ namespace ts { return true; } - function checkReferenceExpression(n: Node, invalidReferenceMessage: DiagnosticMessage, constantVariableMessage: DiagnosticMessage): boolean { - function findSymbol(n: Node): Symbol { - const symbol = getNodeLinks(n).resolvedSymbol; - // Because we got the symbol from the resolvedSymbol property, it might be of kind - // SymbolFlags.ExportValue. In this case it is necessary to get the actual export - // symbol, which will have the correct flags set on it. - return symbol && getExportSymbolOfValueSymbolIfExported(symbol); - } + function isReadonlySymbol(symbol: Symbol): boolean { + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + return symbol.flags & SymbolFlags.Property && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Readonly) !== 0 || + symbol.flags & SymbolFlags.Variable && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0 || + symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) || + (symbol.flags & SymbolFlags.EnumMember) !== 0; + } - function isReferenceOrErrorExpression(n: Node): boolean { - // TypeScript 1.0 spec (April 2014): - // Expressions are classified as values or references. - // References are the subset of expressions that are permitted as the target of an assignment. - // Specifically, references are combinations of identifiers(section 4.3), parentheses(section 4.7), - // and property accesses(section 4.10). - // All other expression constructs described in this chapter are classified as values. - switch (n.kind) { - case SyntaxKind.Identifier: { - const symbol = findSymbol(n); - // TypeScript 1.0 spec (April 2014): 4.3 - // An identifier expression that references a variable or parameter is classified as a reference. - // 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 & SymbolFlags.Variable) !== 0; + function isReferenceToReadonlyEntity(expr: Expression, symbol: Symbol): boolean { + if (isReadonlySymbol(symbol)) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & SymbolFlags.Property && + (expr.kind === SyntaxKind.PropertyAccessExpression || expr.kind === SyntaxKind.ElementAccessExpression) && + (expr as PropertyAccessExpression | ElementAccessExpression).expression.kind === SyntaxKind.ThisKeyword) { + const func = getContainingFunction(expr); + return !(func && func.kind === SyntaxKind.Constructor && func.parent === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + + function isReferenceThroughNamespaceImport(expr: Expression): boolean { + if (expr.kind === SyntaxKind.PropertyAccessExpression || expr.kind === SyntaxKind.ElementAccessExpression) { + const node = skipParenthesizedNodes((expr as PropertyAccessExpression | ElementAccessExpression).expression); + if (node.kind === SyntaxKind.Identifier) { + const symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & SymbolFlags.Alias) { + const declaration = getDeclarationOfAliasSymbol(symbol); + return declaration && declaration.kind === SyntaxKind.NamespaceImport; } - case SyntaxKind.PropertyAccessExpression: { - const 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 & ~SymbolFlags.EnumMember) !== 0; - } - case SyntaxKind.ElementAccessExpression: - // old compiler doesn't check indexed access - return true; - case SyntaxKind.ParenthesizedExpression: - return isReferenceOrErrorExpression((n).expression); - default: - return false; } } + return false; + } - function isConstVariableReference(n: Node): boolean { - switch (n.kind) { - case SyntaxKind.Identifier: - case SyntaxKind.PropertyAccessExpression: { - const symbol = findSymbol(n); - return symbol && (symbol.flags & SymbolFlags.Variable) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0; - } - case SyntaxKind.ElementAccessExpression: { - const index = (n).argumentExpression; - const symbol = findSymbol((n).expression); - if (symbol && index && index.kind === SyntaxKind.StringLiteral) { - const name = (index).text; - const prop = getPropertyOfType(getTypeOfSymbol(symbol), name); - return prop && (prop.flags & SymbolFlags.Variable) !== 0 && (getDeclarationFlagsFromSymbol(prop) & NodeFlags.Const) !== 0; - } + function checkReferenceExpression(expr: Expression, invalidReferenceMessage: DiagnosticMessage, constantVariableMessage: DiagnosticMessage): boolean { + // References are combinations of identifiers, parentheses, and property accesses. + const node = skipParenthesizedNodes(expr); + if (node.kind !== SyntaxKind.Identifier && node.kind !== SyntaxKind.PropertyAccessExpression && node.kind !== SyntaxKind.ElementAccessExpression) { + error(expr, invalidReferenceMessage); + return false; + } + // Because we get the symbol from the resolvedSymbol property, it might be of kind + // SymbolFlags.ExportValue. In this case it is necessary to get the actual export + // symbol, which will have the correct flags set on it. + const links = getNodeLinks(node); + const symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol) { + if (symbol !== unknownSymbol && symbol !== argumentsSymbol) { + // Only variables (and not functions, classes, namespaces, enum objects, or enum members) + // are considered references when referenced using a simple identifier. + if (node.kind === SyntaxKind.Identifier && !(symbol.flags & SymbolFlags.Variable)) { + error(expr, invalidReferenceMessage); return false; } - case SyntaxKind.ParenthesizedExpression: - return isConstVariableReference((n).expression); - default: + if (isReferenceToReadonlyEntity(node, symbol) || isReferenceThroughNamespaceImport(node)) { + error(expr, constantVariableMessage); return false; + } } } - - if (!isReferenceOrErrorExpression(n)) { - error(n, invalidReferenceMessage); - return false; + else if (node.kind === SyntaxKind.ElementAccessExpression) { + if (links.resolvedIndexInfo && links.resolvedIndexInfo.isReadonly) { + error(expr, constantVariableMessage); + return false; + } } - - if (isConstVariableReference(n)) { - error(n, constantVariableMessage); - return false; - } - return true; } @@ -9908,7 +11551,7 @@ namespace ts { function checkAwaitExpression(node: AwaitExpression): Type { // Grammar checking if (produceDiagnostics) { - if (!(node.parserContextFlags & ParserContextFlags.Await)) { + if (!(node.flags & NodeFlags.AwaitContext)) { grammarErrorOnFirstToken(node, Diagnostics.await_expression_is_only_allowed_within_an_async_function); } @@ -9927,7 +11570,7 @@ namespace ts { case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: case SyntaxKind.TildeToken: - if (someConstituentTypeHasKind(operandType, TypeFlags.ESSymbol)) { + if (maybeTypeOfKind(operandType, TypeFlags.ESSymbol)) { error(node.operand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(node.operator)); } return numberType; @@ -9935,12 +11578,13 @@ namespace ts { return booleanType; case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: - const ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + const ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), + Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); } return numberType; } @@ -9949,48 +11593,58 @@ namespace ts { function checkPostfixUnaryExpression(node: PostfixUnaryExpression): Type { const operandType = checkExpression(node.operand); - const ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + const ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), + Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant_or_a_read_only_property); } return numberType; } - // Just like isTypeOfKind below, except that it returns true if *any* constituent - // has this kind. - function someConstituentTypeHasKind(type: Type, kind: TypeFlags): boolean { + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type: Type, kind: TypeFlags): boolean { if (type.flags & kind) { return true; } if (type.flags & TypeFlags.UnionOrIntersection) { const types = (type).types; - for (const current of types) { - if (current.flags & kind) { + for (const t of types) { + if (maybeTypeOfKind(t, kind)) { return true; } } - return false; } return false; } - // Return true if type has the given flags, or is a union or intersection type composed of types that all have those flags. - function allConstituentTypesHaveKind(type: Type, kind: TypeFlags): boolean { + // Return true if type is of the given kind. A union type is of a given kind if all constituent types + // are of the given kind. An intersection type is of a given kind if at least one constituent type is + // of the given kind. + function isTypeOfKind(type: Type, kind: TypeFlags): boolean { if (type.flags & kind) { return true; } - if (type.flags & TypeFlags.UnionOrIntersection) { + if (type.flags & TypeFlags.Union) { const types = (type).types; - for (const current of types) { - if (!(current.flags & kind)) { + for (const t of types) { + if (!isTypeOfKind(t, kind)) { return false; } } return true; } + if (type.flags & TypeFlags.Intersection) { + const types = (type).types; + for (const t of types) { + if (isTypeOfKind(t, kind)) { + return true; + } + } + } return false; } @@ -10008,7 +11662,7 @@ namespace 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, TypeFlags.Primitive)) { + if (isTypeOfKind(leftType, TypeFlags.Primitive)) { error(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 @@ -10036,19 +11690,27 @@ namespace ts { const properties = node.properties; for (const p of properties) { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { - // TODO(andersh): Computed property support - const name = (p).name; + const name = (p).name; + if (name.kind === SyntaxKind.ComputedPropertyName) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + continue; + } + + const text = getTextOfPropertyName(name); const type = isTypeAny(sourceType) ? sourceType - : getTypeOfPropertyOfType(sourceType, name.text) || - isNumericLiteralName(name.text) && getIndexTypeOfType(sourceType, IndexKind.Number) || + : getTypeOfPropertyOfType(sourceType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(sourceType, IndexKind.Number) || getIndexTypeOfType(sourceType, IndexKind.String); if (type) { if (p.kind === SyntaxKind.ShorthandPropertyAssignment) { checkDestructuringAssignment(p, type); } else { - checkDestructuringAssignment((p).initializer || name, type); + // non-shorthand property assignments should always have initializers + checkDestructuringAssignment((p).initializer, type); } } else { @@ -10137,7 +11799,7 @@ namespace ts { function checkReferenceAssignment(target: Expression, sourceType: Type, contextualMapper?: TypeMapper): Type { const targetType = checkExpression(target, contextualMapper); - if (checkReferenceExpression(target, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant)) { + if (checkReferenceExpression(target, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property)) { checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); } return sourceType; @@ -10183,8 +11845,11 @@ namespace ts { // as having the primitive type Number. If one operand is the null or undefined value, // it is treated as having the type of the other operand. // The result is always of the Number primitive type. - if (leftType.flags & (TypeFlags.Undefined | TypeFlags.Null)) leftType = rightType; - if (rightType.flags & (TypeFlags.Undefined | TypeFlags.Null)) rightType = leftType; + if (leftType.flags & TypeFlags.Nullable) leftType = rightType; + if (rightType.flags & TypeFlags.Nullable) rightType = leftType; + + leftType = getNonNullableType(leftType); + rightType = getNonNullableType(rightType); let suggestedOperator: SyntaxKind; // if a user tries to apply a bitwise operator to 2 boolean operands @@ -10211,17 +11876,20 @@ namespace ts { // or at least one of the operands to be of type Any or the String primitive type. // If one operand is the null or undefined value, it is treated as having the type of the other operand. - if (leftType.flags & (TypeFlags.Undefined | TypeFlags.Null)) leftType = rightType; - if (rightType.flags & (TypeFlags.Undefined | TypeFlags.Null)) rightType = leftType; + if (leftType.flags & TypeFlags.Nullable) leftType = rightType; + if (rightType.flags & TypeFlags.Nullable) rightType = leftType; + + leftType = getNonNullableType(leftType); + rightType = getNonNullableType(rightType); let resultType: Type; - if (allConstituentTypesHaveKind(leftType, TypeFlags.NumberLike) && allConstituentTypesHaveKind(rightType, TypeFlags.NumberLike)) { + if (isTypeOfKind(leftType, TypeFlags.NumberLike) && isTypeOfKind(rightType, TypeFlags.NumberLike)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } else { - if (allConstituentTypesHaveKind(leftType, TypeFlags.StringLike) || allConstituentTypesHaveKind(rightType, TypeFlags.StringLike)) { + if (isTypeOfKind(leftType, TypeFlags.StringLike) || isTypeOfKind(rightType, TypeFlags.StringLike)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -10267,9 +11935,9 @@ namespace ts { case SyntaxKind.InKeyword: return checkInExpression(left, right, leftType, rightType); case SyntaxKind.AmpersandAmpersandToken: - return rightType; + return addNullableKind(rightType, getNullableKind(leftType)); case SyntaxKind.BarBarToken: - return getUnionType([leftType, rightType]); + return getUnionType([getNonNullableType(leftType), rightType]); case SyntaxKind.EqualsToken: checkAssignmentOperator(rightType); return getRegularTypeOfObjectLiteral(rightType); @@ -10280,8 +11948,8 @@ namespace ts { // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator: SyntaxKind): boolean { const offendingSymbolOperand = - someConstituentTypeHasKind(leftType, TypeFlags.ESSymbol) ? left : - someConstituentTypeHasKind(rightType, TypeFlags.ESSymbol) ? right : + maybeTypeOfKind(leftType, TypeFlags.ESSymbol) ? left : + maybeTypeOfKind(rightType, TypeFlags.ESSymbol) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(operator)); @@ -10315,7 +11983,9 @@ namespace ts { // requires VarExpr to be classified as a reference // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) // and the type of the non - compound operation to be assignable to the type of VarExpr. - const ok = checkReferenceExpression(left, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + const ok = checkReferenceExpression(left, + Diagnostics.Invalid_left_hand_side_of_assignment_expression, + Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant_or_a_read_only_property); // Use default messages if (ok) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported @@ -10350,7 +12020,7 @@ namespace ts { function checkYieldExpression(node: YieldExpression): Type { // Grammar checking if (produceDiagnostics) { - if (!(node.parserContextFlags & ParserContextFlags.Yield) || isYieldExpressionInClass(node)) { + if (!(node.flags & NodeFlags.YieldContext) || isYieldExpressionInClass(node)) { grammarErrorOnFirstToken(node, Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); } @@ -10396,6 +12066,15 @@ namespace ts { return getUnionType([type1, type2]); } + function checkStringLiteralExpression(node: StringLiteral): Type { + const contextualType = getContextualType(node); + if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + return getStringLiteralTypeForText(node.text); + } + + return stringType; + } + function checkTemplateExpression(node: TemplateExpression): Type { // We just want to check each expressions, but we are unconcerned with // the type of each expression, as any value may be coerced into a string. @@ -10455,7 +12134,7 @@ namespace ts { if (isInferentialContext(contextualMapper)) { const signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { - const contextualType = getContextualType(node); + const contextualType = getApparentTypeOfContextualType(node); if (contextualType) { const contextualSignature = getSingleCallSignature(contextualType); if (contextualSignature && !contextualSignature.typeParameters) { @@ -10526,6 +12205,7 @@ namespace ts { case SyntaxKind.TemplateExpression: return checkTemplateExpression(node); case SyntaxKind.StringLiteral: + return checkStringLiteralExpression(node); case SyntaxKind.NoSubstitutionTemplateLiteral: return stringType; case SyntaxKind.RegularExpressionLiteral: @@ -10555,6 +12235,8 @@ namespace ts { case SyntaxKind.TypeAssertionExpression: case SyntaxKind.AsExpression: return checkAssertion(node); + case SyntaxKind.NonNullExpression: + return checkNonNullAssertion(node); case SyntaxKind.DeleteExpression: return checkDeleteExpression(node); case SyntaxKind.VoidExpression: @@ -10596,11 +12278,10 @@ namespace ts { } checkSourceElement(node.constraint); + getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node))); if (produceDiagnostics) { - checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, Diagnostics.Type_parameter_name_cannot_be_0); } - // TODO: Check multiple declarations are identical } function checkParameter(node: ParameterDeclaration) { @@ -10655,7 +12336,55 @@ namespace ts { return -1; } - function isInLegalTypePredicatePosition(node: Node): boolean { + function checkTypePredicate(node: TypePredicateNode): void { + const parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + + const typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + + const { parameterName } = node; + if (isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName as ThisTypeNode); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, + Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + const leadingError = chainDiagnosticMessages(undefined, Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + checkTypeAssignableTo(typePredicate.type, + getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), + node.type, + /*headMessage*/ undefined, + leadingError); + } + } + else if (parameterName) { + let hasReportedError = false; + for (const { name } of parent.parameters) { + if (isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + + function getTypePredicateParent(node: Node): SignatureDeclaration { switch (node.parent.kind) { case SyntaxKind.ArrowFunction: case SyntaxKind.CallSignature: @@ -10664,9 +12393,35 @@ namespace ts { case SyntaxKind.FunctionType: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - return node === (node.parent).type; + const parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + + function checkIfTypePredicateVariableIsDeclaredInBindingPattern( + pattern: BindingPattern, + predicateVariableNode: Node, + predicateVariableName: string) { + for (const { name } of pattern.elements) { + if (name.kind === SyntaxKind.Identifier && + (name).text === predicateVariableName) { + error(predicateVariableNode, + Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, + predicateVariableName); + return true; + } + else if (name.kind === SyntaxKind.ArrayBindingPattern || + name.kind === SyntaxKind.ObjectBindingPattern) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern( + name, + predicateVariableNode, + predicateVariableName)) { + return true; + } + } } - return false; } function checkSignatureDeclaration(node: SignatureDeclaration) { @@ -10686,65 +12441,7 @@ namespace ts { forEach(node.parameters, checkParameter); if (node.type) { - if (node.type.kind === SyntaxKind.TypePredicate) { - const typePredicate = getSignatureFromDeclaration(node).typePredicate; - const 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, - getTypeOfNode(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 (const 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); - } + checkSourceElement(node.type); } if (produceDiagnostics) { @@ -10779,10 +12476,11 @@ namespace ts { checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } + else if (isAsyncFunctionLike(node)) { + checkAsyncFunctionReturnType(node); + } } } - - checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node: Node) { @@ -10840,7 +12538,7 @@ namespace ts { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration - checkFunctionLikeDeclaration(node); + checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. @@ -10852,13 +12550,14 @@ namespace ts { function checkConstructorDeclaration(node: ConstructorDeclaration) { // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. checkSignatureDeclaration(node); - // Grammar check for checking only related to constructoDeclaration + // Grammar check for checking only related to constructorDeclaration checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); const symbol = getSymbolOfNode(node); const firstDeclaration = getDeclarationOfKind(symbol, node.kind); + // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(symbol); @@ -10873,10 +12572,6 @@ namespace ts { return; } - function isSuperCallExpression(n: Node): boolean { - return n.kind === SyntaxKind.CallExpression && (n).expression.kind === SyntaxKind.SuperKeyword; - } - function containsSuperCallAsComputedPropertyName(n: Declaration): boolean { return n.name && containsSuperCall(n.name); } @@ -10914,13 +12609,11 @@ namespace ts { // constructors of derived classes must contain at least one super call somewhere in their function body. const containingClassDecl = node.parent; if (getClassExtendsHeritageClauseElement(containingClassDecl)) { - const containingClassSymbol = getSymbolOfNode(containingClassDecl); - const containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); - const baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); - - if (containsSuperCall(node.body)) { - if (baseConstructorType === nullType) { - error(node, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + const classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + const superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } // The first statement in the body of a constructor (excluding prologue directives) must be a super call @@ -10937,6 +12630,7 @@ namespace ts { if (superCallShouldBeFirst) { const statements = (node.body).statements; let superCallStatement: ExpressionStatement; + for (const statement of statements) { if (statement.kind === SyntaxKind.ExpressionStatement && isSuperCallExpression((statement).expression)) { superCallStatement = statement; @@ -10949,13 +12643,9 @@ namespace ts { if (!superCallStatement) { error(node, Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); } - else { - // In such a required super call, it is a compile-time error for argument expressions to reference this. - markThisReferencesAsErrors(superCallStatement.expression); - } } } - else if (baseConstructorType !== nullType) { + else if (!classExtendsNull) { error(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); } } @@ -10966,6 +12656,8 @@ namespace ts { // Grammar checking accessors checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); if (node.kind === SyntaxKind.GetAccessor) { if (!isInAmbientContext(node) && nodeIsPresent(node.body) && (node.flags & NodeFlags.HasImplicitReturn)) { if (node.flags & NodeFlags.HasExplicitReturn) { @@ -10978,7 +12670,12 @@ namespace 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 === SyntaxKind.ComputedPropertyName) { + checkComputedPropertyName(node.name); + } if (!hasDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. @@ -10988,6 +12685,9 @@ namespace ts { if (((node.flags & NodeFlags.AccessibilityModifier) !== (otherAccessor.flags & NodeFlags.AccessibilityModifier))) { error(node.name, Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } + if (((node.flags & NodeFlags.Abstract) !== (otherAccessor.flags & NodeFlags.Abstract))) { + error(node.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } const currentAccessorType = getAnnotatedAccessorType(node); const otherAccessorType = getAnnotatedAccessorType(otherAccessor); @@ -11002,21 +12702,39 @@ namespace ts { } getTypeOfAccessors(getSymbolOfNode(node)); } + if (node.parent.kind !== SyntaxKind.ObjectLiteralExpression) { + checkSourceElement(node.body); + } + else { + checkNodeDeferred(node); + } + } - checkFunctionLikeDeclaration(node); + function checkAccessorDeferred(node: AccessorDeclaration) { + checkSourceElement(node.body); } function checkMissingDeclaration(node: Node) { checkDecorators(node); } - function checkTypeArgumentConstraints(typeParameters: TypeParameter[], typeArguments: TypeNode[]): boolean { + function checkTypeArgumentConstraints(typeParameters: TypeParameter[], typeArgumentNodes: TypeNode[]): boolean { + let typeArguments: Type[]; + let mapper: TypeMapper; let result = true; for (let i = 0; i < typeParameters.length; i++) { const constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { + if (!typeArguments) { + typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); + mapper = createTypeMapper(typeParameters, typeArguments); + } const typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo( + typeArgument, + getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), + typeArgumentNodes[i], + Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -11071,48 +12789,6 @@ namespace ts { return (node.flags & NodeFlags.Private) && isInAmbientContext(node); } - function checkSpecializedSignatureDeclaration(signatureDeclarationNode: SignatureDeclaration): void { - if (!produceDiagnostics) { - return; - } - const signature = getSignatureFromDeclaration(signatureDeclarationNode); - if (!signature.hasStringLiterals) { - return; - } - - // TypeScript 1.0 spec (April 2014): 3.7.2.2 - // Specialized signatures are not permitted in conjunction with a function body - if (nodeIsPresent((signatureDeclarationNode).body)) { - error(signatureDeclarationNode, Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type); - return; - } - - // TypeScript 1.0 spec (April 2014): 3.7.2.4 - // Every specialized call or construct signature in an object type must be assignable - // to at least one non-specialized call or construct signature in the same object type - let signaturesToCheck: Signature[]; - // 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 === SyntaxKind.InterfaceDeclaration) { - Debug.assert(signatureDeclarationNode.kind === SyntaxKind.CallSignature || signatureDeclarationNode.kind === SyntaxKind.ConstructSignature); - const signatureKind = signatureDeclarationNode.kind === SyntaxKind.CallSignature ? SignatureKind.Call : SignatureKind.Construct; - const containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); - const containingType = getDeclaredTypeOfSymbol(containingSymbol); - signaturesToCheck = getSignaturesOfType(containingType, signatureKind); - } - else { - signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); - } - - for (const otherSignature of signaturesToCheck) { - if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { - return; - } - } - - error(signatureDeclarationNode, Diagnostics.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature); - } - function getEffectiveDeclarationFlags(n: Node, flagsToCheck: NodeFlags): NodeFlags { let flags = getCombinedNodeFlags(n); @@ -11157,16 +12833,16 @@ namespace ts { forEach(overloads, o => { const deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; if (deviation & NodeFlags.Export) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); + error(o.name, Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & NodeFlags.Ambient) { error(o.name, Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (NodeFlags.Private | NodeFlags.Protected)) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(o.name || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & NodeFlags.Abstract) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); + error(o.name, Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -11211,16 +12887,24 @@ namespace ts { seen = c === node; } }); - if (subsequentNode) { + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { const errorNode: Node = (subsequentNode).name || subsequentNode; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && (subsequentNode).name && (node.name).text === ((subsequentNode).name).text) { - // the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members - Debug.assert(node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature); - Debug.assert((node.flags & NodeFlags.Static) !== (subsequentNode.flags & NodeFlags.Static)); - const diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; - error(errorNode, diagnostic); + const reportError = + (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) && + (node.flags & NodeFlags.Static) !== (subsequentNode.flags & NodeFlags.Static); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + const diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; + error(errorNode, diagnostic); + } return; } else if (nodeIsPresent((subsequentNode).body)) { @@ -11315,7 +12999,7 @@ namespace ts { // Abstract methods can't have an implementation -- in particular, they don't need one. if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & NodeFlags.Abstract) ) { + !(lastSeenNonAmbientDeclaration.flags & NodeFlags.Abstract)) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -11326,28 +13010,10 @@ namespace ts { if (bodyDeclaration) { const signatures = getSignaturesOfSymbol(symbol); const bodySignature = getSignatureFromDeclaration(bodyDeclaration); - // If the implementation signature has string literals, we will have reported an error in - // checkSpecializedSignatureDeclaration - if (!bodySignature.hasStringLiterals) { - // TypeScript 1.0 spec (April 2014): 6.1 - // If a function declaration includes overloads, the overloads determine the call - // signatures of the type given to the function object - // and the function implementation signature must be assignable to that type - // - // TypeScript 1.0 spec (April 2014): 3.8.4 - // Note that specialized call and construct signatures (section 3.7.2.4) are not significant when determining assignment compatibility - // Consider checking against specialized signatures too. Not doing so creates a type hole: - // - // function g(x: "hi", y: boolean); - // function g(x: string, y: {}); - // function g(x: string, y: string) { } - // - // The implementation is completely unrelated to the specialized signature, yet we do not check this. - for (const signature of signatures) { - if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { - error(signature.declaration, Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); - break; - } + for (const signature of signatures) { + if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { + error(signature.declaration, Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; } } } @@ -11398,7 +13064,7 @@ namespace ts { } } - // Spaces for anyting not declared a 'default export'. + // Spaces for anything not declared a 'default export'. const nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; const commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; @@ -11409,7 +13075,7 @@ namespace ts { for (const d of symbol.declarations) { const declarationSpaces = getDeclarationSpaces(d); - // Only error on the declarations that conributed to the intersecting spaces. + // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { error(d.name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(d.name)); } @@ -11424,7 +13090,7 @@ namespace ts { case SyntaxKind.InterfaceDeclaration: return SymbolFlags.ExportType; case SyntaxKind.ModuleDeclaration: - return (d).name.kind === SyntaxKind.StringLiteral || getModuleInstanceState(d) !== ModuleInstanceState.NonInstantiated + return isAmbientModule(d) || getModuleInstanceState(d) !== ModuleInstanceState.NonInstantiated ? SymbolFlags.ExportNamespace | SymbolFlags.ExportValue : SymbolFlags.ExportNamespace; case SyntaxKind.ClassDeclaration: @@ -11559,7 +13225,7 @@ namespace ts { return checkNonThenableType(type, location, message); } else { - if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { + if (type.id === promisedType.id || indexOf(awaitedTypeStack, promisedType.id) >= 0) { // We have a bad actor in the form of a promise whose promised type is // the same promise type, or a mutually recursive promise. Return the // unknown type as we cannot guess the shape. If this were the actual @@ -11614,6 +13280,36 @@ namespace ts { } } + /** + * Checks that the return type provided is an instantiation of the global Promise type + * and returns the awaited type of the return type. + * + * @param returnType The return type of a FunctionLikeDeclaration + * @param location The node on which to report the error. + */ + function checkCorrectPromiseType(returnType: Type, location: Node) { + if (returnType === unknownType) { + // The return type already had some other error, so we ignore and return + // the unknown type. + return unknownType; + } + + const globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType === emptyGenericType + || globalPromiseType === getTargetType(returnType)) { + // Either we couldn't resolve the global promise type, which would have already + // reported an error, or we could resolve it and the return type is a valid type + // reference to the global type. In either case, we return the awaited type for + // the return type. + return checkAwaitedType(returnType, location, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + } + + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(location, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } + /** * Checks the return type of an async function to ensure it is a compatible * Promise implementation. @@ -11628,6 +13324,11 @@ namespace ts { * callable `then` signature. */ function checkAsyncFunctionReturnType(node: FunctionLikeDeclaration): Type { + if (languageVersion >= ScriptTarget.ES6) { + const returnType = getTypeFromTypeNode(node.type); + return checkCorrectPromiseType(returnType, node.type); + } + const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify @@ -11678,6 +13379,9 @@ namespace ts { return unknownType; } + // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. + checkReturnTypeAnnotationAsExpression(node); + // Validate the promise constructor type. const promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { @@ -11686,11 +13390,11 @@ namespace ts { // Verify there is no local declaration that could collide with the promise constructor. const promiseName = getEntityNameFromTypeNode(node.type); - const root = getFirstIdentifier(promiseName); - const rootSymbol = getSymbol(node.locals, root.text, SymbolFlags.Value); + const promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); + const rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.text, SymbolFlags.Value); if (rootSymbol) { error(rootSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, - root.text, + promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } @@ -11774,24 +13478,12 @@ namespace ts { * Checks the type annotation of an accessor declaration or property declaration as * an expression if it is a type reference to a type with a value declaration. */ - function checkTypeAnnotationAsExpression(node: AccessorDeclaration | PropertyDeclaration | ParameterDeclaration | MethodDeclaration) { - switch (node.kind) { - case SyntaxKind.PropertyDeclaration: - checkTypeNodeAsExpression((node).type); - break; - case SyntaxKind.Parameter: - checkTypeNodeAsExpression((node).type); - break; - case SyntaxKind.MethodDeclaration: - checkTypeNodeAsExpression((node).type); - break; - case SyntaxKind.GetAccessor: - checkTypeNodeAsExpression((node).type); - break; - case SyntaxKind.SetAccessor: - checkTypeNodeAsExpression(getSetAccessorTypeAnnotationNode(node)); - break; - } + function checkTypeAnnotationAsExpression(node: VariableLikeDeclaration) { + checkTypeNodeAsExpression((node).type); + } + + function checkReturnTypeAnnotationAsExpression(node: FunctionLikeDeclaration) { + checkTypeNodeAsExpression(node.type); } /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ @@ -11815,7 +13507,7 @@ namespace ts { } 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); + error(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } if (compilerOptions.emitDecoratorMetadata) { @@ -11829,11 +13521,12 @@ namespace ts { break; case SyntaxKind.MethodDeclaration: - checkParameterTypeAnnotationsAsExpressions(node); - // fall-through - - case SyntaxKind.SetAccessor: case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + checkParameterTypeAnnotationsAsExpressions(node); + checkReturnTypeAnnotationAsExpression(node); + break; + case SyntaxKind.PropertyDeclaration: case SyntaxKind.Parameter: checkTypeAnnotationAsExpression(node); @@ -11841,31 +13534,24 @@ namespace ts { } } - emitDecorate = true; - if (node.kind === SyntaxKind.Parameter) { - emitParam = true; - } - forEach(node.decorators, checkDecorator); } function checkFunctionDeclaration(node: FunctionDeclaration): void { if (produceDiagnostics) { - checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); + checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkFunctionLikeDeclaration(node: FunctionLikeDeclaration): void { + function checkFunctionOrMethodDeclaration(node: FunctionDeclaration | MethodDeclaration): void { checkDecorators(node); checkSignatureDeclaration(node); const isAsync = isAsyncFunctionLike(node); - if (isAsync) { - emitAwaiter = true; - } // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including @@ -11883,7 +13569,14 @@ namespace ts { const symbol = getSymbolOfNode(node); const localSymbol = node.localSymbol || symbol; - const firstDeclaration = getDeclarationOfKind(localSymbol, node.kind); + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + const firstDeclaration = forEach(localSymbol.declarations, + // Get first non javascript function declaration + declaration => declaration.kind === node.kind && !isSourceFileJavaScript(getSourceFileOfNode(declaration)) ? + declaration : undefined); + // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); @@ -11899,14 +13592,9 @@ namespace ts { } checkSourceElement(node.body); - if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - const returnType = getTypeFromTypeNode(node.type); - let promisedType: Type; - if (isAsync) { - promisedType = checkAsyncFunctionReturnType(node); - } - - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); + if (!node.asteriskToken) { + const returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !node.type) { @@ -11930,11 +13618,7 @@ namespace ts { if (node.kind === SyntaxKind.Block) { checkGrammarStatementInAmbientContext(node); } - forEach(node.statements, checkSourceElement); - if (isFunctionBlock(node) || node.kind === SyntaxKind.ModuleBlock) { - checkFunctionAndClassExpressionBodies(node); - } } function checkCollisionWithArgumentsInGeneratedCode(node: SignatureDeclaration) { @@ -12038,13 +13722,32 @@ namespace ts { // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent const parent = getDeclarationContainer(node); - if (parent.kind === SyntaxKind.SourceFile && isExternalModule(parent)) { + if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name)); } } + function checkCollisionWithGlobalPromiseInGeneratedCode(node: Node, name: Identifier): void { + if (!needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + + // Uninstantiated modules shouldnt do this check + if (node.kind === SyntaxKind.ModuleDeclaration && getModuleInstanceState(node) !== ModuleInstanceState.Instantiated) { + return; + } + + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + const parent = getDeclarationContainer(node); + if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent) && parent.flags & NodeFlags.HasAsyncFunctions) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, + declarationNameToString(name), declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node: VariableDeclaration | BindingElement) { // - ScriptBody : StatementList // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList @@ -12167,6 +13870,23 @@ namespace ts { checkExpressionCached(node.initializer); } } + + if (node.kind === SyntaxKind.BindingElement) { + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === SyntaxKind.ComputedPropertyName) { + checkComputedPropertyName(node.propertyName); + } + + // check private/protected variable access + const parent = (node.parent).parent; + const parentType = getTypeForBindingElementParent(parent); + const name = node.propertyName || node.name; + const property = getPropertyOfType(parentType, getTextOfPropertyName(name)); + if (parent.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent, parent.initializer, parentType, property); + } + } + // For a binding pattern, check contained binding elements if (isBindingPattern(node.name)) { forEach((node.name).elements, checkSourceElement); @@ -12178,7 +13898,8 @@ namespace ts { } // For a binding pattern, validate the initializer and exit if (isBindingPattern(node.name)) { - if (node.initializer) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== SyntaxKind.ForInStatement) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -12188,7 +13909,8 @@ namespace ts { const type = getTypeOfVariableOrParameterOrProperty(symbol); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer - if (node.initializer) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== SyntaxKind.ForInStatement) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -12213,6 +13935,7 @@ namespace ts { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } @@ -12331,7 +14054,7 @@ namespace ts { else { const leftType = checkExpression(varExpr); checkReferenceExpression(varExpr, /*invalidReferenceMessage*/ Diagnostics.Invalid_left_hand_side_in_for_of_statement, - /*constantVariableMessage*/ Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant); + /*constantVariableMessage*/ Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_constant_or_a_read_only_property); // iteratedType will be undefined if the rightType was missing properties/signatures // required to get its iteratedType (like [Symbol.iterator] or next). This may be @@ -12378,11 +14101,12 @@ namespace ts { } else { // run check only former check succeeded to avoid cascading errors - checkReferenceExpression(varExpr, Diagnostics.Invalid_left_hand_side_in_for_in_statement, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant); + checkReferenceExpression(varExpr, Diagnostics.Invalid_left_hand_side_in_for_in_statement, + Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_constant_or_a_read_only_property); } } - const rightType = checkExpression(node.expression); + const rightType = checkNonNullExpression(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 (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.ObjectType | TypeFlags.TypeParameter)) { @@ -12402,7 +14126,7 @@ namespace ts { } function checkRightHandSideOfForOf(rhsExpression: Expression): Type { - const expressionType = getTypeOfExpression(rhsExpression); + const expressionType = checkNonNullExpression(rhsExpression); return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true); } @@ -12576,7 +14300,7 @@ namespace ts { * This function does the following steps: * 1. Break up arrayOrStringType (possibly a union) into its string constituents and array constituents. * 2. Take the element types of the array constituents. - * 3. Return the union of the element types, and string if there was a string constitutent. + * 3. Return the union of the element types, and string if there was a string constituent. * * For example: * string -> string @@ -12594,9 +14318,14 @@ namespace ts { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. - const arrayType = removeTypesFromUnionType(arrayOrStringType, TypeFlags.StringLike, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); + let arrayType = arrayOrStringType; + if (arrayOrStringType.flags & TypeFlags.Union) { + arrayType = getUnionType(filter((arrayOrStringType as UnionType).types, t => !(t.flags & TypeFlags.StringLike))); + } + else if (arrayOrStringType.flags & TypeFlags.StringLike) { + arrayType = emptyUnionType; + } const hasStringConstituent = arrayOrStringType !== arrayType; - let reportedError = false; if (hasStringConstituent) { if (languageVersion < ScriptTarget.ES5) { @@ -12645,10 +14374,15 @@ namespace ts { // TODO: Check that target label is valid } - function isGetAccessorWithAnnotatatedSetAccessor(node: FunctionLikeDeclaration) { + function isGetAccessorWithAnnotatedSetAccessor(node: FunctionLikeDeclaration) { return !!(node.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(node.symbol, SyntaxKind.SetAccessor))); } + function isUnwrappedReturnTypeVoidOrAny(func: FunctionLikeDeclaration, returnType: Type): boolean { + const unwrappedReturnType = isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType; + return maybeTypeOfKind(unwrappedReturnType, TypeFlags.Void | TypeFlags.Any); + } + function checkReturnStatement(node: ReturnStatement) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { @@ -12658,12 +14392,12 @@ namespace ts { } } - if (node.expression) { - const func = getContainingFunction(node); - if (func) { - const signature = getSignatureFromDeclaration(func); - const returnType = getReturnTypeOfSignature(signature); - const exprType = checkExpressionCached(node.expression); + const func = getContainingFunction(node); + if (func) { + const signature = getSignatureFromDeclaration(func); + const returnType = getReturnTypeOfSignature(signature); + if (strictNullChecks || node.expression) { + const exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (func.asteriskToken) { // A generator does not need its return expressions checked against its return type. @@ -12674,36 +14408,42 @@ namespace ts { } if (func.kind === SyntaxKind.SetAccessor) { - error(node.expression, Diagnostics.Setters_cannot_return_a_value); + if (node.expression) { + error(node.expression, Diagnostics.Setters_cannot_return_a_value); + } } else if (func.kind === SyntaxKind.Constructor) { - if (!checkTypeAssignableTo(exprType, returnType, node.expression)) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node.expression)) { 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) { + else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { if (isAsyncFunctionLike(func)) { const promisedType = getPromisedType(returnType); - const awaitedType = checkAwaitedType(exprType, node.expression, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + const awaitedType = checkAwaitedType(exprType, node.expression || node, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); if (promisedType) { // If the function has a return type, but promisedType is // undefined, an error will be reported in checkAsyncFunctionReturnType // so we don't need to report one here. - checkTypeAssignableTo(awaitedType, promisedType, node.expression); + checkTypeAssignableTo(awaitedType, promisedType, node.expression || node); } } else { - checkTypeAssignableTo(exprType, returnType, node.expression); + checkTypeAssignableTo(exprType, returnType, node.expression || node); } } } + else if (func.kind !== SyntaxKind.Constructor && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, Diagnostics.Not_all_code_paths_return_a_value); + } } } function checkWithStatement(node: WithStatement) { // Grammar checking for withStatement if (!checkGrammarStatementInAmbientContext(node)) { - if (node.parserContextFlags & ParserContextFlags.Await) { + if (node.flags & NodeFlags.AwaitContext) { grammarErrorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); } } @@ -12741,8 +14481,8 @@ namespace ts { // In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression. // TODO (drosen): this needs to be amended to reflect the "comparable" relationship. const caseType = checkExpression(caseClause.expression); - if (!isTypeComparableTo(expressionType, caseType)) { + // expressionType is not comparable to caseType, try the reversed check and report errors if it fails checkTypeComparableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); } } @@ -12924,7 +14664,7 @@ namespace ts { } } - // Check each type parameter and check that list has no duplicate type parameter declarations + /** Check each type parameter and check that type parameters have no duplicate type parameter declarations */ function checkTypeParameters(typeParameterDeclarations: TypeParameterDeclaration[]) { if (typeParameterDeclarations) { for (let i = 0, n = typeParameterDeclarations.length; i < n; i++) { @@ -12942,17 +14682,39 @@ namespace ts { } } + /** Check that type parameter lists are identical across multiple declarations */ + function checkTypeParameterListsIdentical(node: ClassLikeDeclaration | InterfaceDeclaration, symbol: Symbol) { + if (symbol.declarations.length === 1) { + return; + } + let firstDecl: ClassLikeDeclaration | InterfaceDeclaration; + for (const declaration of symbol.declarations) { + if (declaration.kind === SyntaxKind.ClassDeclaration || declaration.kind === SyntaxKind.InterfaceDeclaration) { + if (!firstDecl) { + firstDecl = declaration; + } + else if (!areTypeParametersIdentical(firstDecl.typeParameters, node.typeParameters)) { + error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, node.name.text); + } + } + } + } + function checkClassExpression(node: ClassExpression): Type { checkClassLikeDeclaration(node); + checkNodeDeferred(node); return getTypeOfSymbol(getSymbolOfNode(node)); } + function checkClassExpressionDeferred(node: ClassExpression) { + forEach(node.members, checkSourceElement); + } + function checkClassDeclaration(node: ClassDeclaration) { if (!node.name && !(node.flags & NodeFlags.Default)) { grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); - forEach(node.members, checkSourceElement); } @@ -12963,6 +14725,7 @@ namespace ts { checkTypeNameIsReserved(node.name, Diagnostics.Class_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } checkTypeParameters(node.typeParameters); checkExportsOnMergedDeclarations(node); @@ -12970,14 +14733,15 @@ namespace ts { const type = getDeclaredTypeOfSymbol(symbol); const typeWithThis = getTypeWithThisArgument(type); const staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(node, symbol); const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - emitExtends = emitExtends || !isInAmbientContext(node); const baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { const baseType = baseTypes[0]; const staticBaseType = getBaseConstructorTypeOfClass(type); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); if (baseTypeNode.typeArguments) { forEach(baseTypeNode.typeArguments, checkSourceElement); @@ -13033,6 +14797,19 @@ namespace ts { } } + function checkBaseTypeAccessibility(type: ObjectType, node: ExpressionWithTypeArguments) { + const signatures = getSignaturesOfType(type, SignatureKind.Construct); + if (signatures.length) { + const declaration = signatures[0].declaration; + if (declaration && declaration.flags & NodeFlags.Private) { + const typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, (node.expression).text); + } + } + } + } + function getTargetSymbol(s: Symbol) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags @@ -13074,7 +14851,7 @@ namespace ts { Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { - // In order to resolve whether the inherited method was overriden in the base class or not, + // In order to resolve whether the inherited method was overridden in the base class or not, // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* // type declaration, derived and base resolve to the same symbol even in the case of generic classes. if (derived === base) { @@ -13219,14 +14996,10 @@ namespace ts { checkExportsOnMergedDeclarations(node); const symbol = getSymbolOfNode(node); - const firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); - if (symbol.declarations.length > 1) { - if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { - error(node.name, Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); - } - } + checkTypeParameterListsIdentical(node, symbol); // Only check this symbol once + const firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); if (node === firstInterfaceDecl) { const type = getDeclaredTypeOfSymbol(symbol); const typeWithThis = getTypeWithThisArgument(type); @@ -13272,11 +15045,14 @@ namespace ts { const enumIsConst = isConst(node); for (const member of node.members) { - if (member.name.kind === SyntaxKind.ComputedPropertyName) { + if (isComputedNonLiteralName(member.name)) { error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums); } - else if (isNumericLiteralName((member.name).text)) { - error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); + else { + const text = getTextOfPropertyName(member.name); + if (isNumericLiteralName(text)) { + error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } } const previousEnumMemberIsNonConstant = autoValue === undefined; @@ -13299,7 +15075,8 @@ namespace ts { } if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue++; + getNodeLinks(member).enumMemberValue = autoValue; + autoValue++; } } @@ -13466,6 +15243,7 @@ namespace ts { checkTypeNameIsReserved(node.name, Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); @@ -13547,7 +15325,13 @@ namespace ts { function checkModuleDeclaration(node: ModuleDeclaration) { if (produceDiagnostics) { // Grammar checking - const isAmbientExternalModule = node.name.kind === SyntaxKind.StringLiteral; + const isGlobalAugmentation = isGlobalScopeAugmentation(node); + const inAmbientContext = isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + + const isAmbientExternalModule = isAmbientModule(node); const 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; @@ -13557,20 +15341,21 @@ namespace ts { } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!isInAmbientContext(node) && node.name.kind === SyntaxKind.StringLiteral) { + if (!inAmbientContext && node.name.kind === SyntaxKind.StringLiteral) { grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names); } } checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); const symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & SymbolFlags.ValueModule && symbol.declarations.length > 1 - && !isInAmbientContext(node) + && !inAmbientContext && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { const firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -13591,19 +15376,107 @@ namespace ts { } } - // Checks for ambient external modules. if (isAmbientExternalModule) { - if (!isGlobalSourceFile(node.parent)) { - error(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + if (isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + const checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & SymbolFlags.Merged); + if (checkBody) { + // body of ambient external module is always a module block + for (const statement of (node.body).statements) { + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } } - if (isExternalModuleNameRelative(node.name.text)) { - error(node.name, Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (isExternalModuleNameRelative(node.name.text)) { + error(node.name, Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } } } } checkSourceElement(node.body); } + function checkModuleAugmentationElement(node: Node, isGlobalAugmentation: boolean): void { + switch (node.kind) { + case SyntaxKind.VariableStatement: + // error each individual name in variable statement instead of marking the entire variable statement + for (const decl of (node).declarationList.declarations) { + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case SyntaxKind.ExportAssignment: + case SyntaxKind.ExportDeclaration: + grammarErrorOnFirstToken(node, Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case SyntaxKind.ImportEqualsDeclaration: + if ((node).moduleReference.kind !== SyntaxKind.StringLiteral) { + error((node).name, Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + break; + } + // fallthrough + case SyntaxKind.ImportDeclaration: + grammarErrorOnFirstToken(node, Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case SyntaxKind.BindingElement: + case SyntaxKind.VariableDeclaration: + const name = (node).name; + if (isBindingPattern(name)) { + for (const el of name.elements) { + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // fallthrough + case SyntaxKind.ClassDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.TypeAliasDeclaration: + const symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + let reportError = !(symbol.flags & SymbolFlags.Merged); + if (!reportError) { + if (isGlobalAugmentation) { + // global symbol should not have parent since it is not explicitly exported + reportError = symbol.parent !== undefined; + } + else { + // symbol should not originate in augmentation + reportError = isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + if (reportError) { + error(node, Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + } + } + break; + } + } + function getFirstIdentifier(node: EntityName | Expression): Identifier { while (true) { if (node.kind === SyntaxKind.QualifiedName) { @@ -13626,7 +15499,7 @@ namespace ts { error(moduleName, Diagnostics.String_literal_expected); return false; } - const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; + const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && isAmbientModule(node.parent.parent); if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule) { error(moduleName, node.kind === SyntaxKind.ExportDeclaration ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : @@ -13634,12 +15507,16 @@ namespace ts { return false; } if (inAmbientExternalModule && isExternalModuleNameRelative((moduleName).text)) { - // TypeScript 1.0 spec (April 2013): 12.1.6 - // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference - // other external modules only through top - level external module names. - // Relative external module names are not permitted. - error(node, Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); - return false; + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } } return true; } @@ -13648,8 +15525,14 @@ namespace ts { const symbol = getSymbolOfNode(node); const target = resolveAlias(symbol); if (target !== unknownSymbol) { + // For external modules symbol represent local symbol for an alias. + // This local symbol will merge any other local declarations (excluding other aliases) + // and symbol.flags will contains combined representation for all merged declaration. + // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, + // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* + // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). const excludedMeanings = - (symbol.flags & SymbolFlags.Value ? SymbolFlags.Value : 0) | + (symbol.flags & (SymbolFlags.Value | SymbolFlags.ExportValue) ? SymbolFlags.Value : 0) | (symbol.flags & SymbolFlags.Type ? SymbolFlags.Type : 0) | (symbol.flags & SymbolFlags.Namespace ? SymbolFlags.Namespace : 0); if (target.flags & excludedMeanings) { @@ -13664,6 +15547,7 @@ namespace ts { function checkImportBinding(node: ImportEqualsDeclaration | ImportClause | NamespaceImport | ImportSpecifier) { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); } @@ -13745,7 +15629,7 @@ namespace ts { // export { x, y } from "foo" forEach(node.exportClause.elements, checkExportSpecifier); - const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; + const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && isAmbientModule(node.parent.parent); if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule) { error(node, Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } @@ -13753,7 +15637,7 @@ namespace ts { else { // export * from "foo" const moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && moduleSymbol.exports["export="]) { + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } } @@ -13769,7 +15653,16 @@ namespace ts { function checkExportSpecifier(node: ExportSpecifier) { checkAliasSymbol(node); if (!(node.parent.parent).moduleSpecifier) { - markExportAsReferenced(node); + const exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + const symbol = resolveName(exportedName, exportedName.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, Diagnostics.Cannot_re_export_name_that_is_not_defined_in_the_module); + } + else { + markExportAsReferenced(node); + } } } @@ -13780,7 +15673,7 @@ namespace ts { } const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; - if (container.kind === SyntaxKind.ModuleDeclaration && (container).name.kind === SyntaxKind.Identifier) { + if (container.kind === SyntaxKind.ModuleDeclaration && !isAmbientModule(container)) { error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } @@ -13809,18 +15702,8 @@ namespace ts { } } - function getModuleStatements(node: Declaration): Statement[] { - if (node.kind === SyntaxKind.SourceFile) { - return (node).statements; - } - if (node.kind === SyntaxKind.ModuleDeclaration && (node).body.kind === SyntaxKind.ModuleBlock) { - return ((node).body).statements; - } - return emptyArray; - } - function hasExportedMembers(moduleSymbol: Symbol) { - for (var id in moduleSymbol.exports) { + for (const id in moduleSymbol.exports) { if (id !== "export=") { return true; } @@ -13835,15 +15718,41 @@ namespace ts { const exportEqualsSymbol = moduleSymbol.exports["export="]; if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + const exports = getExportsOfModule(moduleSymbol); + for (const id in exports) { + if (id === "__export") { + continue; + } + const { declarations, flags } = exports[id]; + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (SymbolFlags.Namespace | SymbolFlags.Interface | SymbolFlags.Enum)) { + continue; + } + const exportedDeclarationsCount = countWhere(declarations, isNotOverload); + if (flags & SymbolFlags.TypeAlias && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + continue; + } + if (exportedDeclarationsCount > 1) { + for (const declaration of declarations) { + if (isNotOverload(declaration)) { + diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Cannot_redeclare_exported_variable_0, id)); + } + } + } } links.exportsChecked = true; } - } - 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 isNotOverload(declaration: Declaration): boolean { + return declaration.kind !== SyntaxKind.FunctionDeclaration || !!(declaration as FunctionDeclaration).body; } } @@ -13854,7 +15763,7 @@ namespace ts { const kind = node.kind; if (cancellationToken) { - // Only bother checking on a few construct kinds. We don't want to be excessivly + // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { case SyntaxKind.ModuleDeclaration: @@ -13983,102 +15892,29 @@ namespace ts { // Here, performing a full type check of the body of the function expression whilst in the process of // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. - function checkFunctionAndClassExpressionBodies(node: Node): void { - switch (node.kind) { - case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: - forEach((node).parameters, checkFunctionAndClassExpressionBodies); - checkFunctionExpressionOrObjectLiteralMethodBody(node); - break; - case SyntaxKind.ClassExpression: - forEach((node).members, checkSourceElement); - forEachChild(node, checkFunctionAndClassExpressionBodies); - break; - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - forEach(node.decorators, checkFunctionAndClassExpressionBodies); - forEach((node).parameters, checkFunctionAndClassExpressionBodies); - if (isObjectLiteralMethod(node)) { - checkFunctionExpressionOrObjectLiteralMethodBody(node); - } - break; - case SyntaxKind.Constructor: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - case SyntaxKind.FunctionDeclaration: - forEach((node).parameters, checkFunctionAndClassExpressionBodies); - break; - case SyntaxKind.WithStatement: - checkFunctionAndClassExpressionBodies((node).expression); - break; - case SyntaxKind.Decorator: - case SyntaxKind.Parameter: - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.PropertySignature: - case SyntaxKind.ObjectBindingPattern: - case SyntaxKind.ArrayBindingPattern: - case SyntaxKind.BindingElement: - case SyntaxKind.ArrayLiteralExpression: - case SyntaxKind.ObjectLiteralExpression: - case SyntaxKind.PropertyAssignment: - case SyntaxKind.PropertyAccessExpression: - case SyntaxKind.ElementAccessExpression: - case SyntaxKind.CallExpression: - case SyntaxKind.NewExpression: - case SyntaxKind.TaggedTemplateExpression: - case SyntaxKind.TemplateExpression: - case SyntaxKind.TemplateSpan: - case SyntaxKind.TypeAssertionExpression: - case SyntaxKind.AsExpression: - case SyntaxKind.ParenthesizedExpression: - case SyntaxKind.TypeOfExpression: - case SyntaxKind.VoidExpression: - case SyntaxKind.AwaitExpression: - case SyntaxKind.DeleteExpression: - case SyntaxKind.PrefixUnaryExpression: - case SyntaxKind.PostfixUnaryExpression: - case SyntaxKind.BinaryExpression: - case SyntaxKind.ConditionalExpression: - case SyntaxKind.SpreadElementExpression: - case SyntaxKind.YieldExpression: - case SyntaxKind.Block: - case SyntaxKind.ModuleBlock: - case SyntaxKind.VariableStatement: - case SyntaxKind.ExpressionStatement: - case SyntaxKind.IfStatement: - case SyntaxKind.DoStatement: - case SyntaxKind.WhileStatement: - case SyntaxKind.ForStatement: - case SyntaxKind.ForInStatement: - case SyntaxKind.ForOfStatement: - case SyntaxKind.ContinueStatement: - case SyntaxKind.BreakStatement: - case SyntaxKind.ReturnStatement: - case SyntaxKind.SwitchStatement: - case SyntaxKind.CaseBlock: - case SyntaxKind.CaseClause: - case SyntaxKind.DefaultClause: - case SyntaxKind.LabeledStatement: - case SyntaxKind.ThrowStatement: - case SyntaxKind.TryStatement: - case SyntaxKind.CatchClause: - case SyntaxKind.VariableDeclaration: - case SyntaxKind.VariableDeclarationList: - case SyntaxKind.ClassDeclaration: - case SyntaxKind.HeritageClause: - case SyntaxKind.ExpressionWithTypeArguments: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.EnumMember: - case SyntaxKind.ExportAssignment: - case SyntaxKind.SourceFile: - case SyntaxKind.JsxExpression: - case SyntaxKind.JsxElement: - case SyntaxKind.JsxSelfClosingElement: - case SyntaxKind.JsxAttribute: - case SyntaxKind.JsxSpreadAttribute: - case SyntaxKind.JsxOpeningElement: - forEachChild(node, checkFunctionAndClassExpressionBodies); - break; + function checkNodeDeferred(node: Node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + + function checkDeferredNodes() { + for (const node of deferredNodes) { + switch (node.kind) { + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + checkAccessorDeferred(node); + break; + case SyntaxKind.ClassExpression: + checkClassExpressionDeferred(node); + break; + } } } @@ -14096,22 +15932,25 @@ namespace ts { 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; + if (compilerOptions.skipDefaultLibCheck) { + // If the user specified '--noLib' and a file has a '/// ', + // then we should treat that file as a default lib. + if (node.hasNoDefaultLib) { + return; + } } // Grammar checking checkGrammarSourceFile(node); - emitExtends = false; - emitDecorate = false; - emitParam = false; potentialThisCollisions.length = 0; + deferredNodes = []; forEach(node.statements, checkSourceElement); - checkFunctionAndClassExpressionBodies(node); + checkDeferredNodes(); + deferredNodes = undefined; - if (isExternalModule(node)) { + if (isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -14120,26 +15959,6 @@ namespace ts { potentialThisCollisions.length = 0; } - if (emitExtends) { - links.flags |= NodeCheckFlags.EmitExtends; - } - - if (emitDecorate) { - links.flags |= NodeCheckFlags.EmitDecorate; - } - - if (emitParam) { - links.flags |= NodeCheckFlags.EmitParam; - } - - if (emitAwaiter) { - links.flags |= NodeCheckFlags.EmitAwaiter; - } - - if (emitGenerator || (emitAwaiter && languageVersion < ScriptTarget.ES6)) { - links.flags |= NodeCheckFlags.EmitGenerator; - } - links.flags |= NodeCheckFlags.TypeChecked; } } @@ -14214,7 +16033,7 @@ namespace ts { switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalModule(location)) { + if (!isExternalOrCommonJsModule(location)) { break; } case SyntaxKind.ModuleDeclaration: @@ -14228,8 +16047,8 @@ namespace ts { if (className) { copySymbol(location.symbol, meaning); } - // fall through; this fall-through is necessary because we would like to handle - // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration + // fall through; this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: // If we didn't come from static member of class or interface, @@ -14324,6 +16143,22 @@ namespace ts { return node.parent && node.parent.kind === SyntaxKind.ExpressionWithTypeArguments; } + function forEachEnclosingClass(node: Node, callback: (node: Node) => T): T { + let result: T; + + while (true) { + node = getContainingClass(node); + if (!node) break; + if (result = callback(node)) break; + } + + return result; + } + + function isNodeWithinClass(node: Node, classDeclaration: ClassLikeDeclaration) { + return !!forEachEnclosingClass(node, n => n === classDeclaration); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide: EntityName): ImportEqualsDeclaration | ExportAssignment { while (nodeOnRightSide.parent.kind === SyntaxKind.QualifiedName) { nodeOnRightSide = nodeOnRightSide.parent; @@ -14349,6 +16184,20 @@ namespace ts { return getSymbolOfNode(entityName.parent); } + if (isInJavaScriptFile(entityName) && entityName.parent.kind === SyntaxKind.PropertyAccessExpression) { + const specialPropertyAssignmentKind = getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case SpecialPropertyAssignmentKind.ExportsProperty: + case SpecialPropertyAssignmentKind.PrototypeProperty: + return getSymbolOfNode(entityName.parent); + case SpecialPropertyAssignmentKind.ThisProperty: + case SpecialPropertyAssignmentKind.ModuleExports: + return getSymbolOfNode(entityName.parent.parent); + default: + // Fall through if it is not a special property assignment + } + } + if (entityName.parent.kind === SyntaxKind.ExportAssignment) { return resolveEntityName(entityName, /*all meanings*/ SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); @@ -14384,11 +16233,6 @@ namespace ts { meaning |= SymbolFlags.Alias; return resolveEntityName(entityName, meaning); } - else if ((entityName.parent.kind === SyntaxKind.JsxOpeningElement) || - (entityName.parent.kind === SyntaxKind.JsxSelfClosingElement) || - (entityName.parent.kind === SyntaxKind.JsxClosingElement)) { - return getJsxElementTagSymbol(entityName.parent); - } else if (isExpression(entityName)) { if (nodeIsMissing(entityName)) { // Missing entity name. @@ -14396,6 +16240,10 @@ namespace ts { } if (entityName.kind === SyntaxKind.Identifier) { + if (isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + return getIntrinsicTagSymbol(entityName.parent); + } + // Include aliases in the meaning, this ensures that we do not follow aliases to where they point and instead // return the alias symbol. const meaning: SymbolFlags = SymbolFlags.Value | SymbolFlags.Alias; @@ -14453,8 +16301,8 @@ namespace ts { : getSymbolOfPartOfRightHandSideOfImportEquals(node); } else if (node.parent.kind === SyntaxKind.BindingElement && - node.parent.parent.kind === SyntaxKind.ObjectBindingPattern && - node === (node.parent).propertyName) { + node.parent.parent.kind === SyntaxKind.ObjectBindingPattern && + node === (node.parent).propertyName) { const typeOfPattern = getTypeOfNode(node.parent.parent); const propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, (node).text); @@ -14475,6 +16323,9 @@ namespace ts { const type = isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; + case SyntaxKind.ThisType: + return getTypeFromTypeNode(node).symbol; + case SyntaxKind.ConstructorKeyword: // constructor keyword for an overload, should take us to the definition if it exist const constructorDeclaration = node.parent; @@ -14491,7 +16342,7 @@ namespace ts { (node.parent).moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } - // Fall through + // Fall through case SyntaxKind.NumericLiteral: // index access @@ -14512,11 +16363,18 @@ namespace ts { // This is necessary as an identifier in short-hand property assignment can contains two meaning: // property name and property value. if (location && location.kind === SyntaxKind.ShorthandPropertyAssignment) { - return resolveEntityName((location).name, SymbolFlags.Value); + return resolveEntityName((location).name, SymbolFlags.Value | SymbolFlags.Alias); } return undefined; } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node: ExportSpecifier): Symbol { + return (node.parent.parent).moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); + } + function getTypeOfNode(node: Node): Type { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further @@ -14633,6 +16491,35 @@ namespace ts { return getReferencedValueSymbol(node) === argumentsSymbol; } + function moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean { + let moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol) { + // module not found - be conservative + return true; + } + + const hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + + const symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & SymbolFlags.Value) + : forEachValue(getExportsOfModule(moduleSymbol), isValue); + } + + return symbolLinks.exportsSomeValue; + + function isValue(s: Symbol): boolean { + s = resolveSymbol(s); + return s && !!(s.flags & SymbolFlags.Value); + } + } + // 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 { @@ -14669,42 +16556,61 @@ namespace ts { 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 { + function isSymbolOfDeclarationWithCollidingName(symbol: Symbol): boolean { if (symbol.flags & SymbolFlags.BlockScoped) { const links = getSymbolLinks(symbol); - if (links.isNestedRedeclaration === undefined) { + if (links.isDeclarationWithCollidingName === undefined) { const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); - links.isNestedRedeclaration = isStatementWithLocals(container) && - !!resolveName(container.parent, symbol.name, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (isStatementWithLocals(container)) { + const nodeLinks = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.name, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { + // redeclaration - always should be renamed + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks.flags & NodeCheckFlags.CapturedBlockScopedBinding) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + const isDeclaredInLoop = nodeLinks.flags & NodeCheckFlags.BlockScopedBindingInLoop; + const inLoopInitializer = isIterationStatement(container, /*lookInLabeledStatements*/ false); + const inLoopBodyBlock = container.kind === SyntaxKind.Block && isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + + links.isDeclarationWithCollidingName = !isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } } - return links.isNestedRedeclaration; + return links.isDeclarationWithCollidingName; } return false; } // When resolved as an expression identifier, if the given node references a nested block scoped entity with - // a name that hides an existing name, return the declaration of that entity. Otherwise, return undefined. - function getReferencedNestedRedeclaration(node: Identifier): Declaration { + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(node: Identifier): Declaration { const symbol = getReferencedValueSymbol(node); - return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + return symbol && isSymbolOfDeclarationWithCollidingName(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)); + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(node: Declaration): boolean { + return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); } function isValueAliasDeclaration(node: Node): boolean { @@ -14739,7 +16645,7 @@ namespace ts { if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } - // const enums and modules that contain only const enums are not considered values from the emit perespective + // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true return target !== unknownSymbol && target && @@ -14836,22 +16742,22 @@ namespace ts { else if (type.flags & TypeFlags.Any) { return TypeReferenceSerializationKind.ObjectType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.Void)) { + else if (isTypeOfKind(type, TypeFlags.Void)) { return TypeReferenceSerializationKind.VoidType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.Boolean)) { + else if (isTypeOfKind(type, TypeFlags.Boolean)) { return TypeReferenceSerializationKind.BooleanType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.NumberLike)) { + else if (isTypeOfKind(type, TypeFlags.NumberLike)) { return TypeReferenceSerializationKind.NumberLikeType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.StringLike)) { + else if (isTypeOfKind(type, TypeFlags.StringLike)) { return TypeReferenceSerializationKind.StringLikeType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.Tuple)) { + else if (isTypeOfKind(type, TypeFlags.Tuple)) { return TypeReferenceSerializationKind.ArrayLikeType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.ESSymbol)) { + else if (isTypeOfKind(type, TypeFlags.ESSymbol)) { return TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -14881,10 +16787,17 @@ namespace ts { } function writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - const type = getTypeOfExpression(expr); + const type = getWidenedType(getTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } + function writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { + const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); + resolveBaseTypesOfClass(classType); + const baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; + getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); + } + function hasGlobalName(name: string): boolean { return hasProperty(globals, name); } @@ -14901,26 +16814,12 @@ namespace ts { return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } - function instantiateSingleCallFunctionType(functionType: Type, typeArguments: Type[]): Type { - if (functionType === unknownType) { - return unknownType; - } - - const signature = getSingleCallSignature(functionType); - if (!signature) { - return unknownType; - } - - const instantiatedSignature = getSignatureInstantiation(signature, typeArguments); - return getOrCreateTypeFromSignature(instantiatedSignature); - } - function createResolver(): EmitResolver { return { getReferencedExportContainer, getReferencedImportDeclaration, - getReferencedNestedRedeclaration, - isNestedRedeclaration, + getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName, isValueAliasDeclaration, hasGlobalName, isReferencedAliasDeclaration, @@ -14931,6 +16830,7 @@ namespace ts { writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression, + writeBaseConstructorTypeOfClass, isSymbolAccessible, isEntityNameVisible, getConstantValue, @@ -14938,28 +16838,58 @@ namespace ts { getReferencedValueDeclaration, getTypeReferenceSerializationKind, isOptionalParameter, - isArgumentsLocalBinding + moduleExportsSomeValue, + isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration }; } + function getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile { + const specifier = getExternalModuleName(declaration); + const moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + if (!moduleSymbol) { + return undefined; + } + return getDeclarationOfKind(moduleSymbol, SyntaxKind.SourceFile) as SourceFile; + } + function initializeTypeChecker() { // Bind all source files and propagate errors forEach(host.getSourceFiles(), file => { bindSourceFile(file, compilerOptions); }); + let augmentations: LiteralExpression[][]; // Initialize global symbol table forEach(host.getSourceFiles(), file => { - if (!isExternalModule(file)) { + if (!isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.wasReferenced && file.symbol && file.symbol.globalExports) { + mergeSymbolTable(globals, file.symbol.globalExports); + } }); - // Initialize special symbols + if (augmentations) { + // merge module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (const list of augmentations) { + for (const augmentation of list) { + mergeModuleAugmentation(augmentation); + } + } + } + + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); getSymbolLinks(unknownSymbol).type = unknownType; - globals[undefinedSymbol.name] = undefinedSymbol; + // Initialize special types globalArrayType = getGlobalType("Array", /*arity*/ 1); globalObjectType = getGlobalType("Object"); @@ -15006,6 +16936,10 @@ namespace ts { } anyArrayType = createArrayType(anyType); + + const symbol = getGlobalSymbol("ReadonlyArray", SymbolFlags.Type, /*diagnostic*/ undefined); + globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; } function createInstantiatedPromiseLikeType(): ObjectType { @@ -15036,7 +16970,12 @@ namespace ts { return false; } if (!nodeCanBeDecorated(node)) { - return grammarErrorOnFirstToken(node, Diagnostics.Decorators_are_not_valid_here); + if (node.kind === SyntaxKind.MethodDeclaration && !ts.nodeIsPresent((node).body)) { + return grammarErrorOnFirstToken(node, Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, Diagnostics.Decorators_are_not_valid_here); + } } else if (node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor) { const accessors = getAllAccessorDeclarations((node.parent).members, node); @@ -15092,23 +17031,32 @@ namespace ts { return; } - let lastStatic: Node, lastPrivate: Node, lastProtected: Node, lastDeclare: Node, lastAsync: Node; + let lastStatic: Node, lastPrivate: Node, lastProtected: Node, lastDeclare: Node, lastAsync: Node, lastReadonly: Node; let flags = 0; for (const modifier of node.modifiers) { + if (modifier.kind !== SyntaxKind.ReadonlyKeyword) { + if (node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.MethodSignature) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_member, tokenToString(modifier.kind)); + } + if (node.kind === SyntaxKind.IndexSignature) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_index_signature, tokenToString(modifier.kind)); + } + } switch (modifier.kind) { + case SyntaxKind.ConstKeyword: + if (node.kind !== SyntaxKind.EnumDeclaration && node.parent.kind === SyntaxKind.ClassDeclaration) { + return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(SyntaxKind.ConstKeyword)); + } + break; case SyntaxKind.PublicKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: - let text: string; - if (modifier.kind === SyntaxKind.PublicKeyword) { - text = "public"; - } - else if (modifier.kind === SyntaxKind.ProtectedKeyword) { - text = "protected"; + let text = visibilityToString(modifierToFlag(modifier.kind)); + + if (modifier.kind === SyntaxKind.ProtectedKeyword) { lastProtected = modifier; } - else { - text = "private"; + else if (modifier.kind === SyntaxKind.PrivateKeyword) { lastPrivate = modifier; } @@ -15118,11 +17066,14 @@ namespace ts { else if (flags & NodeFlags.Static) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } + else if (flags & NodeFlags.Readonly) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } else if (flags & NodeFlags.Async) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } else if (node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { - return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & NodeFlags.Abstract) { if (modifier.kind === SyntaxKind.PrivateKeyword) { @@ -15139,11 +17090,14 @@ namespace ts { if (flags & NodeFlags.Static) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "static"); } + else if (flags & NodeFlags.Readonly) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } else if (flags & NodeFlags.Async) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } else if (node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { - return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } else if (node.kind === SyntaxKind.Parameter) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); @@ -15155,6 +17109,17 @@ namespace ts { lastStatic = modifier; break; + case SyntaxKind.ReadonlyKeyword: + if (flags & NodeFlags.Readonly) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== SyntaxKind.PropertyDeclaration && node.kind !== SyntaxKind.PropertySignature && node.kind !== SyntaxKind.IndexSignature) { + return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= NodeFlags.Readonly; + lastReadonly = modifier; + break; + case SyntaxKind.ExportKeyword: if (flags & NodeFlags.Export) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "export"); @@ -15202,8 +17167,11 @@ namespace ts { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "abstract"); } if (node.kind !== SyntaxKind.ClassDeclaration) { - if (node.kind !== SyntaxKind.MethodDeclaration) { - return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); + if (node.kind !== SyntaxKind.MethodDeclaration && + node.kind !== SyntaxKind.PropertyDeclaration && + node.kind !== SyntaxKind.GetAccessor && + node.kind !== SyntaxKind.SetAccessor) { + return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } if (!(node.parent.kind === SyntaxKind.ClassDeclaration && node.parent.flags & NodeFlags.Abstract)) { return grammarErrorOnNode(modifier, Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); @@ -15242,15 +17210,12 @@ namespace ts { if (flags & NodeFlags.Abstract) { return grammarErrorOnNode(lastStatic, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & NodeFlags.Protected) { - return grammarErrorOnNode(lastProtected, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); - } - else if (flags & NodeFlags.Private) { - return grammarErrorOnNode(lastPrivate, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); - } else if (flags & NodeFlags.Async) { return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } + else if (flags & NodeFlags.Readonly) { + return grammarErrorOnNode(lastReadonly, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } return; } else if ((node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration) && flags & NodeFlags.Ambient) { @@ -15396,15 +17361,9 @@ namespace ts { } } - function checkGrammarForIndexSignatureModifier(node: SignatureDeclaration): void { - if (node.flags & NodeFlags.Modifier) { - grammarErrorOnFirstToken(node, Diagnostics.Modifiers_not_permitted_on_index_signature_members); - } - } - function checkGrammarIndexSignature(node: SignatureDeclaration) { // Prevent cascading error by short-circuit - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node) || checkGrammarForIndexSignatureModifier(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); } function checkGrammarForAtLeastOneTypeArgument(node: Node, typeArguments: NodeArray): boolean { @@ -15550,8 +17509,8 @@ namespace ts { const seen: Map = {}; const Property = 1; const GetAccessor = 2; - const SetAccesor = 4; - const GetOrSetAccessor = GetAccessor | SetAccesor; + const SetAccessor = 4; + const GetOrSetAccessor = GetAccessor | SetAccessor; for (const prop of node.properties) { const name = prop.name; @@ -15568,7 +17527,14 @@ namespace ts { return grammarErrorOnNode((prop).equalsToken, Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } - // ECMA-262 11.1.5 Object Initialiser + // Modifiers are never allowed on properties except for 'async' on a method declaration + forEach(prop.modifiers, mod => { + if (mod.kind !== SyntaxKind.AsyncKeyword || prop.kind !== SyntaxKind.MethodDeclaration) { + grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod)); + } + }); + + // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and // IsDataDescriptor(propId.descriptor) is true. @@ -15578,10 +17544,10 @@ namespace ts { // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields let currentKind: number; if (prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment) { - // Grammar checking for computedPropertName and shorthandPropertyAssignment + // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, (prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === SyntaxKind.NumericLiteral) { - checkGrammarNumericLiteral(name); + checkGrammarNumericLiteral(name); } currentKind = Property; } @@ -15592,7 +17558,7 @@ namespace ts { currentKind = GetAccessor; } else if (prop.kind === SyntaxKind.SetAccessor) { - currentKind = SetAccesor; + currentKind = SetAccessor; } else { Debug.fail("Unexpected syntax kind:" + prop.kind); @@ -15652,13 +17618,27 @@ namespace ts { if (forInOrOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) { const variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { - if (variableList.declarations.length > 1) { + const declarations = variableList.declarations; + + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + + if (declarations.length > 1) { const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } - const firstDeclaration = variableList.declarations[0]; + const firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer @@ -15685,7 +17665,7 @@ namespace ts { else if (isInAmbientContext(accessor)) { return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } - else if (accessor.body === undefined) { + else if (accessor.body === undefined && !(accessor.flags & NodeFlags.Abstract)) { return grammarErrorAtPos(getSourceFileOfNode(accessor), accessor.end - 1, ";".length, Diagnostics._0_expected, "{"); } else if (accessor.typeParameters) { @@ -15720,7 +17700,7 @@ namespace ts { } function checkGrammarForNonSymbolComputedProperty(node: DeclarationName, message: DiagnosticMessage) { - if (node.kind === SyntaxKind.ComputedPropertyName && !isWellKnownSymbolSyntactically((node).expression)) { + if (isDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -15737,7 +17717,7 @@ namespace ts { return true; } else if (node.body === undefined) { - return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, Diagnostics._0_expected, "{"); + return grammarErrorAtPos(getSourceFileOfNode(node), node.end - 1, ";".length, Diagnostics._0_expected, "{"); } } @@ -15857,7 +17837,7 @@ namespace ts { } } - const checkLetConstNames = languageVersion >= ScriptTarget.ES6 && (isLet(node) || isConst(node)); + const checkLetConstNames = (isLet(node) || isConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". @@ -15871,7 +17851,7 @@ namespace ts { function checkGrammarNameInLetOrConstDeclarations(name: Identifier | BindingPattern): boolean { if (name.kind === SyntaxKind.Identifier) { - if ((name).text === "let") { + if ((name).originalKeywordKind === SyntaxKind.LetKeyword) { return grammarErrorOnNode(name, Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); } } @@ -15924,25 +17904,6 @@ namespace ts { } } - function isIntegerLiteral(expression: Expression): boolean { - if (expression.kind === SyntaxKind.PrefixUnaryExpression) { - const unaryExpression = expression; - if (unaryExpression.operator === SyntaxKind.PlusToken || unaryExpression.operator === SyntaxKind.MinusToken) { - expression = unaryExpression.operand; - } - } - if (expression.kind === SyntaxKind.NumericLiteral) { - // Allows for scientific notation since literalExpression.text was formed by - // coercing a number to a string. Sometimes this coercion can yield a string - // in scientific notation. - // We also don't need special logic for hex because a hex integer is converted - // to decimal when it is coerced. - return /^[0-9]+([eE]\+?[0-9]+)?$/.test((expression).text); - } - - return false; - } - function hasParseDiagnostics(sourceFile: SourceFile): boolean { return sourceFile.parseDiagnostics.length > 0; } @@ -15971,11 +17932,6 @@ namespace ts { } } - 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); @@ -15999,11 +17955,17 @@ namespace ts { if (checkGrammarForNonSymbolComputedProperty(node.name, Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, Diagnostics.An_interface_property_cannot_have_an_initializer); + } } else if (node.parent.kind === SyntaxKind.TypeLiteral) { if (checkGrammarForNonSymbolComputedProperty(node.name, Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } } if (isInAmbientContext(node) && node.initializer) { @@ -16068,7 +18030,7 @@ namespace ts { // We are either parented by another statement, or some sort of block. // If we're in a block, we only want to really report an error once - // to prevent noisyness. So use a bit on the block to indicate if + // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // if (node.parent.kind === SyntaxKind.Block || node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { @@ -16086,9 +18048,9 @@ namespace ts { } } - function checkGrammarNumericLiteral(node: Identifier): boolean { + function checkGrammarNumericLiteral(node: LiteralExpression): boolean { // Grammar checking - if (node.flags & NodeFlags.OctalLiteral && languageVersion >= ScriptTarget.ES5) { + if (node.isOctalLiteral && languageVersion >= ScriptTarget.ES5) { return grammarErrorOnNode(node, Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 3fca97c0450..b9ec3c1da5e 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -17,6 +17,12 @@ namespace ts { type: "boolean", description: Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "declarationDir", + type: "string", + isFilePath: true, + paramType: Diagnostics.DIRECTORY, + }, { name: "diagnostics", type: "boolean", @@ -52,7 +58,11 @@ namespace ts { }, paramType: Diagnostics.KIND, description: Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, - error: Diagnostics.Argument_for_jsx_must_be_preserve_or_react + }, + { + name: "reactNamespace", + type: "string", + description: Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit }, { name: "listFiles", @@ -66,13 +76,14 @@ namespace ts { name: "mapRoot", type: "string", isFilePath: true, - description: Diagnostics.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, paramType: Diagnostics.LOCATION, }, { name: "module", shortName: "m", type: { + "none": ModuleKind.None, "commonjs": ModuleKind.CommonJS, "amd": ModuleKind.AMD, "system": ModuleKind.System, @@ -82,7 +93,6 @@ namespace ts { }, description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: Diagnostics.KIND, - error: Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015 }, { name: "newLine", @@ -90,9 +100,8 @@ namespace ts { "crlf": NewLineKind.CarriageReturnLineFeed, "lf": NewLineKind.LineFeed }, - description: Diagnostics.Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + description: Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, paramType: Diagnostics.NEWLINE, - error: Diagnostics.Argument_for_newLine_option_must_be_CRLF_or_LF }, { name: "noEmit", @@ -174,8 +183,8 @@ namespace ts { name: "rootDir", type: "string", isFilePath: true, - description: Diagnostics.Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, paramType: Diagnostics.LOCATION, + description: Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, }, { name: "isolatedModules", @@ -190,7 +199,7 @@ namespace ts { name: "sourceRoot", type: "string", isFilePath: true, - description: Diagnostics.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + description: Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, paramType: Diagnostics.LOCATION, }, { @@ -219,9 +228,8 @@ namespace ts { "es6": ScriptTarget.ES6, "es2015": ScriptTarget.ES2015, }, - description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental, + description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: Diagnostics.VERSION, - error: Diagnostics.Argument_for_target_option_must_be_ES3_ES5_or_ES2015 }, { name: "version", @@ -250,10 +258,9 @@ namespace ts { name: "moduleResolution", type: { "node": ModuleResolutionKind.NodeJs, - "classic": ModuleResolutionKind.Classic + "classic": ModuleResolutionKind.Classic, }, - description: Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, - error: Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic, + description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, }, { name: "allowUnusedLabels", @@ -279,6 +286,80 @@ namespace ts { name: "forceConsistentCasingInFileNames", type: "boolean", description: Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "baseUrl", + type: "string", + isFilePath: true, + description: Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + isTSConfigOnly: true + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { + name: "rootDirs", + type: "string", + isFilePath: true + } + }, + { + name: "traceModuleResolution", + type: "boolean", + description: Diagnostics.Enable_tracing_of_the_module_resolution_process + }, + { + name: "allowJs", + type: "boolean", + description: Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + description: Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "noImplicitUseStrict", + type: "boolean", + description: Diagnostics.Do_not_emit_use_strict_directives_in_module_output + }, + { + name: "strictNullChecks", + type: "boolean", + description: Diagnostics.Enable_strict_null_checks + } + ]; + + /* @internal */ + export let typingOptionDeclarations: CommandLineOption[] = [ + { + name: "enableAutoDiscovery", + type: "boolean", + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } } ]; @@ -308,6 +389,16 @@ namespace ts { return optionNameMapCache; } + /* @internal */ + export function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic { + const namesOfType: string[] = []; + forEachKey(opt.type, key => { + namesOfType.push(` '${key}'`); + }); + + return createCompilerDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, namesOfType); + } + export function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine { const options: CompilerOptions = {}; const fileNames: string[] = []; @@ -324,7 +415,8 @@ namespace ts { function parseStrings(args: string[]) { let i = 0; while (i < args.length) { - let s = args[i++]; + let s = args[i]; + i++; if (s.charCodeAt(0) === CharacterCodes.at) { parseResponseFile(s.slice(1)); } @@ -339,31 +431,37 @@ namespace ts { if (hasProperty(optionNameMap, s)) { const opt = optionNameMap[s]; - // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). - if (!args[i] && opt.type !== "boolean") { - errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + if (opt.isTSConfigOnly) { + errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); } + else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + } - switch (opt.type) { - case "number": - options[opt.name] = parseInt(args[i++]); - break; - case "boolean": - options[opt.name] = true; - break; - case "string": - options[opt.name] = args[i++] || ""; - break; - // If not a primitive, the possible types are specified in what is effectively a map of options. - default: - let map = >opt.type; - let key = (args[i++] || "").toLowerCase(); - if (hasProperty(map, key)) { - options[opt.name] = map[key]; - } - else { - errors.push(createCompilerDiagnostic((opt).error)); - } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + options[opt.name] = true; + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + case "list": + options[opt.name] = parseListTypeOption(opt, args[i]); + i++; + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + options[opt.name] = parseCustomTypeOption(opt, args[i]); + i++; + break; + } } } else { @@ -373,6 +471,29 @@ namespace ts { else { fileNames.push(s); } + + function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string) { + const key = (value || "").trim().toLowerCase(); + const map = opt.type; + if (hasProperty(map, key)) { + return map[key]; + } + else { + errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + + function parseListTypeOption(opt: CommandLineOptionOfListType, value: string): (string | number)[] { + const values = (value || "").trim().split(","); + switch (opt.element.type) { + case "number": + return ts.map(values, parseInt); + case "string": + return ts.map(values, v => v || ""); + default: + return filter(map(values, v => parseCustomTypeOption(opt.element, v)), v => !!v); + } + } } } @@ -440,7 +561,6 @@ namespace ts { } } - /** * Remove the comments from a json like text. * Comments can be single line comments (starting with # or //) or multiline comments using / * * / @@ -466,7 +586,6 @@ namespace ts { return output; } - /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -474,19 +593,25 @@ namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine { - const { options, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath); + export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string): ParsedCommandLine { + const errors: Diagnostic[] = []; + const compilerOptions: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName); + const options = extend(existingOptions, compilerOptions); + const typingOptions: TypingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); + + const fileNames = getFileNames(errors); return { options, - fileNames: getFileNames(), + fileNames, + typingOptions, errors }; - function getFileNames(): string[] { + function getFileNames(errors: Diagnostic[]): string[] { let fileNames: string[] = []; if (hasProperty(json, "files")) { - if (json["files"] instanceof Array) { + if (isArray(json["files"])) { fileNames = map(json["files"], s => combinePaths(basePath, s)); } else { @@ -494,36 +619,96 @@ namespace ts { } } else { - const exclude = json["exclude"] instanceof Array ? map(json["exclude"], normalizeSlashes) : undefined; - const sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); - for (let i = 0; i < sysFiles.length; i++) { - const name = sysFiles[i]; - if (fileExtensionIs(name, ".d.ts")) { - const baseName = name.substr(0, name.length - ".d.ts".length); - if (!contains(sysFiles, baseName + ".tsx") && !contains(sysFiles, baseName + ".ts")) { - fileNames.push(name); - } - } - else if (fileExtensionIs(name, ".ts")) { - if (!contains(sysFiles, name + "x")) { - fileNames.push(name); - } - } - else { - fileNames.push(name); + const filesSeen: Map = {}; + + let exclude: string[] = []; + if (isArray(json["exclude"])) { + exclude = json["exclude"]; + } + else { + // by default exclude node_modules, and any specificied output directory + exclude = ["node_modules"]; + const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + exclude.push(outDir); } } + exclude = map(exclude, normalizeSlashes); + + const supportedExtensions = getSupportedExtensions(options); + Debug.assert(indexOf(supportedExtensions, ".ts") < indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); + + // Get files of supported extensions in their order of resolution + for (const extension of supportedExtensions) { + const filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); + for (const fileName of filesInDirWithExtension) { + // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension, + // lets pick them when its turn comes up + if (extension === ".ts" && fileExtensionIs(fileName, ".d.ts")) { + continue; + } + + // Skip over any minified JavaScript files (ending in ".min.js") + if (/\.min\.js$/.test(fileName)) { + continue; + } + + // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) + // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation + if (extension === ".d.ts" || (options.allowJs && contains(supportedJavascriptExtensions, extension))) { + const baseName = fileName.substr(0, fileName.length - extension.length); + if (hasProperty(filesSeen, baseName + ".ts") || hasProperty(filesSeen, baseName + ".tsx")) { + continue; + } + } + + filesSeen[fileName] = true; + fileNames.push(fileName); + } + } + } + if (hasProperty(json, "excludes") && !hasProperty(json, "exclude")) { + errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } return fileNames; } } - export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string): { options: CompilerOptions, errors: Diagnostic[] } { - const options: CompilerOptions = {}; + export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions, errors: Diagnostic[] } { const errors: Diagnostic[] = []; + const options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options, errors }; + } + + export function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions, errors: Diagnostic[] } { + const errors: Diagnostic[] = []; + const options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options, errors }; + } + + function convertCompilerOptionsFromJsonWorker(jsonOptions: any, + basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions { + + const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {}; + convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_compiler_option_0, errors); + return options; + } + + function convertTypingOptionsFromJsonWorker(jsonOptions: any, + basePath: string, errors: Diagnostic[], configFileName?: string): TypingOptions { + + const options: TypingOptions = getBaseFileName(configFileName) === "jsconfig.json" + ? { enableAutoDiscovery: true, include: [], exclude: [] } + : { enableAutoDiscovery: false, include: [], exclude: [] }; + convertOptionsFromJson(typingOptionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_typing_option_0, errors); + return options; + } + + function convertOptionsFromJson(optionDeclarations: CommandLineOption[], jsonOptions: any, basePath: string, + defaultOptions: CompilerOptions | TypingOptions, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) { if (!jsonOptions) { - return { options, errors }; + return ; } const optionNameMap = arrayToMap(optionDeclarations, opt => opt.name); @@ -531,37 +716,50 @@ namespace ts { for (const id in jsonOptions) { if (hasProperty(optionNameMap, id)) { const opt = optionNameMap[id]; - const optType = opt.type; - let value = jsonOptions[id]; - const expectedType = typeof optType === "string" ? optType : "string"; - if (typeof value === expectedType) { - if (typeof optType !== "string") { - const key = value.toLowerCase(); - if (hasProperty(optType, key)) { - value = optType[key]; - } - else { - errors.push(createCompilerDiagnostic((opt).error)); - value = 0; - } - } - if (opt.isFilePath) { - value = normalizePath(combinePaths(basePath, value)); - if (value === "") { - value = "."; - } - } - options[opt.name] = value; - } - else { - errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, id, expectedType)); - } + defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); } else { - errors.push(createCompilerDiagnostic(Diagnostics.Unknown_compiler_option_0, id)); + errors.push(createCompilerDiagnostic(diagnosticMessage, id)); } } + } - return { options, errors }; + function convertJsonOption(opt: CommandLineOption, value: any, basePath: string, errors: Diagnostic[]): CompilerOptionsValue { + const optType = opt.type; + const expectedType = typeof optType === "string" ? optType : "string"; + if (optType === "list" && isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (typeof value === expectedType) { + if (typeof optType !== "string") { + return convertJsonOptionOfCustomType(opt, value, errors); + } + else { + if (opt.isFilePath) { + value = normalizePath(combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + } + return value; + } + else { + errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, expectedType)); + } + } + + function convertJsonOptionOfCustomType(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) { + const key = value.toLowerCase(); + if (hasProperty(opt.type, key)) { + return opt.type[key]; + } + else { + errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + + function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: any[], basePath: string, errors: Diagnostic[]): any[] { + return filter(map(values, v => convertJsonOption(option.element, v, basePath, errors)), v => !!v); } } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 5c882fb5304..76306e290ca 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -74,8 +74,6 @@ namespace ts { GreaterThan = 1 } - export interface StringSet extends Map { } - /** * Iterates through 'array' by index and performs the callback on each element of array until the callback * returns a truthy value, then returns that value. @@ -244,9 +242,17 @@ namespace ts { const count = array.length; if (count > 0) { let pos = 0; - let result = arguments.length <= 2 ? array[pos++] : initial; + let result: T | U; + if (arguments.length <= 2) { + result = array[pos]; + pos++; + } + else { + result = initial; + } while (pos < count) { - result = f(result, array[pos++]); + result = f(result, array[pos]); + pos++; } return result; } @@ -260,9 +266,17 @@ namespace ts { if (array) { let pos = array.length - 1; if (pos >= 0) { - let result = arguments.length <= 2 ? array[pos--] : initial; + let result: T | U; + if (arguments.length <= 2) { + result = array[pos]; + pos--; + } + else { + result = initial; + } while (pos >= 0) { - result = f(result, array[pos--]); + result = f(result, array[pos]); + pos--; } return result; } @@ -276,6 +290,14 @@ namespace ts { return hasOwnProperty.call(map, key); } + export function getKeys(map: Map): string[] { + const keys: string[] = []; + for (const key in map) { + keys.push(key); + } + return keys; + } + export function getProperty(map: Map, key: string): T { return hasOwnProperty.call(map, key) ? map[key] : undefined; } @@ -297,8 +319,8 @@ namespace ts { return result; } - export function extend(first: Map, second: Map): Map { - const result: Map = {}; + export function extend, T2 extends Map<{}>>(first: T1 , second: T2): T1 & T2 { + const result: T1 & T2 = {}; for (const id in first) { (result as any)[id] = first[id]; } @@ -356,6 +378,33 @@ namespace ts { return result; } + /** + * Reduce the properties of a map. + * + * @param map The map to reduce + * @param callback An aggregation function that is called for each entry in the map + * @param initial The initial value for the reduction. + */ + export function reduceProperties(map: Map, callback: (aggregate: U, value: T, key: string) => U, initial: U): U { + let result = initial; + if (map) { + for (const key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } + } + + return result; + } + + /** + * Tests whether a value is an array. + */ + export function isArray(value: any): value is any[] { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + export function memoize(callback: () => T): () => T { let value: T; return () => { @@ -410,6 +459,17 @@ namespace ts { }; } + /* internal */ + export function formatMessage(dummy: any, message: DiagnosticMessage): string { + let text = getLocaleSpecificMessage(message); + + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + + return text; + } + export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: any[]): Diagnostic; export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic { let text = getLocaleSpecificMessage(message); @@ -585,7 +645,9 @@ namespace ts { return path.substr(0, rootLength) + normalized.join(directorySeparator); } - export function getDirectoryPath(path: string) { + export function getDirectoryPath(path: Path): Path; + export function getDirectoryPath(path: string): string; + export function getDirectoryPath(path: string): any { return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(directorySeparator))); } @@ -625,7 +687,7 @@ namespace ts { } function getNormalizedPathComponentsOfUrl(url: string) { - // Get root length of http://www.website.com/folder1/foler2/ + // Get root length of http://www.website.com/folder1/folder2/ // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] @@ -653,7 +715,7 @@ namespace ts { const indexOfNextSlash = url.indexOf(directorySeparator, rootLength); if (indexOfNextSlash !== -1) { // Found the "/" after the website.com so the root is length of http://www.website.com/ - // and get components afetr the root normally like any other folder components + // and get components after the root normally like any other folder components rootLength = indexOfNextSlash + 1; return normalizedPathComponents(url, rootLength); } @@ -685,7 +747,8 @@ namespace ts { } // Find the component that differs - for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { + let joinStartIndex: number; + for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { break; } @@ -714,7 +777,7 @@ namespace ts { } export function getBaseFileName(path: string) { - if (!path) { + if (path === undefined) { return undefined; } const i = path.lastIndexOf(directorySeparator); @@ -735,21 +798,47 @@ namespace ts { return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } + export function ensureScriptKind(fileName: string, scriptKind?: ScriptKind): ScriptKind { + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt + // to get the ScriptKind from the file name. If it cannot be resolved + // from the file name then the default 'TS' script kind is returned. + return (scriptKind || getScriptKindFromFileName(fileName)) || ScriptKind.TS; + } + + export function getScriptKindFromFileName(fileName: string): ScriptKind { + const ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js": + return ScriptKind.JS; + case ".jsx": + return ScriptKind.JSX; + case ".ts": + return ScriptKind.TS; + case ".tsx": + return ScriptKind.TSX; + default: + return ScriptKind.Unknown; + } + } + /** * List of supported extensions in order of file resolution precedence. */ - export const supportedExtensions = [".ts", ".tsx", ".d.ts"]; - /** - * List of extensions that will be used to look for external modules. - * This list is kept separate from supportedExtensions to for cases when we'll allow to include .js files in compilation, - * but still would like to load only TypeScript files as modules - */ - export const moduleFileExtensions = supportedExtensions; + export const supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + export const supportedJavascriptExtensions = [".js", ".jsx"]; + const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions); - export function isSupportedSourceFileName(fileName: string) { + export function getSupportedExtensions(options?: CompilerOptions): string[] { + return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions; + } + + export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) { if (!fileName) { return false; } - for (const extension of supportedExtensions) { + for (const extension of getSupportedExtensions(compilerOptions)) { if (fileExtensionIs(fileName, extension)) { return true; } @@ -767,25 +856,9 @@ namespace ts { return path; } - const backslashOrDoubleQuote = /[\"\\]/g; - const escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - const escapedCharsMap: Map = { - "\0": "\\0", - "\t": "\\t", - "\v": "\\v", - "\f": "\\f", - "\b": "\\b", - "\r": "\\r", - "\n": "\\n", - "\\": "\\\\", - "\"": "\\\"", - "\u2028": "\\u2028", // lineSeparator - "\u2029": "\\u2029", // paragraphSeparator - "\u0085": "\\u0085" // nextLine - }; - export interface ObjectAllocator { - getNodeConstructor(kind: SyntaxKind): new (pos?: number, end?: number) => Node; + getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node; + getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile; getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol; getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type; getSignatureConstructor(): new (checker: TypeChecker) => Signature; @@ -804,17 +877,17 @@ namespace ts { function Signature(checker: TypeChecker) { } + function Node(kind: SyntaxKind, pos: number, end: number) { + this.kind = kind; + this.pos = pos; + this.end = end; + this.flags = NodeFlags.None; + this.parent = undefined; + } + export let objectAllocator: ObjectAllocator = { - getNodeConstructor: kind => { - function Node(pos: number, end: number) { - this.pos = pos; - this.end = end; - this.flags = NodeFlags.None; - this.parent = undefined; - } - Node.prototype = { kind }; - return Node; - }, + getNodeConstructor: () => Node, + getSourceFileConstructor: () => Node, getSymbolConstructor: () => Symbol, getTypeConstructor: () => Type, getSignatureConstructor: () => Signature @@ -846,7 +919,7 @@ namespace ts { } export function fail(message?: string): void { - Debug.assert(false, message); + Debug.assert(/*expression*/ false, message); } } @@ -859,4 +932,11 @@ namespace ts { } return copiedList; } + + export function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string { + return useCaseSensitivefileNames + ? ((fileName) => fileName) + : ((fileName) => fileName.toLowerCase()); + } + } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index ac91a39a78b..0a8b6615a23 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -18,7 +18,7 @@ namespace ts { referencePathsOutput: string; } - type GetSymbolAccessibilityDiagnostic = (symbolAccesibilityResult: SymbolAccessiblityResult) => SymbolAccessibilityDiagnostic; + type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic; interface EmitTextWriterWithSymbolWriter extends EmitTextWriter, SymbolWriter { getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic; @@ -31,13 +31,17 @@ namespace ts { } export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] { - const diagnostics: Diagnostic[] = []; - const jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); - emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; + const declarationDiagnostics = createDiagnosticCollection(); + forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); + return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); + + function getDeclarationDiagnosticsFromFile({ declarationFilePath }, sources: SourceFile[], isBundledEmit: boolean) { + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + } } - function emitDeclarations(host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit { + function emitDeclarations(host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection, declarationFilePath: string, + sourceFiles: SourceFile[], isBundledEmit: boolean): DeclarationEmit { const newLine = host.getNewLine(); const compilerOptions = host.getCompilerOptions(); @@ -45,18 +49,25 @@ namespace ts { let writeLine: () => void; let increaseIndent: () => void; let decreaseIndent: () => void; - let writeTextOfNode: (sourceFile: SourceFile, node: Node) => void; + let writeTextOfNode: (text: string, node: Node) => void; - let writer = createAndSetNewTextWriterWithSymbolWriter(); + let writer: EmitTextWriterWithSymbolWriter; + + createAndSetNewTextWriterWithSymbolWriter(); let enclosingDeclaration: Node; - let currentSourceFile: SourceFile; + let resultHasExternalModuleIndicator: boolean; + let currentText: string; + let currentLineMap: number[]; + let currentIdentifiers: Map; + let isCurrentFileExternalModule: boolean; let reportedDeclarationError = false; let errorNameNode: DeclarationName; const emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments; const emit = compilerOptions.stripInternal ? stripInternal : emitNode; + let noDeclare: boolean; - const moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; + let moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; let asynchronousSubModuleDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]; // Contains the reference paths that needs to go in the declaration file. @@ -64,84 +75,99 @@ namespace ts { // and we could be collecting these paths from multiple files into single one with --out option let referencePathsOutput = ""; - if (root) { - // Emitting just a single file, so emit references in this file only + // Emit references corresponding to each file + const emittedReferencedFiles: SourceFile[] = []; + let addedGlobalFileReference = false; + let allSourcesModuleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; + forEach(sourceFiles, sourceFile => { + // Dont emit for javascript file + if (isSourceFileJavaScript(sourceFile)) { + return; + } + + // Check what references need to be added if (!compilerOptions.noResolve) { - let addedGlobalFileReference = false; - forEach(root.referencedFiles, fileReference => { - const referencedFile = tryResolveScriptReference(host, root, fileReference); + forEach(sourceFile.referencedFiles, fileReference => { + const referencedFile = tryResolveScriptReference(host, sourceFile, fileReference); - // All the references that are not going to be part of same file - if (referencedFile && ((referencedFile.flags & NodeFlags.DeclarationFile) || // This is a declare file reference - shouldEmitToOwnFile(referencedFile, compilerOptions) || // This is referenced file is emitting its own js file - !addedGlobalFileReference)) { // Or the global out file corresponding to this reference was not added - - writeReferencePath(referencedFile); - if (!isExternalModuleOrDeclarationFile(referencedFile)) { + // Emit reference in dts, if the file reference was not already emitted + if (referencedFile && !contains(emittedReferencedFiles, referencedFile)) { + // Add a reference to generated dts file, + // global file reference is added only + // - if it is not bundled emit (because otherwise it would be self reference) + // - and it is not already added + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } + emittedReferencedFiles.push(referencedFile); } }); } - emitSourceFile(root); + resultHasExternalModuleIndicator = false; + if (!isBundledEmit || !isExternalModule(sourceFile)) { + noDeclare = false; + emitSourceFile(sourceFile); + } + else if (isExternalModule(sourceFile)) { + noDeclare = true; + write(`declare module "${getResolvedExternalModuleName(host, sourceFile)}" {`); + writeLine(); + increaseIndent(); + emitSourceFile(sourceFile); + decreaseIndent(); + write("}"); + writeLine(); + } // create asynchronous output for the importDeclarations if (moduleElementDeclarationEmitInfo.length) { const oldWriter = writer; forEach(moduleElementDeclarationEmitInfo, aliasEmitInfo => { - if (aliasEmitInfo.isVisible) { + if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { Debug.assert(aliasEmitInfo.node.kind === SyntaxKind.ImportDeclaration); createAndSetNewTextWriterWithSymbolWriter(); - Debug.assert(aliasEmitInfo.indent === 0); + Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); + for (let i = 0; i < aliasEmitInfo.indent; i++) { + increaseIndent(); + } writeImportDeclaration(aliasEmitInfo.node); aliasEmitInfo.asynchronousOutput = writer.getText(); + for (let i = 0; i < aliasEmitInfo.indent; i++) { + decreaseIndent(); + } } }); setWriter(oldWriter); + + allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); + moduleElementDeclarationEmitInfo = []; } - } - else { - // Emit references corresponding to this file - const emittedReferencedFiles: SourceFile[] = []; - forEach(host.getSourceFiles(), sourceFile => { - if (!isExternalModuleOrDeclarationFile(sourceFile)) { - // Check what references need to be added - if (!compilerOptions.noResolve) { - forEach(sourceFile.referencedFiles, fileReference => { - const referencedFile = tryResolveScriptReference(host, sourceFile, fileReference); - // If the reference file is a declaration file or an external module, emit that reference - if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) && - !contains(emittedReferencedFiles, referencedFile))) { // If the file reference was not already emitted - - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - - emitSourceFile(sourceFile); - } - }); - } + if (!isBundledEmit && isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + // in case if we didn't write any external module specifiers in .d.ts we need to emit something + // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. + write("export {};"); + writeLine(); + } + }); return { reportedDeclarationError, - moduleElementDeclarationEmitInfo, + moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput, }; function hasInternalAnnotation(range: CommentRange) { - const text = currentSourceFile.text; - const comment = text.substring(range.pos, range.end); + const comment = currentText.substring(range.pos, range.end); return comment.indexOf("@internal") >= 0; } function stripInternal(node: Node) { if (node) { - const leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos); + const leadingCommentRanges = getLeadingCommentRanges(currentText, node.pos); if (forEach(leadingCommentRanges, hasInternalAnnotation)) { return; } @@ -150,7 +176,7 @@ namespace ts { } } - function createAndSetNewTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter { + function createAndSetNewTextWriterWithSymbolWriter(): void { const writer = createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; @@ -162,7 +188,6 @@ namespace ts { writer.writeParameter = writer.write; writer.writeSymbol = writer.write; setWriter(writer); - return writer; } function setWriter(newWriter: EmitTextWriterWithSymbolWriter) { @@ -228,30 +253,30 @@ namespace ts { setWriter(oldWriter); } - function handleSymbolAccessibilityError(symbolAccesibilityResult: SymbolAccessiblityResult) { - if (symbolAccesibilityResult.accessibility === SymbolAccessibility.Accessible) { + function handleSymbolAccessibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === SymbolAccessibility.Accessible) { // write the aliases - if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccesibilityResult.aliasesToMakeVisible); + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); } } else { // Report error reportedDeclarationError = true; - const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); if (errorInfo) { if (errorInfo.typeName) { - diagnostics.push(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, + emitterDiagnostics.add(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, - getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), - symbolAccesibilityResult.errorSymbolName, - symbolAccesibilityResult.errorModuleName)); + getTextOfNodeFromSourceText(currentText, errorInfo.typeName), + symbolAccessibilityResult.errorSymbolName, + symbolAccessibilityResult.errorModuleName)); } else { - diagnostics.push(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, + emitterDiagnostics.add(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, - symbolAccesibilityResult.errorSymbolName, - symbolAccesibilityResult.errorModuleName)); + symbolAccessibilityResult.errorSymbolName, + symbolAccessibilityResult.errorModuleName)); } } } @@ -263,7 +288,8 @@ namespace ts { function reportInaccessibleThisError() { if (errorNameNode) { - diagnostics.push(createDiagnosticForNode(errorNameNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, + reportedDeclarationError = true; + emitterDiagnostics.add(createDiagnosticForNode(errorNameNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, declarationNameToString(errorNameNode))); } } @@ -321,10 +347,10 @@ namespace ts { function writeJsDocComments(declaration: Node) { if (declaration) { - const jsDocComments = getJsDocComments(declaration, currentSourceFile); - emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); + const jsDocComments = getJsDocCommentsFromText(declaration, currentText); + emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space - emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, writeCommentRange); + emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, writeCommentRange); } } @@ -341,9 +367,11 @@ namespace ts { case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.VoidKeyword: - case SyntaxKind.ThisKeyword: - case SyntaxKind.StringLiteral: - return writeTextOfNode(currentSourceFile, type); + case SyntaxKind.UndefinedKeyword: + case SyntaxKind.NullKeyword: + case SyntaxKind.ThisType: + case SyntaxKind.StringLiteralType: + return writeTextOfNode(currentText, type); case SyntaxKind.ExpressionWithTypeArguments: return emitExpressionWithTypeArguments(type); case SyntaxKind.TypeReference: @@ -375,14 +403,14 @@ namespace ts { function writeEntityName(entityName: EntityName | Expression) { if (entityName.kind === SyntaxKind.Identifier) { - writeTextOfNode(currentSourceFile, entityName); + writeTextOfNode(currentText, entityName); } else { const left = entityName.kind === SyntaxKind.QualifiedName ? (entityName).left : (entityName).expression; const right = entityName.kind === SyntaxKind.QualifiedName ? (entityName).right : (entityName).name; writeEntityName(left); write("."); - writeTextOfNode(currentSourceFile, right); + writeTextOfNode(currentText, right); } } @@ -417,7 +445,7 @@ namespace ts { } function emitTypePredicate(type: TypePredicateNode) { - writeTextOfNode(currentSourceFile, type.parameterName); + writeTextOfNode(currentText, type.parameterName); write(" is "); emitType(type.type); } @@ -466,9 +494,12 @@ namespace ts { } function emitSourceFile(node: SourceFile) { - currentSourceFile = node; + currentText = node.text; + currentLineMap = getLineStarts(node); + currentIdentifiers = node.identifiers; + isCurrentFileExternalModule = isExternalModule(node); enclosingDeclaration = node; - emitDetachedComments(currentSourceFile, writer, writeCommentRange, node, newLine, true /* remove comments */); + emitDetachedComments(currentText, currentLineMap, writer, writeCommentRange, node, newLine, true /* remove comments */); emitLines(node.statements); } @@ -478,13 +509,14 @@ namespace ts { // do not need to keep track of created temp names. function getExportDefaultTempVariableName(): string { const baseName = "_default"; - if (!hasProperty(currentSourceFile.identifiers, baseName)) { + if (!hasProperty(currentIdentifiers, baseName)) { return baseName; } let count = 0; while (true) { - const name = baseName + "_" + (++count); - if (!hasProperty(currentSourceFile.identifiers, name)) { + count++; + const name = baseName + "_" + count; + if (!hasProperty(currentIdentifiers, name)) { return name; } } @@ -493,7 +525,7 @@ namespace ts { function emitExportAssignment(node: ExportAssignment) { if (node.expression.kind === SyntaxKind.Identifier) { write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentSourceFile, node.expression); + writeTextOfNode(currentText, node.expression); } else { // Expression @@ -519,7 +551,7 @@ namespace ts { writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic(diagnostic: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getDefaultExportAccessibilityDiagnostic(diagnostic: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { return { diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: node @@ -537,7 +569,7 @@ namespace ts { } // Import equals declaration in internal module can become visible as part of any emit so lets make sure we add these irrespective else if (node.kind === SyntaxKind.ImportEqualsDeclaration || - (node.parent.kind === SyntaxKind.SourceFile && isExternalModule(currentSourceFile))) { + (node.parent.kind === SyntaxKind.SourceFile && isCurrentFileExternalModule)) { let isVisible: boolean; if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== SyntaxKind.SourceFile) { // Import declaration of another module that is visited async so lets put it in right spot @@ -593,7 +625,7 @@ namespace ts { function emitModuleElementDeclarationFlags(node: Node) { // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent === currentSourceFile) { + if (node.parent.kind === SyntaxKind.SourceFile) { // If the node is exported if (node.flags & NodeFlags.Export) { write("export "); @@ -602,24 +634,27 @@ namespace ts { if (node.flags & NodeFlags.Default) { write("default "); } - else if (node.kind !== SyntaxKind.InterfaceDeclaration) { + else if (node.kind !== SyntaxKind.InterfaceDeclaration && !noDeclare) { write("declare "); } } } - function emitClassMemberDeclarationFlags(node: Declaration) { - if (node.flags & NodeFlags.Private) { + function emitClassMemberDeclarationFlags(flags: NodeFlags) { + if (flags & NodeFlags.Private) { write("private "); } - else if (node.flags & NodeFlags.Protected) { + else if (flags & NodeFlags.Protected) { write("protected "); } - if (node.flags & NodeFlags.Static) { + if (flags & NodeFlags.Static) { write("static "); } - if (node.flags & NodeFlags.Abstract) { + if (flags & NodeFlags.Readonly) { + write("readonly "); + } + if (flags & NodeFlags.Abstract) { write("abstract "); } } @@ -632,7 +667,7 @@ namespace ts { write("export "); } write("import "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" = "); if (isInternalModuleImportEqualsDeclaration(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); @@ -640,12 +675,12 @@ namespace ts { } else { write("require("); - writeTextOfNode(currentSourceFile, getExternalModuleImportEqualsDeclarationExpression(node)); + emitExternalModuleSpecifier(node); write(");"); } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getImportEntityNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { return { diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -666,10 +701,6 @@ namespace ts { } function writeImportDeclaration(node: ImportDeclaration) { - if (!node.importClause && !(node.flags & NodeFlags.Export)) { - // do not write non-exported import declarations that don't have import clauses - return; - } emitJsDocComments(node); if (node.flags & NodeFlags.Export) { write("export "); @@ -678,7 +709,7 @@ namespace ts { if (node.importClause) { const currentWriterPos = writer.getTextPos(); if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentSourceFile, node.importClause.name); + writeTextOfNode(currentText, node.importClause.name); } if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { if (currentWriterPos !== writer.getTextPos()) { @@ -687,7 +718,7 @@ namespace ts { } if (node.importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { write("* as "); - writeTextOfNode(currentSourceFile, (node.importClause.namedBindings).name); + writeTextOfNode(currentText, (node.importClause.namedBindings).name); } else { write("{ "); @@ -697,17 +728,49 @@ namespace ts { } write(" from "); } - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); write(";"); writer.writeLine(); } + function emitExternalModuleSpecifier(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration) { + // emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations). + // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered + // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' + // so compiler will treat them as external modules. + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== SyntaxKind.ModuleDeclaration; + let moduleSpecifier: Node; + if (parent.kind === SyntaxKind.ImportEqualsDeclaration) { + const node = parent as ImportEqualsDeclaration; + moduleSpecifier = getExternalModuleImportEqualsDeclarationExpression(node); + } + else if (parent.kind === SyntaxKind.ModuleDeclaration) { + moduleSpecifier = (parent).name; + } + else { + const node = parent as (ImportDeclaration | ExportDeclaration); + moduleSpecifier = node.moduleSpecifier; + } + + if (moduleSpecifier.kind === SyntaxKind.StringLiteral && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + const moduleName = getExternalModuleNameFromDeclaration(host, resolver, parent); + if (moduleName) { + write('"'); + write(moduleName); + write('"'); + return; + } + } + + writeTextOfNode(currentText, moduleSpecifier); + } + function emitImportOrExportSpecifier(node: ImportOrExportSpecifier) { if (node.propertyName) { - writeTextOfNode(currentSourceFile, node.propertyName); + writeTextOfNode(currentText, node.propertyName); write(" as "); } - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } function emitExportSpecifier(node: ExportSpecifier) { @@ -733,7 +796,7 @@ namespace ts { } if (node.moduleSpecifier) { write(" from "); - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); } write(";"); writer.writeLine(); @@ -742,17 +805,27 @@ namespace ts { function writeModuleDeclaration(node: ModuleDeclaration) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & NodeFlags.Namespace) { - write("namespace "); + if (isGlobalScopeAugmentation(node)) { + write("global "); } else { - write("module "); + if (node.flags & NodeFlags.Namespace) { + write("namespace "); + } + else { + write("module "); + } + if (isExternalModuleAugmentation(node)) { + emitExternalModuleSpecifier(node); + } + else { + writeTextOfNode(currentText, node.name); + } } - writeTextOfNode(currentSourceFile, node.name); while (node.body.kind !== SyntaxKind.ModuleBlock) { node = node.body; write("."); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; @@ -772,7 +845,7 @@ namespace ts { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("type "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); emitTypeParameters(node.typeParameters); write(" = "); emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); @@ -780,7 +853,7 @@ namespace ts { writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { return { diagnosticMessage: Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -796,7 +869,7 @@ namespace ts { write("const "); } write("enum "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" {"); writeLine(); increaseIndent(); @@ -808,7 +881,7 @@ namespace ts { function emitEnumMemberDeclaration(node: EnumMember) { emitJsDocComments(node); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); const enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); @@ -827,7 +900,7 @@ namespace ts { increaseIndent(); emitJsDocComments(node); decreaseIndent(); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); // 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 "); @@ -847,7 +920,7 @@ namespace ts { } } - function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { // Type parameter constraints are named by user so we should always be able to name it let diagnosticMessage: DiagnosticMessage; switch (node.parent.kind) { @@ -916,8 +989,12 @@ namespace ts { else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) { write("null"); } + else { + writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer); + } - function getHeritageClauseVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getHeritageClauseVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { let diagnosticMessage: DiagnosticMessage; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { @@ -958,7 +1035,7 @@ namespace ts { } write("class "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -982,7 +1059,7 @@ namespace ts { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("interface "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -1003,7 +1080,7 @@ namespace ts { } emitJsDocComments(node); - emitClassMemberDeclarationFlags(node); + emitClassMemberDeclarationFlags(node.flags); emitVariableDeclaration(node); write(";"); writeLine(); @@ -1020,7 +1097,7 @@ namespace ts { // If this node is a computed name, it can only be a symbol, because we've already skipped // it if it's not a well known symbol. In that case, the text of the name will be exactly // what we want, namely the name expression enclosed in brackets. - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); // If optional property emit ? if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && hasQuestionToken(node)) { write("?"); @@ -1034,10 +1111,10 @@ namespace ts { } } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult: SymbolAccessiblityResult) { + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) { if (node.kind === SyntaxKind.VariableDeclaration) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; @@ -1046,30 +1123,30 @@ namespace ts { else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) { // TODO(jfreeman): Deal with computed properties in error reporting. if (node.flags & NodeFlags.Static) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } else if (node.parent.kind === SyntaxKind.ClassDeclaration) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; } else { // Interfaces cannot have types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; } } } - function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, @@ -1093,8 +1170,8 @@ namespace ts { } function emitBindingElement(bindingElement: BindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getBindingElementTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: bindingElement, @@ -1107,7 +1184,7 @@ namespace ts { emitBindingPattern(bindingElement.name); } else { - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError); } } @@ -1156,8 +1233,8 @@ namespace ts { if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node); - writeTextOfNode(currentSourceFile, node.name); + emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : NodeFlags.Readonly)); + writeTextOfNode(currentText, node.name); if (!(node.flags & NodeFlags.Private)) { accessorWithTypeAnnotation = node; let type = getTypeAnnotationFromAccessor(node); @@ -1185,17 +1262,17 @@ namespace ts { } } - function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { let diagnosticMessage: DiagnosticMessage; if (accessorWithTypeAnnotation.kind === SyntaxKind.SetAccessor) { // Setters have to have type named and cannot infer it so, the type should always be named if (accessorWithTypeAnnotation.parent.flags & NodeFlags.Static) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; } @@ -1208,15 +1285,15 @@ namespace ts { } else { if (accessorWithTypeAnnotation.flags & NodeFlags.Static) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; @@ -1242,18 +1319,18 @@ namespace ts { if (node.kind === SyntaxKind.FunctionDeclaration) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === SyntaxKind.MethodDeclaration) { - emitClassMemberDeclarationFlags(node); + else if (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.Constructor) { + emitClassMemberDeclarationFlags(node.flags); } if (node.kind === SyntaxKind.FunctionDeclaration) { write("function "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } else if (node.kind === SyntaxKind.Constructor) { write("constructor"); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); if (hasQuestionToken(node)) { write("?"); } @@ -1268,21 +1345,23 @@ namespace ts { } function emitSignatureDeclaration(node: SignatureDeclaration) { - // Construct signature or constructor type write new Signature - if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) { - write("new "); - } - emitTypeParameters(node.typeParameters); + const prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + if (node.kind === SyntaxKind.IndexSignature) { + // Index signature can have readonly modifier + emitClassMemberDeclarationFlags(node.flags); write("["); } else { + // Construct signature or constructor type write new Signature + if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) { + write("new "); + } + emitTypeParameters(node.typeParameters); write("("); } - const prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - // Parameters emitCommaList(node.parameters, emitParameterDeclaration); @@ -1313,26 +1392,26 @@ namespace ts { writeLine(); } - function getReturnTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getReturnTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { let diagnosticMessage: DiagnosticMessage; switch (node.kind) { case SyntaxKind.ConstructSignature: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; case SyntaxKind.CallSignature: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; case SyntaxKind.IndexSignature: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; @@ -1340,30 +1419,30 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: if (node.flags & NodeFlags.Static) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } else if (node.parent.kind === SyntaxKind.ClassDeclaration) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; } else { // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; case SyntaxKind.FunctionDeclaration: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; @@ -1393,7 +1472,7 @@ namespace ts { emitBindingPattern(node.name); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } if (resolver.isOptionalParameter(node)) { write("?"); @@ -1409,8 +1488,8 @@ namespace ts { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } - function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, @@ -1418,53 +1497,53 @@ namespace ts { } : undefined; } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult: SymbolAccessiblityResult): DiagnosticMessage { + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult): DiagnosticMessage { switch (node.parent.kind) { case SyntaxKind.Constructor: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; case SyntaxKind.ConstructSignature: // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; case SyntaxKind.CallSignature: // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: if (node.parent.flags & NodeFlags.Static) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } case SyntaxKind.FunctionDeclaration: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; @@ -1493,14 +1572,6 @@ namespace ts { } function emitBindingElement(bindingElement: BindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } if (bindingElement.kind === SyntaxKind.OmittedExpression) { // If bindingElement is an omittedExpression (i.e. containing elision), @@ -1519,7 +1590,7 @@ namespace ts { // Example: // original: function foo({y: [a,b,c]}) {} // emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void; - writeTextOfNode(currentSourceFile, bindingElement.propertyName); + writeTextOfNode(currentText, bindingElement.propertyName); write(": "); } if (bindingElement.name) { @@ -1542,7 +1613,7 @@ namespace ts { if (bindingElement.dotDotDotToken) { write("..."); } - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); } } } @@ -1589,34 +1660,58 @@ namespace ts { } } - function writeReferencePath(referencedFile: SourceFile) { - let declFileName = referencedFile.flags & NodeFlags.DeclarationFile - ? referencedFile.fileName // Declaration file, use declaration file name - : shouldEmitToOwnFile(referencedFile, compilerOptions) - ? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file - : removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; // Global out file + /** + * Adds the reference to referenced file, returns true if global file reference was emitted + * @param referencedFile + * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not + */ + function writeReferencePath(referencedFile: SourceFile, addBundledFileReference: boolean): boolean { + let declFileName: string; + let addedBundledEmitReference = false; + if (isDeclarationFile(referencedFile)) { + // Declaration file, use declaration file name + declFileName = referencedFile.fileName; + } + else { + // Get the declaration file path + forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + } - declFileName = getRelativePathToDirectoryOrUrl( - getDirectoryPath(normalizeSlashes(jsFilePath)), - declFileName, - host.getCurrentDirectory(), - host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ false); + if (declFileName) { + declFileName = getRelativePathToDirectoryOrUrl( + getDirectoryPath(normalizeSlashes(declarationFilePath)), + declFileName, + host.getCurrentDirectory(), + host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); - referencePathsOutput += "/// " + newLine; + referencePathsOutput += '/// ' + newLine; + } + return addedBundledEmitReference; + + function getDeclFileName(emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) { + // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path + if (isBundledEmit && !addBundledFileReference) { + return; + } + + Debug.assert(!!emitFileNames.declarationFilePath || isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); + declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; + addedBundledEmitReference = isBundledEmit; + } } } /* @internal */ - export function writeDeclarationFile(jsFilePath: string, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[]) { - const emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); - // TODO(shkamat): Should we not write any declaration file if any of them can produce error, - // or should we just not write this file like we are doing now - if (!emitDeclarationResult.reportedDeclarationError) { + export function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection) { + const emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + const emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; + if (!emitSkipped) { const declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - writeFile(host, diagnostics, removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } + return emitSkipped; function getDeclarationOutput(synchronousDeclarationOutput: string, moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]) { let appliedSyncOutputPos = 0; diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index be75c549825..39a60f73da0 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1,4 +1,4 @@ - { +{ "Unterminated string literal.": { "category": "Error", "code": 1002 @@ -67,6 +67,10 @@ "category": "Error", "code": 1023 }, + "'readonly' modifier can only appear on a property declaration or index signature.": { + "category": "Error", + "code": 1024 + }, "Accessibility modifier already seen.": { "category": "Error", "code": 1028 @@ -119,7 +123,7 @@ "category": "Error", "code": 1043 }, - "'{0}' modifier cannot appear on a module element.": { + "'{0}' modifier cannot appear on a module or namespace element.": { "category": "Error", "code": 1044 }, @@ -195,6 +199,10 @@ "category": "Error", "code": 1063 }, + "The return type of an async function or method must be the global Promise type.": { + "category": "Error", + "code": 1064 + }, "In ambient enum declarations member initializer must be constant expression.": { "category": "Error", "code": 1066 @@ -203,6 +211,14 @@ "category": "Error", "code": 1068 }, + "'{0}' modifier cannot appear on a type member.": { + "category": "Error", + "code": 1070 + }, + "'{0}' modifier cannot appear on an index signature.": { + "category": "Error", + "code": 1071 + }, "A '{0}' modifier cannot be used with an import declaration.": { "category": "Error", "code": 1079 @@ -423,10 +439,6 @@ "category": "Error", "code": 1144 }, - "Modifiers not permitted on index signature members.": { - "category": "Error", - "code": 1145 - }, "Declaration expected.": { "category": "Error", "code": 1146 @@ -435,7 +447,7 @@ "category": "Error", "code": 1147 }, - "Cannot compile modules unless the '--module' flag is provided.": { + "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file.": { "category": "Error", "code": 1148 }, @@ -675,7 +687,7 @@ "category": "Error", "code": 1218 }, - "Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning.": { + "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.": { "category": "Error", "code": 1219 }, @@ -767,7 +779,7 @@ "category": "Error", "code": 1241 }, - "'abstract' modifier can only appear on a class or method declaration.": { + "'abstract' modifier can only appear on a class, method, or property declaration.": { "category": "Error", "code": 1242 }, @@ -783,7 +795,22 @@ "category": "Error", "code": 1245 }, - + "An interface property cannot have an initializer.": { + "category": "Error", + "code": 1246 + }, + "A type literal property cannot have an initializer.": { + "category": "Error", + "code": 1247 + }, + "A class member cannot have the '{0}' keyword.": { + "category": "Error", + "code": 1248 + }, + "A decorator can only decorate a method implementation, not an overload.": { + "category": "Error", + "code": 1249 + }, "'with' statements are not allowed in an async function block.": { "category": "Error", "code": 1300 @@ -804,6 +831,18 @@ "category": "Error", "code": 1313 }, + "Global module exports may only appear in module files.": { + "category": "Error", + "code": 1314 + }, + "Global module exports may only appear in declaration files.": { + "category": "Error", + "code": 1315 + }, + "Global module exports may only appear at top level.": { + "category": "Error", + "code": 1316 + }, "Duplicate identifier '{0}'.": { "category": "Error", "code": 2300 @@ -836,6 +875,10 @@ "category": "Error", "code": 2307 }, + "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity.": { + "category": "Error", + "code": 2308 + }, "An export assignment cannot be used in a module with other exported elements.": { "category": "Error", "code": 2309 @@ -852,7 +895,7 @@ "category": "Error", "code": 2312 }, - "Constraint of a type parameter cannot reference any type parameter from the same type parameter list.": { + "Type parameter '{0}' has a circular constraint.": { "category": "Error", "code": 2313 }, @@ -892,7 +935,7 @@ "category": "Error", "code": 2322 }, - "Type '{0}' is not comparable to type '{1}'.": { + "Cannot redeclare exported variable '{0}'.": { "category": "Error", "code": 2323 }, @@ -1060,6 +1103,10 @@ "category": "Error", "code": 2365 }, + "Function lacks ending return statement and return type does not include 'undefined'.": { + "category": "Error", + "code": 2366 + }, "Type parameter name cannot be '{0}'": { "category": "Error", "code": 2368 @@ -1120,7 +1167,7 @@ "category": "Error", "code": 2382 }, - "Overload signatures must all be exported or not exported.": { + "Overload signatures must all be exported or non-exported.": { "category": "Error", "code": 2383 }, @@ -1176,6 +1223,10 @@ "category": "Error", "code": 2396 }, + "Declaration name conflicts with built-in global identifier '{0}'.": { + "category": "Error", + "code": 2397 + }, "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.": { "category": "Error", "code": 2399 @@ -1248,10 +1299,6 @@ "category": "Error", "code": 2417 }, - "Type name '{0}' in extends clause does not reference constructor function for '{0}'.": { - "category": "Error", - "code": 2419 - }, "Class '{0}' incorrectly implements interface '{1}'.": { "category": "Error", "code": 2420 @@ -1280,7 +1327,7 @@ "category": "Error", "code": 2427 }, - "All declarations of an interface must have identical type parameters.": { + "All declarations of '{0}' must have identical type parameters.": { "category": "Error", "code": 2428 }, @@ -1360,11 +1407,11 @@ "category": "Error", "code": 2448 }, - "The operand of an increment or decrement operator cannot be a constant.": { + "The operand of an increment or decrement operator cannot be a constant or a read-only property.": { "category": "Error", "code": 2449 }, - "Left-hand side of assignment expression cannot be a constant.": { + "Left-hand side of assignment expression cannot be a constant or a read-only property.": { "category": "Error", "code": 2450 }, @@ -1380,6 +1427,10 @@ "category": "Error", "code": 2453 }, + "Variable '{0}' is used before being assigned.": { + "category": "Error", + "code": 2454 + }, "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'.": { "category": "Error", "code": 2455 @@ -1496,11 +1547,11 @@ "category": "Error", "code": 2484 }, - "The left-hand side of a 'for...of' statement cannot be a previously defined constant.": { + "The left-hand side of a 'for...of' statement cannot be a constant or a read-only property.": { "category": "Error", "code": 2485 }, - "The left-hand side of a 'for...in' statement cannot be a previously defined constant.": { + "The left-hand side of a 'for...in' statement cannot be a constant or a read-only property.": { "category": "Error", "code": 2486 }, @@ -1604,7 +1655,7 @@ "category": "Error", "code": 2511 }, - "Overload signatures must all be abstract or not abstract.": { + "Overload signatures must all be abstract or non-abstract.": { "category": "Error", "code": 2512 }, @@ -1626,7 +1677,11 @@ }, "Cannot assign an abstract constructor type to a non-abstract constructor type.": { "category": "Error", - "code":2517 + "code": 2517 + }, + "A 'this'-based type guard is not compatible with a parameter-based type guard.": { + "category": "Error", + "code": 2518 }, "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions.": { "category": "Error", @@ -1664,7 +1719,19 @@ "category": "Error", "code": 2528 }, - "JSX element attributes type '{0}' must be an object type.": { + "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions.": { + "category": "Error", + "code": 2529 + }, + "Property '{0}' is incompatible with index signature.": { + "category": "Error", + "code": 2530 + }, + "Object is possibly 'null' or 'undefined'.": { + "category": "Error", + "code": 2531 + }, + "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 }, @@ -1728,6 +1795,90 @@ "category": "Error", "code": 2657 }, + "Type '{0}' provides no match for the signature '{1}'": { + "category": "Error", + "code": 2658 + }, + "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher.": { + "category": "Error", + "code": 2659 + }, + "'super' can only be referenced in members of derived classes or object literal expressions.": { + "category": "Error", + "code": 2660 + }, + "Cannot re-export name that is not defined in the module.": { + "category": "Error", + "code": 2661 + }, + "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?": { + "category": "Error", + "code": 2662 + }, + "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?": { + "category": "Error", + "code": 2663 + }, + "Invalid module name in augmentation, module '{0}' cannot be found.": { + "category": "Error", + "code": 2664 + }, + "Module augmentation cannot introduce new names in the top level scope.": { + "category": "Error", + "code": 2665 + }, + "Exports and export assignments are not permitted in module augmentations.": { + "category": "Error", + "code": 2666 + }, + "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module.": { + "category": "Error", + "code": 2667 + }, + "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible.": { + "category": "Error", + "code": 2668 + }, + "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.": { + "category": "Error", + "code": 2669 + }, + "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context.": { + "category": "Error", + "code": 2670 + }, + "Cannot augment module '{0}' because it resolves to a non-module entity.": { + "category": "Error", + "code": 2671 + }, + "Cannot assign a '{0}' constructor type to a '{1}' constructor type.": { + "category": "Error", + "code": 2672 + }, + "Constructor of class '{0}' is private and only accessible within the class declaration.": { + "category": "Error", + "code": 2673 + }, + "Constructor of class '{0}' is protected and only accessible within the class declaration.": { + "category": "Error", + "code": 2674 + }, + "Cannot extend a class '{0}'. Class constructor is marked as private.": { + "category": "Error", + "code": 2675 + }, + "Accessors must both be abstract or non-abstract.": { + "category": "Error", + "code": 2676 + }, + "A type predicate's type must be assignable to its parameter's type.": { + "category": "Error", + "code": 2677 + }, + "Type '{0}' is not comparable to type '{1}'.": { + "category": "Error", + "code": 2678 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", "code": 4000 @@ -2064,6 +2215,38 @@ "category": "Error", "code": 5054 }, + "Cannot write file '{0}' because it would overwrite input file.": { + "category": "Error", + "code": 5055 + }, + "Cannot write file '{0}' because it would be overwritten by multiple input files.": { + "category": "Error", + "code": 5056 + }, + "Cannot find a tsconfig.json file at the specified directory: '{0}'": { + "category": "Error", + "code": 5057 + }, + "The specified path does not exist: '{0}'": { + "category": "Error", + "code": 5058 + }, + "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier.": { + "category": "Error", + "code": 5059 + }, + "Option 'paths' cannot be used without specifying '--baseUrl' option.": { + "category": "Error", + "code": 5060 + }, + "Pattern '{0}' can have at most one '*' character": { + "category": "Error", + "code": 5061 + }, + "Substitution '{0}' in pattern '{1}' in can have at most one '*' character": { + "category": "Error", + "code": 5062 + }, "Concatenate and emit output to single file.": { "category": "Message", @@ -2073,11 +2256,11 @@ "category": "Message", "code": 6002 }, - "Specifies the location where debugger should locate map files instead of generated locations.": { + "Specify the location where debugger should locate map files instead of generated locations.": { "category": "Message", "code": 6003 }, - "Specifies the location where debugger should locate TypeScript files instead of source locations.": { + "Specify the location where debugger should locate TypeScript files instead of source locations.": { "category": "Message", "code": 6004 }, @@ -2105,10 +2288,14 @@ "category": "Message", "code": 6010 }, - "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)": { - "category": "Message", - "code": 6015 - }, + "Allow default imports from modules with no default export. This does not affect code emit, just typechecking.": { + "category": "Message", + "code": 6011 + }, + "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'": { + "category": "Message", + "code": 6015 + }, "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'": { "category": "Message", "code": 6016 @@ -2193,14 +2380,10 @@ "category": "Error", "code": 6045 }, - "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', or 'es2015'.": { + "Argument for '{0}' option must be: {1}": { "category": "Error", "code": 6046 }, - "Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'.": { - "category": "Error", - "code": 6047 - }, "Locale must be of the form or -. For example '{0}' or '{1}'.": { "category": "Error", "code": 6048 @@ -2237,7 +2420,7 @@ "category": "Message", "code": 6056 }, - "Specifies the root directory of input files. Use to control the output directory structure with --outDir.": { + "Specify the root directory of input files. Use to control the output directory structure with --outDir.": { "category": "Message", "code": 6058 }, @@ -2245,7 +2428,7 @@ "category": "Error", "code": 6059 }, - "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).": { + "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).": { "category": "Message", "code": 6060 }, @@ -2253,15 +2436,10 @@ "category": "Message", "code": 6061 }, - "Argument for '--newLine' option must be 'CRLF' or 'LF'.": { + "Option '{0}' can only be specified in 'tsconfig.json' file.": { "category": "Error", - "code": 6062 + "code": 6064 }, - "Argument for '--moduleResolution' option must be 'node' or 'classic'.": { - "category": "Error", - "code": 6063 - }, - "Enables experimental support for ES7 decorators.": { "category": "Message", "code": 6065 @@ -2274,7 +2452,7 @@ "category": "Message", "code": 6068 }, - "Specifies module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).": { + "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).": { "category": "Message", "code": 6069 }, @@ -2314,14 +2492,141 @@ "category": "Message", "code": 6078 }, - "Specify JSX code generation: 'preserve' or 'react'": { "category": "Message", "code": 6080 }, - "Argument for '--jsx' must be 'preserve' or 'react'.": { + "Only 'amd' and 'system' modules are supported alongside --{0}.": { + "category": "Error", + "code": 6082 + }, + "Base directory to resolve non-absolute module names.": { "category": "Message", - "code": 6081 + "code": 6083 + }, + "Specify the object invoked for createElement and __spread when targeting 'react' JSX emit": { + "category": "Message", + "code": 6084 + }, + "Enable tracing of the module resolution process.": { + "category": "Message", + "code": 6085 + }, + "======== Resolving module '{0}' from '{1}'. ========": { + "category": "Message", + "code": 6086 + }, + "Explicitly specified module resolution kind: '{0}'.": { + "category": "Message", + "code": 6087 + }, + "Module resolution kind is not specified, using '{0}'.": { + "category": "Message", + "code": 6088 + }, + "======== Module name '{0}' was successfully resolved to '{1}'. ========": { + "category": "Message", + "code": 6089 + }, + "======== Module name '{0}' was not resolved. ========": { + "category": "Message", + "code": 6090 + }, + "'paths' option is specified, looking for a pattern to match module name '{0}'.": { + "category": "Message", + "code": 6091 + }, + "Module name '{0}', matched pattern '{1}'.": { + "category": "Message", + "code": 6092 + }, + "Trying substitution '{0}', candidate module location: '{1}'.": { + "category": "Message", + "code": 6093 + }, + "Resolving module name '{0}' relative to base url '{1}' - '{2}'.": { + "category": "Message", + "code": 6094 + }, + "Loading module as file / folder, candidate module location '{0}'.": { + "category": "Message", + "code": 6095 + }, + "File '{0}' does not exist.": { + "category": "Message", + "code": 6096 + }, + "File '{0}' exist - use it as a module resolution result.": { + "category": "Message", + "code": 6097 + }, + "Loading module '{0}' from 'node_modules' folder.": { + "category": "Message", + "code": 6098 + }, + "Found 'package.json' at '{0}'.": { + "category": "Message", + "code": 6099 + }, + "'package.json' does not have 'typings' field.": { + "category": "Message", + "code": 6100 + }, + "'package.json' has 'typings' field '{0}' that references '{1}'.": { + "category": "Message", + "code": 6101 + }, + "Allow javascript files to be compiled.": { + "category": "Message", + "code": 6102 + }, + "Option '{0}' should have array of strings as a value.": { + "category": "Error", + "code": 6103 + }, + "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'.": { + "category": "Message", + "code": 6104 + }, + "Expected type of 'typings' field in 'package.json' to be 'string', got '{0}'.": { + "category": "Message", + "code": 6105 + }, + "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'": { + "category": "Message", + "code": 6106 + }, + "'rootDirs' option is set, using it to resolve relative module name '{0}'": { + "category": "Message", + "code": 6107 + }, + "Longest matching prefix for '{0}' is '{1}'": { + "category": "Message", + "code": 6108 + }, + "Loading '{0}' from the root dir '{1}', candidate location '{2}'": { + "category": "Message", + "code": 6109 + }, + "Trying other entries in 'rootDirs'": { + "category": "Message", + "code": 6110 + }, + "Module resolution using 'rootDirs' has failed": { + "category": "Message", + "code": 6111 + }, + "Do not emit 'use strict' directives in module output.": { + "category": "Message", + "code": 6112 + }, + "Enable strict null checks.": { + "category": "Message", + "code": 6113 + }, + "Unknown option 'excludes'. Did you mean 'exclude'?": { + "category": "Error", + "code": 6114 }, "Variable '{0}' implicitly has an '{1}' type.": { @@ -2352,6 +2657,10 @@ "category": "Error", "code": 7013 }, + "Element implicitly has an 'any' type because index expression is not of type 'number'.": { + "category": "Error", + "code": 7015 + }, "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation.": { "category": "Error", "code": 7016 @@ -2407,7 +2716,7 @@ "Not all code paths return a value.": { "category": "Error", "code": 7030 - }, + }, "You cannot rename this element.": { "category": "Error", "code": 8000 @@ -2472,11 +2781,6 @@ "category": "Error", "code": 8016 }, - "'decorators' can only be used in a .ts file.": { - "category": "Error", - "code": 8017 - }, - "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses.": { "category": "Error", "code": 9002 @@ -2506,15 +2810,27 @@ "code": 17004 }, "A constructor cannot contain a 'super' call when its class extends 'null'": { - "category": "Error", - "code": 17005 + "category": "Error", + "code": 17005 }, "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.": { - "category": "Error", - "code": 17006 + "category": "Error", + "code": 17006 }, "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.": { - "category": "Error", - "code": 17007 + "category": "Error", + "code": 17007 + }, + "JSX element '{0}' has no corresponding closing tag.": { + "category": "Error", + "code": 17008 + }, + "'super' must be called before accessing 'this' in the constructor of a derived class.": { + "category": "Error", + "code": 17009 + }, + "Unknown typing option '{0}'.": { + "category": "Error", + "code": 17010 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 464bd51a91d..0cb28a72a67 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1,10 +1,19 @@ /// +/// /// /* @internal */ namespace ts { - export function isExternalModuleOrDeclarationFile(sourceFile: SourceFile) { - return isExternalModule(sourceFile) || isDeclarationFile(sourceFile); + export function getResolvedExternalModuleName(host: EmitHost, file: SourceFile): string { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + } + + export function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): string { + const file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); } type DependencyGroup = Array; @@ -278,6 +287,54 @@ namespace ts { _i = 0x10000000, // Use/preference flag for '_i' } + const enum CopyDirection { + ToOriginal, + ToOutParameter + } + + /** + * If loop contains block scoped binding captured in some function then loop body is converted to a function. + * Lexical bindings declared in loop initializer will be passed into the loop body function as parameters, + * however if this binding is modified inside the body - this new value should be propagated back to the original binding. + * This is done by declaring new variable (out parameter holder) outside of the loop for every binding that is reassigned inside the body. + * On every iteration this variable is initialized with value of corresponding binding. + * At every point where control flow leaves the loop either explicitly (break/continue) or implicitly (at the end of loop body) + * we copy the value inside the loop to the out parameter holder. + * + * for (let x;;) { + * let a = 1; + * let b = () => a; + * x++ + * if (...) break; + * ... + * } + * + * will be converted to + * + * var out_x; + * var loop = function(x) { + * var a = 1; + * var b = function() { return a; } + * x++; + * if (...) return out_x = x, "break"; + * ... + * out_x = x; + * } + * for (var x;;) { + * out_x = x; + * var state = loop(x); + * x = out_x; + * if (state === "break") break; + * } + * + * NOTE: values to out parameters are not copies if loop is abrupted with 'return' - in this case this will end the entire enclosing function + * so nobody can observe this new value. + */ + interface LoopOutParameter { + originalName: Identifier; + outParamName: string; + } + // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult { // emit output for the __extends helper function @@ -310,58 +367,29 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { };`; const awaiterHelper = ` -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) { - return new Promise(function (resolve, reject) { - generator = generator.call(thisArg, _arguments); - function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); } - function onfulfill(value) { try { step("next", value); } catch (e) { reject(e); } } - function onreject(value) { try { step("throw", value); } catch (e) { reject(e); } } - function step(verb, value) { - var result = generator[verb](value); - result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject); - } - step("next", void 0); +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments)).next()); }); };`; const compilerOptions = host.getCompilerOptions(); - const languageVersion = compilerOptions.target || ScriptTarget.ES3; - const modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; + const languageVersion = getEmitScriptTarget(compilerOptions); + const modulekind = getEmitModuleKind(compilerOptions); const sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - let diagnostics: Diagnostic[] = []; + const emitterDiagnostics = createDiagnosticCollection(); + let emitSkipped = false; const newLine = host.getNewLine(); - const jsxDesugaring = host.getCompilerOptions().jsx !== JsxEmit.Preserve; - const shouldEmitJsx = (s: SourceFile) => (s.languageVariant === LanguageVariant.JSX && !jsxDesugaring); - if (targetSourceFile === undefined) { - forEach(host.getSourceFiles(), sourceFile => { - if (shouldEmitToOwnFile(sourceFile, compilerOptions)) { - const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - - if (compilerOptions.outFile || compilerOptions.out) { - emitFile(compilerOptions.outFile || compilerOptions.out); - } - } - else { - // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) - if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - const jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) { - emitFile(compilerOptions.outFile || compilerOptions.out); - } - } - - // Sort and make the unique list of diagnostics - diagnostics = sortAndDeduplicateDiagnostics(diagnostics); + const emitJavaScript = createFileEmitter(); + forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { - emitSkipped: false, - diagnostics, + emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), sourceMaps: sourceMapDataList }; @@ -379,14 +407,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi interface ConvertedLoopState { /* - * set of labels that occured inside the converted loop + * set of labels that occurred inside the converted loop * used to determine if labeled jump can be emitted as is or it should be dispatched to calling code */ labels?: Map; /* * collection of labeled jumps that transfer control outside the converted loop. * maps store association 'label -> labelMarker' where - * - label - value of label as it apprear in code + * - label - value of label as it appear in code * - label marker - return value that should be interpreted by calling code as 'jump to